node.jsはnodemailを使ってメールの実例を送ります。

1757 ワード

一、nodemail
npm install nodemailer --save
をインストールし、
var nodemailer = require("nodemailer");

// SMTP
var smtpTransport = nodemailer.createTransport("SMTP",{
  host: "smtp.qq.com", //
  secureConnection: true, // SSL
  port: 465, // SMTP
  auth: {
    user: "[email protected]", //
    pass: "xxxxxxxx" //
  }
});

//
var mailOptions = {
  from: "Fred Foo <[email protected]>", //
  to: "[email protected], [email protected]", //
  subject: "Hello world", //
  html: "<b>thanks a for visiting!</b> , !" // html
}

//
smtpTransport.sendMail(mailOptions, function(error, response){
  if(error){
    console.log(error);
  }else{
    console.log("Message sent: " + response.message);
  }
  smtpTransport.close(); // ,
});

を呼び出し、よくあるエラー

{ [AuthError: Invalid login - 454 Authentication failed, please open smtp flag first!]
  name: 'AuthError',
  data: '454 Authentication failed, please open smtp flag first!',
  stage: 'auth' }
を呼び出します。
エラーの原因:アカウントにこのサービス解決策が設定されていない:QQメールアドレス->設定->アカウント->オープンサービス:POP 3/SMTPサービス

{ [SenderError: Mail from command failed - 501 mail from address must be same as authorization user]
  name: 'SenderError',
  data: '501 mail from address must be same as authorization user',
  stage: 'mail' }
エラー原因:送信アカウントと認証アカウントが異なる