

Start: Gmail: Email Message Received
This item starts a case when Gmail has received a new message.
Basic Configs
- Step Name
- Note
Configs for this Auto Step
- conf_auth
- C1: OAuth2 Setting *
- conf_label
- C2: Label (Inbox if blank)
- conf_idData
- C3: Data item to save Message ID *
- conf_timestampData
- C4: Data item to save received time
- conf_rfc822msgIdData
- C5: Data item to save RFC 822 Message-ID header
Notes
- This modeling element is for Google Workspace accounts only, so you cannot use it with a general user account (@gmail.com)
- As a preliminary step, a user with Google Workspace administrator privileges must set the target OAuth app as a trusted app in the admin console
- If the OAuth app is not trusted, you cannot use this modeling element
- The client ID of the corresponding OAuth app is 13039123046-t87nmrj499ffoa58asehks3asajvgqnh.apps.googleusercontent.com
- After the app is released, Questetra BPM Suite will periodically poll Gmail
- You can confirm the check status from the [Case Log]
- A Case will not be started on the first poll; only the check will be done
- Emails with the specified label will be checked
- Use Gmail’s [Label] function to assign labels to emails that should start a case
- If multiple labels are specified in [C2: Label], emails with all the specified labels will be checked
- In addition to user-created labels, system labels such as INBOX, UNREAD and STARRED are also supported
- For the list of system labels see the Gmail API Guide
- In each poll, a certain number of newer emails with the target label are checked.
- A Case will be started for emails that have not yet been started among the checked emails
- If an email has the specified label, it will be included in the check even if the Case has already started
- If the label is removed from the email, it will no longer be checked
- Automated item [Gmail: Remove Label from Email Message]
- By removing the label, you will be able to see that the message has been imported to Questetra on browsing your Gmail mailbox
- If the label is removed from the email, it will no longer be checked
- If a large number of emails are received in a short period, the emails beyond a certain number will not be checked so the Case will not start
- Approx. 90 Cases every 3 minutes ~ 15 minutes
- Even if the email is not checked and does not start the Case, the case will start if checked in the following polling
Capture

