node.js 使用 qq邮箱发送邮件

安装 nodemailer

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: "xxxxxxxx@qq.com", // 账号
        pass: "xxxxxxxx" // 密码
    }
});

// 设置邮件内容
var mailOptions = {
    from: "Fred Foo <xxxxxxxx@qq.com>", // 发件地址
    to: "2838890xx@qq.com, minimixx@126.com", // 收件列表
    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(); // 如果没用,关闭连接池
});

2015.5.15 更新

var nodemailer = require("nodemailer");
var smtpTransport = require('nodemailer-smtp-transport');

// 开启一个 SMTP 连接池
var transport = nodemailer.createTransport(smtpTransport({
  host: "smtp.qq.com", // 主机
  secure: true, // 使用 SSL
  port: 465, // SMTP 端口
  auth: {
    user: "lellansin@qq.com", // 账号
    pass: "xxxxxx" // 密码
  }
}));

// 设置邮件内容
var mailOptions = {
  from: "Fred Foo <lellansin@qq.com>", // 发件地址
  to: "lellansin@qq.com", // 收件列表
  subject: "Hello world", // 标题
  html: "<b>thanks a for visiting!</b> 世界,你好!" // html 内容
}

// 发送邮件
transport.sendMail(mailOptions, function(error, response) {
  if (error) {
    console.error(error);
  } else {
    console.log(response);
  }
  transport.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邮箱 -> 设置 -> 帐户 -> 开启服务:POP3/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' }

错误原因:
发件账号与认证账号不同

3 thoughts on “node.js 使用 qq邮箱发送邮件

  1. 博主你好,我用了上面那段代码,出现了两个情况,跟你说下:
    1. 提示已经不兼容最新版的nodemailer了;
    2. 我把nodemailer降到0.7版本,可以正常使用你这段代码,所以非常感谢!! 之后遇到了另一个问题是我用ajax方式提交,邮箱已经能收到邮件,但是页面上用firebug看它一直在sending,三四分钟后会出现发送不成功的情况。所以想请教你一下,如果是用ajax发送邮件的话,你会如何写呢?

    再次感谢!

  2. /Users/xiongmingcai/GitHub/robot/node_modules/nodemailer/lib/mailer/index.js:45
    this.transporter.mailer = this;
    ^
    TypeError: Cannot set property ‘mailer’ of undefined

留下评论