LoginSignup
9
7

More than 5 years have passed since last update.

HerokuからEメールを送る

Posted at

システムを開発している中で、メールを送るシーンがあります。
例えば、サインアップするシステムを作っていると、サインアップ後に登録の確認をするメールを送るとか、パスワードのリセットするためにメールを送るとか。
これを、Herokuでやろうとしても、素のHerokuではできません。
そんな時は、SendGridを使いましょうという話です。

HerokuにSendGridを追加

まずは、HerokuにSendGridアドオンを追加します。
HerokuのOverViewから、「Configure Add-ons」をクリックします。

conf.png

次に、「Find more add-ons」をクリックします。

find.png

SendGridを検索します。

sendgrid.png

「Install SendGrid」でインストールしましょう。

install.png

SendGridの設定

 次は設定です。
 まずは、HerokuのAdd-onsリストから、SendGridを選択しましょう。

menu.png

 次にSendGridのSettingsのAPI Keysで、メール送信時に使うAPI Keyを作成します。

createapikey.png

keyname.png

API Keyが生成されました。
ここで注意です。API Keyはここでしか表示されません。API Keyをクリックすると、クリップボードにコピーできますので、必ず、コピーしましょう。

key.png

Node.jsでメールを送る

@sendgrid/mailのインストール

まずは、SendGridでメールを送るための、npmパッケージをインストールします。

npm install @sendgrid/mail --save

インプリする

いよいよ、インプリです。

sendmail.ts
import { Injectable } from '@nestjs/common';
import * as sgmail from '@sendgrid/mail';

@Injectable()
export class EmailService {
    sendMail(templateName: string, toemail: string): Promise<boolean> {
        return new Promise((resolve, reject) => {
             // SENDGRID_API_KEYを設定する
             sgmail.setApiKey(process.env.SENDGRID_API_KEY);
             // 送信するメールの内容を設定する
             const msg = {
                  to: toemail,
                  from: opts.email,
                  subject: '' + opts.servicename + '】からのお知らせ',
                  text: data
              };

               // メールを送信する
               sgmail.send(msg)
               .then((req) => {
                   resolve(true);
                })
                .catch((err) => {
                   reject(err);
                });
            }
        });
    }
}

これで、Herokuからメールが送信できるようになります。
簡単!!

9
7
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
9
7