See also
Script (click to open)
- An XML file that contains the code below is available to download
- gmail-message-received.xml (C) Questetra, Inc. (MIT License)
- Just use it for a reference for the codes
- This file cannot be imported into a Workflow App as an Add-on
/**
* @typedef {Object} timestamp java.sql.Timestamp オブジェクト
*/
/** 日時フォーマッター */
const datetimeFormatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
/**
* configs から必要な情報の取り出し
* @returns {Object} setting 設定
* @returns {AuthSettingWrapper} setting.auth OAuth2 認証設定
* @returns {Array} setting.labels ラベル一覧
*/
const prepare = () => {
const auth = configs.getObject('conf_auth');
let label = configs.get('conf_label');
let labels = [];
if (label !== null && label !== '') {
labels = label.split('\n')
.map(label => label.trim())
.filter(label => label !== '');
}
return {
auth,
labels
};
};
/**
* 追加されたメールの検索
* @param {Number} limit 取得上限数
* @param timestampLowerLimit timestamp の下限
* @returns {Array} messages メッセージ一覧
* @returns {string} messages[].id Gmail Message ID
* @returns {timestamp} messages[].timestamp メール受信時刻
* @returns {string} messages[].rfc822msgId RFC 822 Message-ID
*/
const list = (limit, timestampLowerLimit) => {
const {auth, labels} = prepare();
let labelIds = ['INBOX'];
if (labels.length !== 0) {
labelIds = getLabelIds(auth, labels);
}
// HTTP リクエスト数制限を考慮する
limit = Math.min(limit, httpClient.getRequestingLimit() - 2);
const messages = getMessages(auth, labelIds, limit, timestampLowerLimit);
logMessages(messages);
return messages;
};
/**
* メッセージ一覧のログ出力
* @param {Array} messages メッセージ一覧
*/
const logMessages = (messages) => {
const replacer = (key, value) => value instanceof java.sql.Timestamp ? datetimeFormatter.format(value) : value;
messages.forEach(msg => engine.log(JSON.stringify(msg, replacer)));
};
/**
* ラベルからラベル ID を取得する
* @param {AuthSettingWrapper} auth OAuth2 認証設定
* @param {Array<String>} labels ラベル一覧
* @return {Array<String>} ラベル ID の一覧
*/
function getLabelIds(auth, labels) {
const response = httpClient.begin()
.authSetting(auth)
.get('https://gmail.googleapis.com/gmail/v1/users/me/labels');
const responseJson = response.getResponseAsString();
const status = response.getStatusCode();
if (status >= 300) {
const accessLog = `--- users.labels.list --- ${status}\n${responseJson}\n`;
engine.log(accessLog);
throw `Failed to get labels. status: ${status}`;
}
const json = JSON.parse(responseJson);
let found = json.labels
.filter(label => labels.includes(label.name));
const foundLabels = found.map(label => label.name);
const notFoundLabels = labels.filter(label => !foundLabels.includes(label));
if (notFoundLabels.length > 0) {
const accessLog = `--- users.labels.list --- ${status}\n${responseJson}\n`;
engine.log(accessLog);
// id が見つからない label がある場合、エラーをスロー
throw `label ids of ${notFoundLabels.join(', ')} not found`;
}
return found.map(label => label.id);
}
/**
* Gmail REST API にメール取得の GET リクエストを送信し、メッセージ一覧を返す
* @param {AuthSettingWrapper} auth OAuth2 認証設定
* @param {Array<String>} labelIds ラベル ID の一覧
* @param {Number} limit 取得上限数
* @param timestampLowerLimit timestamp の下限
* @returns {Array} messages メッセージ一覧
* @returns {string} messages[].id Gmail Message ID
* @returns {timestamp} messages[].timestamp メール受信時刻
* @returns {string} messages[].rfc822msgId RFC 822 Message-ID
*/
function getMessages(auth, labelIds, limit, timestampLowerLimit) {
let request = httpClient.begin()
.authSetting(auth)
.queryParam('maxResults', `${limit}`);
engine.log(`labelIds: ${labelIds}`);
labelIds.forEach(labelId => {
request = request.queryParam('labelIds', labelId);
});
// 単位はミリ秒ではなく秒
const q = `newer: ${Math.floor(timestampLowerLimit.getTime() / 1000)}`;
engine.log(`q: ${q}`);
request = request.queryParam('q', q);
const response = request
.get('https://gmail.googleapis.com/gmail/v1/users/me/messages');
// when error thrown
const responseJson = response.getResponseAsString();
const status = response.getStatusCode();
if (status >= 300) {
const accessLog = `--- users.messages.list --- ${status}\n${responseJson}\n`;
engine.log(accessLog);
throw `Failed to get messages. status: ${status}`;
}
const json = JSON.parse(responseJson);
if (json.messages === undefined || json.messages === null) {
// 該当メッセージが無い
engine.log("no messages");
return [];
}
return json.messages
.filter(msg => !engine.isProcessStarted(msg.id)) // 既にケース開始済みのものを除く
.map(msg => getMessage(auth, msg.id)) // id 以外の情報を取得
// 検索条件ですでに timestampLowerLimit によりフィルタしているが、
// 検索条件の対象時刻とメールの timestamp が一致しない場合が稀にあるため、再フィルタ
.filter(msg => {
const isOld = msg.timestamp.before(timestampLowerLimit);
if (isOld) {
engine.log(`excluded by timestampLowerLimit: id=${msg.id}, timestamp=${datetimeFormatter.format(msg.timestamp)}`);
}
return !isOld; // timestampLowerLimit 以前のものを除外
});
}
/**
* Gmail REST API にメール取得の GET リクエストを送信し、internalDate 等を取得する
* @param {AuthSettingWrapper} auth OAuth2 認証設定
* @param id {String} メッセージ ID
* @return {Object} message メッセージ
* @returns {string} message.id Gmail Message ID
* @returns {timestamp} message.timestamp メール受信時刻
* @returns {string} message.rfc822msgId RFC 822 Message-ID
*/
function getMessage(auth, id) {
const response = httpClient.begin()
.authSetting(auth)
.queryParam('format', 'metadata')
.get(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${id}`);
const responseJson = response.getResponseAsString();
const status = response.getStatusCode();
if (status >= 300) {
const accessLog = `--- users.messages.get --- ${status}\n${responseJson}\n`;
engine.log(accessLog);
throw `Failed to get message ${id}. status: ${status}`;
}
const json = JSON.parse(responseJson);
const msgIdHeader = json.payload.headers.find(h => h.name.toLowerCase() === 'message-id');
const rfc822msgId = msgIdHeader !== undefined ? msgIdHeader.value : '';
return {
id: json.id,
timestamp: new java.sql.Timestamp(Number(json.internalDate)),
rfc822msgId
};
}



