2020年9月18日金曜日

SESで添付付きのHTMLメールを送る

この情報は2020年9月時点の情報です。
先日、お仕事でAWS SESを利用して、動画を添付したHTMLメールを送るというのをやったのですが。
結局ボツになりまして。
もったいないので、ここに概要を貼り付けておこうかと。

ちゃんと動くかどうかは保証しません。なんかあっても私を責めないでください。
HTMLメールはファイルとして用意して、readTemplate()でstringとして読み込むようになっています。
動画はS3からmp4をダウンロードして、base64エンコードします。

タイトルが日本語だとbase64エンコードしないとダメだったりと、いろいろ面倒な感じになっていますが。
    try {
      // HTMLメール本文
      const templateStr = await this.readTemplate()
      const encodedTemplate = Buffer.from(templateStr).toString('base64')
     
      // 動画部分
      const encodedStr = <ここはS3からmp4をダウンロードし、base64エンコードする>


      const fromEmail = 'noreply@hogehoge.jp'

      // Subject
      const subject = '動画のお届けものです'
      const encodedSubject = Buffer.from(subject).toString('base64')

      const boundary = `----=_Part${ Math.random().toString().substr( 2 ) }`


      const rawMessage = [
        `From: "${ fromEmail }" <${ fromEmail }>`,
        `To: ${ address }`,
        `Subject: =?utf-8?B?${ encodedSubject }?=`,
        'MIME-Version: 1.0',
        `Content-Type: multipart/mixed; boundary="${ boundary }"`,
        '\n',
        `--${ boundary }`,
        'Content-Type: text/html; charset=UTF-8',
        'Content-Transfer-Encoding: base64',
        '\n',
        encodedTemplate,
        `--${ boundary }`,
        'Content-Type: video/mp4; name="movie.mp4"',
        'Content-Transfer-Encoding: base64',
        'Content-Disposition: attachement; filename="movie.mp4"',
        '\n',
        encodedStr,
        '\n',
        `--${ boundary }--`
      ]

      const rawParams: SendRawEmailRequest = {
        Source: 'noreply@hogehoge.jp',
        Destinations: [address],
        RawMessage: {
          Data: rawMessage.join('\n')
        },
      }

      AWS.config.update({region: <ここはregionを指定>})
      const ses = new AWS.SES()
      const sendPromise = ses.sendRawEmail(rawParams).promise()
      return new Promise((resolve, reject) => {
        sendPromise
          .then((data) => {
            console.log('send success: ', data.MessageId)
            resolve(true)
          })
          .catch((err) => {
            console.log('send error: ', err)
            reject(err)
          })
      })
    } catch(error) {
      console.log(`sendEmail error(to: ${address}): `, error)
      throw error
    }

0 件のコメント:

コメントを投稿