久しぶりにSendGridを使ってみたのでメモ。
SendGridの注意点
- ユーザ名はメールアドレスではなく、代理店である構造計画研究所から独自に振られたxxx@kke.comというやつ
久しぶりですっかりID忘れてました。
準備
API KEYの取得
利用するにはAPI KEYが必要です。到達率を上げるためにはドメイン認証やらいろいろやったほうがいい。
API KEYはSettingsの中にある。
作業場の準備
mkdir sendmail
cd sendmail
touch index.js
npm init -f
npm install --save @sendgrid/mail
実装
難しくない。本家サイトにユースケースの紹介があるのでそれを見ながら実装する。
まずはSend a sigle email to single recipientを試す。
API_KEYやらその他情報は各自環境に合わせて変更。
const sgMail = require('@sendgrid/mail');
const API_KEY = "XX.O1c1v3QNQzed41lkvQKNIw.7DYw-coFLLfoLqEuWADNzKH_xxxxxxxxxxxxxxxxxx";
sgMail.setApiKey(API_KEY);
const msg = {
to: 'to@mail.com',
from: 'from@mail.com',
subject: 'test mail from sg',
text: 'hoge hoge',
html: '<p>foo bar</p>'
}
sgMail.send(msg).then(res => {
console.log(res);
}).catch(e => {
console.log(e);
});
複数人に送る場合はアドレスの配列を作り、sgMail.sendMultiple(msg)としてやるみたい。
動作確認
実行してみる。
node index.js
届いたみたい。
追記:ファイルを添付する
idnex.jsと同じ階層にtest.pdfがあるとして、下記のような感じ。
index.js
const sgMail = require('@sendgrid/mail');
const fs = require('fs');
//sendgrid
const api_key = "xx.h_2KiszrS9acLRNN8oCs1g.mygHZwKirzSu9FHDR_TVOenruHqjtxxxxxxxxxx";
sgMail.setApiKey(api_key);
//attachment
const pathToAttachment = `${__dirname}/test.pdf`;
const attachment = fs.readFileSync(pathToAttachment).toString("base64");
// console.log(attachment);
const msg = {
to: "to@test.com",
from: "from@test.com",
subject: "test",
text: "hoge",
// html: "<p>hoo</p>",
attachments: [
{
content: attachment,
filename: "test.pdf",
type: "application/pdf",
disposition: "attachment",
contentId: "myPdf"
}
]
}
sgMail.send(msg).catch(e => console.log(e));