Home Using Google Apps Script to Forward Gmail Emails to Slack
Post
Cancel

Using Google Apps Script to Forward Gmail Emails to Slack

Using Google Apps Script to Forward Gmail Emails to Slack

Use Gmail Filter + Google Apps Script to automatically forward customized content to 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 CI/CD process for an iOS App, using Fastlane as an 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 process, which takes about 30-40 mins of CI Server time. Because Apple’s App Store Connect API is not perfect, Fastlane can only check once per minute if the uploaded build is processed, which is very resource-wasting.

  • Bitrise CI Server: Limits the number of simultaneous builds and the maximum execution time to 90 mins. 90 mins is enough, but it will block one build, hindering others from executing.
  • Travis CI Server: Charges based on build time, so waiting is not an option, as money would be wasted.

A Different Approach

No more waiting. End it right after uploading! Use the email notification of completion to trigger subsequent actions.

However, I haven’t received this email recently. I don’t know if it’s a setting issue or if Apple no longer sends this type of notification.

This article will use the email notification that Testflight is ready for testing as an example.

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

How to Forward Received Emails to Slack Channel

Whether it’s a paid or free Slack project, different methods can be used to achieve the function of forwarding emails to a Slack Channel or DM.

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

The effect is the same regardless of the method used:

Default collapsed email content, click to expand and view all content.

Advantages:

  1. Simple and fast
  2. Zero technical threshold
  3. Instant forwarding

Disadvantages:

  1. Cannot customize content
  2. Display style cannot be changed

Custom Forwarding Content

This is the main focus of this article.

Translate the email content data into the style you want to present, as shown in the example above.

First, a complete workflow diagram:

  • Use Gmail Filter to add a recognition label to the email to be forwarded
  • Apps Script regularly fetches emails marked with that label
  • Read the email content
  • Render into the desired display style
  • Send messages to Slack via Slack Bot API or directly using Incoming Message
  • Remove the email label (indicating it has been forwarded)
  • Done

First, create a filter in Gmail

Filters can automate some actions when receiving emails that meet certain conditions, such as automatically marking as read, automatically tagging, automatically moving to spam, automatically categorizing, etc.

In Gmail, click the advanced search icon button in the upper right corner, enter the forwarding email rule conditions, such as from: no_reply@email.apple.com + subject is is now available to test., click “Search” to see if the filter results are as expected; if correct, click the “Create filter” button next to Search.

Or directly click Filter message like these at the top of the email to quickly create filter conditions

Or directly click Filter message like these at the top of the email to quickly create filter conditions

This button design is very counterintuitive, it took me a while to find it the first time.

Next, set the actions for emails that meet this filter condition. Here we select “Apply the label” to create a separate new recognition label “forward-to-slack”, click “Create filter” to complete.

From then on, all emails marked with this label will be forwarded to Slack.

Get Incoming WebHooks App URL

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

  1. Slack lower left corner “Apps” -> “Add apps”
  2. Search “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 of the bot that sends the message; 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 simple method of Incoming Webhook will be deprecated in the future. This article uses the simpler method, but it can be adjusted to the new method along with the next chapter “Import Employee List” which requires the Slack App API.

Writing Apps Script Programs

Paste the following basic script 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": "The email content is as follows:",
          "text": content,
        }
      ]
    };
    var res = UrlFetchApp.fetch('Paste your Slack incoming Webhook URL here',{
      method             : 'post',
      contentType        : 'application/json',
      payload            : JSON.stringify(payload)
    })
}

function forwardEmailsToSlack() {
    // Referenced from: 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:

Example: Extracting version number information from a Testflight approval email:

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

Email content:

We want to get the Bundle Version Short String and the value after 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];
}

Run and See

  • Go back to Gmail, find any email, and manually add the label — “forward-to-slack”
  • In the Apps Script code editor, select “forwardEmailsToSlack” and click the “Run” button

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

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

Click the bottom left “Advanced” -> “Go to ForwardEmailsToSlack (unsafe)”

Click “Allow”

Forwarding successful!!!

Set Up Triggers (Scheduling) for Automatic Checking & Forwarding

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

Bottom left “+ Add Trigger”.

  • Error notification settings: You can set how to notify you when the script encounters an error
  • Choose the function you want to execute: Select Main Function sendMessageToSlack
  • Select event source: You can choose from Calendar or Time-driven (timed or specified)
  • Select time-based trigger type: You can choose to execute on a specific date or every minute/hour/day/week/month
  • Select minute/hour/day/week/month interval: EX: Every minute, every 15 minutes…

For demonstration purposes, set it to execute every minute. I think checking emails every hour is sufficient for real-time needs.

  • Go back to Gmail, find any email, and manually add the label — “forward-to-slack”
  • Wait for the schedule to trigger

Automatic checking & forwarding successful!

Completion

With this feature, you can achieve customized email forwarding processing and even use it as a trigger. For example, automatically execute a script when receiving an XXX email.

Returning to the origin in the first chapter, we can use this mechanism to perfect the CI/CD process; no need to wait idly for Apple to complete processing, and it can be linked to the automation process!

Further Reading

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

===

本文中文版本

===

This article was first published in Traditional Chinese on Medium ➡️ View Here



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

Productivity Tools: Abandon Chrome and Embrace Sidekick Browser

2021 Pinkoi Tech Career Talk - Decoding the High-Efficiency Engineering Team