Post

Google Apps Script|Automate Gmail Forwarding to Slack Channels with Custom Filters

Discover how to use Gmail Filters combined with Google Apps Script to automatically forward customized email content to your Slack channels, streamlining communication and saving time.

Google Apps Script|Automate Gmail Forwarding to Slack Channels with Custom Filters

点击这里查看本文章简体中文版本。

點擊這裡查看本文章正體中文版本。

This post was translated with AI assistance — let me know if anything sounds off!


Using Google Apps Script to Forward Gmail Emails to Slack

Using Gmail Filter + Google Apps Script to Automatically Forward Customized Content to a Slack Channel When Receiving Emails

Photo by [Lukas Blazek](https://unsplash.com/@goumbik?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText){:target="_blank"}

Photo by Lukas Blazek

Origin

Recently, I have been optimizing the iOS App CI/CD process using Fastlane as the automation tool. After packaging and uploading, if you want to continue with the automatic submission step (skip_submission=false), you need to wait for Apple to complete the processing, which takes about 30-40 minutes of CI server time. Since Apple’s App Store Connect API is not fully developed, Fastlane can only check once per minute whether the uploaded build has finished processing, which wastes a lot of resources.

  • Bitrise CI Server: Limits the number of simultaneous builds and sets a maximum runtime of 90 minutes. While 90 minutes is sufficient, a single build can block others from running.

  • Travis CI Server: Charged based on Build Time, so you can’t afford to wait—money goes down the drain.

A Different Approach

No waiting, end immediately after upload! Trigger subsequent actions based on the processed email notification.

However, I haven’t received this email recently. I’m not sure if it’s a settings issue or if Apple has stopped sending such notifications.

This article will use the Testflight email notification that testing can now begin as an example.

The complete process is shown in the above image and is feasible in principle; however, this article will focus on receiving emails and using Apps Script to forward them to a Slack channel.

How to Forward Received Emails to a Slack Channel

Both paid and free Slack plans can use different methods to forward emails to Slack Channels or DMs.

You can refer to the official documentation for setup: Send emails to Slack

The results are the same regardless of the method:

By default, the email content is collapsed. Click to expand and view the full content.

Advantages:

  1. Simple and Fast

  2. Zero Technical Barrier

  3. Real-time forwarding

Disadvantages:

  1. Cannot customize content

  2. Display style cannot be changed

Custom Forwarded Content

This is the main focus of this article.

Translate the email content data into your desired presentation style, as shown in the example image above.

Here is a complete workflow diagram:

  • Using Gmail Filter to Add Identification Labels for Forwarded Emails

  • Apps Script to Periodically Fetch Emails Tagged with a Specific Label

  • Read email content

  • Render the desired display style

  • Send messages to Slack via Slack Bot API or directly using Incoming Message

  • Remove Email Label (Indicates Forwarded)

  • Completed

First, create a filter in Gmail

Filters can automate actions when receiving emails that meet certain criteria, such as: automatically marking as read, tagging, moving to spam, categorizing, and more.

In Gmail, click the advanced search icon button at the top right, enter the forwarding email rule conditions, such as From: no_reply@email.apple.com + Subject contains is now available to test., then click “Search” to check if the filter results are as expected; if correct, click the “Create filter” button next to Search.

Or directly click "Filter messages like these" at the top of the email to quickly create filter rules

Or simply click “Filter messages like these” at the top of the email to quickly create a filter.

This button design is very user-unfriendly; I couldn’t find it the first time.

Next, set the action for emails that meet this filter condition. Here, select “Apply the label” and create a new label named “forward-to-slack.” Then click “Create filter” to finish.

Emails labeled with this tag will be forwarded to Slack.

Get Incoming WebHooks App URL

First, we need to add the Incoming WebHooks App to the Slack Channel. We will use this to send messages.

  1. Slack bottom left corner “Apps” -> “Add apps”

  2. Search for “incoming” in the search box on the right.

  3. Click “Incoming WebHooks” -> “Add”

Select the Channel where you want to send the message.

Note down the “Webhook URL” at the top.

Scroll down to set the name and avatar displayed when sending messages from the Bot; remember to click “Save Settings” after making changes.

Note

Please note that the official recommendation is to use the new Slack APP Bot API’s chat.postMessage to send messages. The simpler Incoming Webhook method will be deprecated in the future. This guide uses the old method for convenience but will need to switch to the new Slack App API in the next chapter, “Import Employee List.”

Writing Apps Script Code

Paste the basic code below and modify it to your desired version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function sendMessageToSlack(content) {
    var payload = {
      "text": "*You have received an email*",
      "attachments": [{
          "pretext": "Email content as follows:",
          "text": content,
        }
      ]
    };
    var res = UrlFetchApp.fetch('貼上你的Slack incoming Webhook URL',{
      method             : 'post',
      contentType        : 'application/json',
      payload            : JSON.stringify(payload)
    })
}

function forwardEmailsToSlack() {
    // Reference: https://gist.github.com/andrewmwilson/5cab8367dc63d87d9aa5

    var label = GmailApp.getUserLabelByName('forward-to-slack');
    var messages = [];
    var threads = label.getThreads();
  
    if (threads == null) {
      return;
    }

    for (var i = 0; i < threads.length; i++) {
        messages = messages.concat(threads[i].getMessages())
    }

    for (var i = 0; i < messages.length; i++) {
        var message = messages[i];
        Logger.log(message);

        var output = '*New Email*';
        output += '\n*from:* ' + message.getFrom();
        output += '\n*to:* ' + message.getTo();
        output += '\n*cc:* ' + message.getCc();
        output += '\n*date:* ' + message.getDate();
        output += '\n*subject:* ' + message.getSubject();
        output += '\n*body:* ' + message.getPlainBody();

        sendMessageToSlack(output);
   }

   label.removeFromThreads(threads);
}

Advanced:

EX: Extracting version number information from Testflight approval emails:

Email Subject: Your app XXX has been approved for beta testing.

Email content:

We want to get the values after Bundle Version Short String and Build Number.

1
2
3
4
5
6
7
var results = subject.match(/(Bundle Version Short String: ){1}(\S+){1}[\S\s]*(Build Number: ){1}(\S+){1}/);
if (results == null \\|\\| results.length != 5) {
  // not valid
} else {
  var version = results[2];
  var build = results[4];
}

Give it a try

  • Go back to Gmail and manually add the label “forward-to-slack” to any email.

  • In the Apps Script code editor, select “forwardEmailsToSlack” and then click the “Run” button

If “Authorization Required” appears, click “Continue” to complete the verification.

During the authentication process, the message “Google hasn’t verified this app” may appear. This is normal because the App Script we wrote has not been verified by Google. However, it’s fine since this is for personal use.

You can click the bottom left corner “Advanced” -> “Go to ForwardEmailsToSlack (unsafe)”

Click “Allow”

Forwarded successfully!!!

Set Up Trigger (Schedule) for Automatic Checking & Forwarding

In the left menu of Apps Script, select “Triggers”.

Bottom left corner “+ Add Trigger Condition”.

  • Error Notification Settings: You can set how to notify you when the script encounters an error during execution

  • Choose the function you want to execute: Select Main Function sendMessageToSlack

  • Select Activity Source: You can choose from Calendar or Time-Driven (Scheduled or Specified)

  • Select time-based trigger type: choose to execute on a specific date or once every minute/hour/day/week/month

  • Select interval by minute/hour/day/week/month: e.g., every minute, every 15 minutes…

Here, for demonstration, it is set to run every minute. I think checking emails once every hour is sufficient for real-time needs.

  • Go back to Gmail and pick any email, then manually add the label — “forward-to-slack”

  • Waiting for schedule trigger

Automatic Check & Forward Successful!

Completion

With this feature, you can achieve customized email forwarding and processing, or even use it as a trigger—for example, automatically running a script when receiving an email from XXX.

Returning to Chapter 1 Origin, we can use this mechanism to improve the CI/CD process; no need to wait idly for Apple to finish processing, and we can integrate automation workflows!

Further Reading

If you have any questions or feedback, feel free to contact me.


Buy me a beer

This post was originally published on Medium (View original post), and automatically converted and synced by ZMediumToMarkdown.

Improve this page on Github.

This post is licensed under CC BY 4.0 by the author.