Using Google Apps Script to Forward Gmail Messages to Slack
Automatically forward customized content to a Slack Channel using Gmail Filter + Google Apps Script when receiving emails.
ℹ️ℹ️ℹ️ The following content is translated by OpenAI.
Click here to view the original Chinese version. | 點此查看本文中文版
Using Google Apps Script to Forward Gmail Messages to Slack
Automatically forward customized content to a Slack Channel using Gmail Filter + Google Apps Script when receiving emails.
Photo by Lukas Blazek
Origin
Recently, while optimizing the CI/CD process for an iOS app, I used Fastlane as the automation tool. After packaging and uploading, if I wanted to continue with the automatic submission steps ( skip_submission=false
), I had to wait for Apple to complete the process, which could waste about 30-40 minutes of CI server time. This is because the Apple App Store Connect API is not very robust, and Fastlane can only check once per minute whether the uploaded build has been processed, which is a waste of resources.
- Bitrise CI Server: Limits the number of concurrent builds and has a maximum execution time of 90 minutes. While 90 minutes is sufficient, it can block one build from allowing others to execute.
- Travis CI Server: Charges based on build time, making it even less feasible to wait, as costs would accumulate.
A Change in Perspective
No more waiting; finish the upload and move on! Trigger subsequent actions based on the notification of the completed email.
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 notification email for TestFlight, which is already available for testing, as an example.
The complete process is illustrated in the image above; while the principle is feasible, it is not the focus of this article. This article will concentrate on receiving emails and using Apps Script to forward them to a Slack Channel.
How to Forward Received Emails to a Slack Channel
Whether you have a paid or free Slack project, there are various methods to achieve email forwarding to a Slack Channel or DM.
You can refer to the official documentation for setup: Send Emails to Slack
Regardless of the method, the effect is as follows:
By default, the email content is collapsed, and you can click to expand and view all content.
Advantages:
- Simple and quick
- No technical barriers
- Instant forwarding
Disadvantages:
- Cannot customize content
- Display style cannot be changed
Customizing Forwarded Content
This is the main point of this article.
Translate the email content into the style you want to present, as shown in the example above.
First, here’s a complete workflow diagram:
- Use Gmail Filter to label the emails to be forwarded.
- Apps Script periodically retrieves emails marked with that label.
- Read the email content.
- Render it in 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 actions when receiving emails that meet certain criteria, such as automatically marking as read, tagging, moving to spam, categorizing, etc.
In Gmail, click the advanced search icon in the upper right, enter the criteria for the emails to be forwarded, such as from: no_reply@email.apple.com
+ subject is is now available to test.
, 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 message like these at the top of the email to quickly create filter criteria.
This button is designed in a very user-unfriendly way; I couldn’t find it the first time.
Next, set the action for emails that meet this filter condition. Here, we choose “Apply the label” to create a new identifying label “forward-to-slack,” and click “Create filter” to complete it.
From now on, emails marked with this label will be forwarded to Slack.
Obtain Incoming WebHooks App URL
First, we need to add the Incoming WebHooks App to the Slack Channel, which we will use to send messages.
- In Slack, click “Apps” in the lower left -> “Add apps”
- Search for “incoming” in the search box on the right.
- Click “Incoming WebHooks” -> “Add”
Select the channel where you want to send messages.
Take note of the “Webhook URL” at the top.
Scroll down to set the display name and avatar for the bot when sending messages; 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. I took a shortcut here, but it will need to be adjusted to the new method in the next chapter “Import Employee List.”
Write the Apps Script Code
- Click here to go to my Apps Script project
- Click “New Project” in the upper left.
- After creating it, you can click the project name to rename it, e.g., ForwardEmailsToSlack.
Paste the following basic code 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() {
// Reference 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:
- You can refer to this official structure document for Slack message styles.
- You can use JavaScript’s Regex Match Function to match and scrape content from the email.
EX: Scraping the version number information from the TestFlight approval email:
Email subject: Your app XXX has been approved for beta testing.
Email content:
We want to obtain 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];
}
- You can refer to this for Regex usage.
- You can use this website to test if your Regex is correct.
Let’s Run It
- Go back to Gmail, find any email, and manually add the label — “forward-to-slack.”
- 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, you may see “Google hasn’t verified this app,” which is normal since our Apps Script has not been verified by Google. However, that’s fine since it’s for personal use.
You can click “Advanced” in the lower left -> “Go to ForwardEmailsToSlack (unsafe).”
Click “Allow.”
Forwarding successful!!!
Set Up a Trigger (Schedule) for Automatic Checking & Forwarding
In the left menu of Apps Script, select “Triggers.”
Click the lower 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 the Main Function
sendMessageToSlack
. - Select event source: You can choose from calendar or time-driven (scheduled or specific).
- Select time-based trigger type: You can choose to execute on a specific date or once every minute/hour/day/week/month.
- Select interval for minutes/hours/days/weeks/months: EX: every minute, every 15 minutes…
Here, to demonstrate, I set it to execute once every minute. I think checking emails every hour would be sufficient for real-time needs.
- Again, go back to Gmail, find any email, and manually add the label — “forward-to-slack.”
- Wait for the scheduled trigger.
Automatic checking & forwarding successful!
Completion
With this functionality, you can achieve customized email forwarding processing, and even use it as a trigger for actions, such as automatically executing a script when receiving a specific email.
Returning to the origin discussed in the first chapter, we can use this mechanism to enhance the CI/CD process; there’s no need to wait idly for Apple to complete processing, and we can integrate it into an automated workflow!
Further Reading
- Building a More Immediate and Convenient Crash Tracking Tool with Crashlytics + Big Query
- Automatically Querying App Crash-Free Users Rate with Crashlytics + Google Analytics
- Using Python + Google Cloud Platform + Line Bot to Automate Routine Tasks
- Creating a Fully Automated WFH Employee Health Reporting System with Slack
- The App Uses HTTPS for Transmission, but Data Still Gets Stolen.
If you have any questions or suggestions, feel free to contact me.
This article was first published on Medium ➡️ Click Here
Automatically converted and synchronized using ZMediumToMarkdown and Medium-to-jekyll-starter.