0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ShoheiAdvent Calendar 2022

Day 10

GASでGMailを操作するいろいろ

Posted at

まずは、メールを取得してみる

const mailSearch = () => {
  const threads = GmailApp.search('Amazonギフト券プレゼント')
  const messagesForThreads = GmailApp.getMessagesForThreads(threads)
  for (const messages of messagesForThreads) {
    console.log(messages[0].getSubject())
  } 
}

image.png

メール送信(メチャクチャ簡単)

const sendMail = () => {
  GmailApp.sendEmail('xxxxx@gmail.com', 'テストだよ', 'これを送信する!')
}

image.png

新着メール(10分以内の未読)をSlackに通知する。

メール検索部分

const newMailSearch = () => {
  const condition = []
  condition.push('is:unread') // 未読
  condition.push(`after:${Math.floor((new Date()).getTime() / 1000) - (5 * 60)}`) // 5分前以降
  const threads = GmailApp.search(condition.join(' '))
  const messagesForThreads = GmailApp.getMessagesForThreads(threads)
  const unreadMessages = []
  for (const messages of messagesForThreads) {
    const lastMessage = messages[messages.length - 1]
    unreadMessages.push({
      date: Utilities.formatDate(lastMessage.getDate(), 'Asia/Tokyo', 'yyyy-MM-dd HH:mm:ss'),
      subject: lastMessage.getSubject(),
      from: lastMessage.getFrom()
    })
  }
  const message = `新着メール(10分以内の未読メール)お知らせ\n\`\`\`${
    unreadMessages.map(element => `[${element.date}] ${element.subject} | from: ${element.from}`).join('\n')
  }\`\`\``
  sendMessage(message)
}

Slackメッセージ送信部分

const SLACK_URL = 'https://hooks.slack.com/services/xxxxxxxxxxxxxx/xxxxxxxxxxxxxx/xxxxxxxxxxxxxx';
const SLACK_CHANNEL = '#bots';

const sendMessage = (message) => {
  UrlFetchApp.fetch(SLACK_URL, {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify({
      channel: SLACK_CHANNEL,
      text: message,
    })
  });
}

最後に

GMail操作も、GAS✖︎〇〇で、できることは段違いに増えるので、また何か作ったら記事書こうと思います。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?