需要用到库
npm install js-yaml
npm install nodemailer
我们邮件的账号(密码| 授权码)不可能明文写到代码里面一般存放在yaml文件或者环境变量里面
js-yaml 解析yaml文件
pass: 授权码 | 密码
user: xxxxx@qq.com 邮箱账号
import nodemailder from 'nodemailer'
import yaml from 'js-yaml'
import fs from 'node:fs'
import http from 'node:http'
import url from 'node:url'
const mailConfig = yaml.load(fs.readFileSync('./mail.yaml', 'utf8'))
const transPort = nodemailder.createTransport({
service: "qq",
port: 587,
host: 'smtp.qq.com',
secure: true,
auth: {
pass: mailConfig.pass,
user: mailConfig.user
}
})
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)
transPort.sendMail({
to: body.to,
from: mailConfig.user,
subject: body.subject,
text: body.text
})
res.end('ok')
})
}
}).listen(3000)
nodemailder.createTransport 创建邮件服务这里用qq举例,
QQ邮件服务文档
用户名/帐户: 你的QQ邮箱完整的地址
密码: 生成的授权码
电子邮件地址: 你的QQ邮箱的完整邮件地址
接收邮件服务器: pop.qq.com,使用SSL,端口号995
发送邮件服务器: smtp.qq.com,使用SSL,端口号465或587
授权码生成
测试发送
POST http://localhost:3000/send/mail HTTP/1.1
Content-Type: application/json
{
"to":"xxxxx@qq.com",
"subject":"标题",
"text":"我想你了,你还好吗Rong"
}