Skip to content

Node.js 邮件服务

应用场景

  • 任务分配与进度跟踪
  • 错误报告和故障排除通知
  • CI/CD 构建状态通知

发邮件(nodemailer + QQ 邮箱)

bash
npm install nodemailer js-yaml

邮箱配置 mail.yaml

yaml
pass: 你的QQ邮箱授权码
user: xxxxx@qq.com

QQ 邮箱需要在 QQ邮箱设置 中开启 SMTP 服务并获取授权码(不是登录密码)。

核心代码

js
import nodemailer from 'nodemailer'
import yaml from 'js-yaml'
import fs from 'node:fs'

// 读取邮箱配置
const mailConfig = yaml.load(fs.readFileSync('./mail.yaml', 'utf8'))

// 创建 SMTP 传输对象
const transporter = nodemailer.createTransport({
  service: 'qq',
  port: 587,
  host: 'smtp.qq.com',
  secure: true,
  auth: {
    pass: mailConfig.pass,   // 授权码
    user: mailConfig.user,   // 邮箱账号
  }
})

// 发送邮件
transporter.sendMail({
  to: 'recipient@example.com',        // 收件人
  from: mailConfig.user,              // 发件人
  subject: '邮件主题',                 // 主题
  text: '邮件正文',                    // 纯文本正文
  // html: '<h1>邮件正文</h1>',       // HTML 正文(可选)
})

HTTP 接口版本

js
http.createServer((req, res) => {
  const { pathname } = url.parse(req.url)
  if (req.method === 'POST' && pathname === '/send/mail') {
    let mailInfo = ''
    req.on('data', (chunk) => mailInfo += chunk.toString())
    req.on('end', () => {
      const body = JSON.parse(mailInfo)
      transporter.sendMail({
        to: body.to,
        from: mailConfig.user,
        subject: body.subject,
        text: body.text,
      })
      res.end('ok')
    })
  }
}).listen(3000)

QQ SMTP 配置

配置项
hostsmtp.qq.com
serviceqq
port587(或 465)
securetrue
用户名QQ邮箱完整地址
密码授权码(非 QQ 密码)