5
6

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-12-15

久しぶりに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

届いたみたい。

 追記:ファイルを添付する

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));
5
6
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
5
6