Skip to main content

邮件发送服务

原理

利用QQ的SMTP的,使用Node库nodemailer 来接替qq邮箱发送服务

使用

  1. 下载库
pnpm i nodemailer
  1. 导入 app.js
const nodemailer = require('nodemailer')
  1. 配置传送服务
let mailTransport = nodemailer.createTransport({  
// host: 'smtp.qq.email',
service: 'qq',
secure: true, //安全方式发送,建议都加上
auth: {
user: '[email protected]', // 发送人qq邮箱地址
pass: 'tezxmfuinmtldich', // SMTP的授权码
},
})
  1. 邮件发送服务
app.post('/send', function (req, res) {  
console.log(req.body)
let options = {
from: ' "测试账号" <[email protected]>', // 发送人 发送的账号
to: '<[email protected]>', // 接受者
bcc: '密送',
subject: '测试Node邮箱', // 邮件标题
text: 'hello 我是邮件内容', // 邮件内容
html: '<h1>hello E-Mail!</h1>', // 邮件正文
}
mailTransport.sendMail(options, function (err, msg) {
if ( err ) {
console.log(err)
res.send(err)
}
else {
res.send({
statusCode: 200,
statusText: 'Ok',
body: {},
})
}
})
})

完整示例:

'use strict'  
const express = require('express')
const app = express()

const cors = require('cors')
const nodemailer = require('nodemailer')
const bodyParser = require('body-parser')


// 获取HTTP的POST正文(body)内容
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 处理跨越请求
app.use(cors())


// 1. 配置传送服务
let mailTransport = nodemailer.createTransport({
// host: 'smtp.qq.email',
service: 'qq',
secure: true, //安全方式发送,建议都加上
auth: {
user: '[email protected]', // 发送人qq邮箱地址
pass: 'tezxmfuinmtldich', // SMTP的授权码
},
})

// 2. 邮件发送服务
app.post('/send', function (req, res) {
console.log(req.body)
let options = {
from: ' "测试账号" <[email protected]>', // 发送人 发送的账号
to: '<[email protected]>', // 接受者
bcc: '密送',
subject: '测试Node邮箱', // 邮件标题
text: 'hello 我是邮件内容', // 邮件内容
html: '<h1>hello E-Mail!</h1>', // 邮件正文
}
mailTransport.sendMail(options, function (err, msg) {
if ( err ) {
console.log(err)
res.send(err)
}
else {
res.send({
statusCode: 200,
statusText: 'Ok',
body: {},
})
}
})
})

app.listen(4002, '127.0.0.1', () => {
console.log('network')
})