やりたいこと
SendGridで複数ファイルを添付したメールを送信したい
やり方
JavaScriptのコード
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 |
var attAry = []; //添付ファイル情報は req.files.フロントエンドで設定したname属性値 プロパティに格納される //今回は req.files.attachment //添付ファイルの数に関わらず、添付ファイルを配列で扱いたい if (req.files.attachment.name == "") { console.log("添付なし"); } else if (!Array.isArray(req.files.attachment)) { console.log("添付1つ"); attAry.push(req.files.attachment) } else { console.log("添付2つ以上"); attAry = req.files.attachment } var attachments = []; //SendGridに渡す配列の設定 for (let i = 0; i < attAry.length; i++) { var attpath = `${attAry[i].path}`; attachments.push( { content: fs.readFileSync(attpath).toString("base64"), filename: attAry[i].name, type: attAry[i].type } ) } //メール情報をセットして送信 const msg = { to: '送信先アドレス', from: '送信元アドレス', subject: '件名', text: '本文', attachments: attachments //添付ファイル情報 }; sgMail.send(msg); |