LoginSignup
4
0

More than 1 year has passed since last update.

nodemailerとGmailと2段階認証

Posted at

2段階認証を使っているGmailのアカウントを使ってnodemailerでメールを送ろうとしたら詰まったので、自分用の備忘録メモ。

nodemailerでGmailからメールを送りたい

nodemailerでGmailを使ってメールを送る場合はこんな感じのコードでできる。

const nodemailer = require('nodemailer');

async function sendEmail() {
  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: process.env.EMAIL,
      pass: process.env.EMAIL_PASS,
    },
  });

  const mailContents = {
    from: process.env.EMAIL,
    to: process.env.TO_EMAIL,
    subject: 'Test Mail',
    text: 'Hello from nodemailer!',
  };

  await transporter.sendMail(mailContents, function (error, info) {
    if (error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }
  });
}

sendEmail().catch(console.error);

はずなんだけど、エラーが出てしまった。Gmailの認証がうまく行っていないっぽい。

Error: Invalid login: 534-5.7.9 Application-specific password required. Learn more at
534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor ix19-20020a170902f81300b0016362da9a03sm543170plb.245 - gsmtp
    at SMTPConnection._formatError 
<中略>
  code: 'EAUTH',
  response: '534-5.7.9 Application-specific password required. Learn more at\n' +
    '534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor ix19-20020a170902f81300b0016362da9a03sm543170plb.245 - gsmtp',
  responseCode: 534,
  command: 'AUTH PLAIN'
}

解決法

以下のページからGoogleアカウント上でアプリパスワードなるものを設定して、そのパスワードでログインをすればOK。
https://myaccount.google.com/u/1/apppasswords

アプリパスワードを使用すると、2 段階認証プロセスに対応していないデバイス上のアプリから Google アカウントにログインできるようになります。

とのこと。

nodemailerのドキュメントに書いてあった。
https://nodemailer.com/usage/using-gmail/

4
0
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
4
0