Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9082

Node.jsからSendGridを使ってメールを送る

$
0
0

久しぶりにSendGridを使ってみたのでメモ。

SendGridの注意点

  • ユーザ名はメールアドレスではなく、代理店である構造計画研究所から独自に振られたxxx@kke.comというやつ

久しぶりですっかりID忘れてました。

準備

API KEYの取得

利用するにはAPI KEYが必要です。到達率を上げるためにはドメイン認証やらいろいろやったほうがいい。
API KEYはSettingsの中にある。

スクリーンショット 2019-12-15 14.58.57.png

作業場の準備

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

届いたみたい。


Viewing all articles
Browse latest Browse all 9082

Latest Images

Trending Articles