Nodemailer是⼀个简单易⽤的Node.js邮件发送组件
安装:
npm install nodemailer --save
node.js(后端代码):
const nodemailer = require('nodemailer'); //引⼊模块
// 配置发送者信息
let transporter = nodemailer.createTransport({
//node_modules/nodemailer/lib/well-known/services.json 查看相关的配置,
如果使⽤qq邮箱,就查看qq邮箱的相关配置
service: 'qq', //类型qq邮箱
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: 'xxxx@qq.com', // 发送⽅的邮箱
pass: 'xxxxx' // SMTP 的授权码
}
});
//pass 不是邮箱账户的密码⽽是SMTP的授权码(必须是相应邮箱的stmp授权码)
//邮箱---设置--账户--POP3/SMTP服务---开启---获取SMTP授权码
// mail:收件⼈邮箱
// subject:邮件标题
// content:邮件内容
// call:回调函数
function send(mail, subject, content, call) {
// 发送的配置项
let mailOptions = {
from: '"DEMO" <xxxxx@qq.com>', // 发送⽅
to: mail, //接收者邮箱,多个邮箱⽤逗号间隔
subject: subject, // 标题
text: content, // ⽂本内容
// html: '<p>这⾥是"Express-demo"详情请点击:</p><a href="https://ww
w.baidu.com/">点击跳转</a>', //⻚⾯内容
// attachments: [{//发送⽂件
// filename: 'index.html', //⽂件名字
// path: './index.html' //⽂件路径
// },
// {
// filename: 'sendEmail.js', //⽂件名字
// content: 'sendEmail.js' //⽂件路径
// }
// ]
};
//发送函数
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
call(false)
} else {
call(true) //因为是异步 所有需要回调函数通知成功结果
}
});
}
module.exports = {
send
}
app.post('/mail', (req, res) => {
send(req.body.mail, req.body.subject, req.body.content, (result) => {
if (result) {
res.send({
code: 0,
msg: "发送成功"
})
} else {
res.send({
code: -1,
msg: "发送失败"
})
}
})
})
路由代码:
app.post('/mail', (req, res) => {
send(req.body.mail, req.body.subject, req.body.content, (result) => {
if (result) {
res.send({
code: 0,
msg: "发送成功"
})
} else {
res.send({
code: -1,
msg: "发送失败"
})
}
})
})
前端代码:
<template>
<div class="mail">
收件⼈地址:<input type="text" v-model="mail">
</div>
<div class="mail">
邮件主题:<input type="text" v-model="subject">
</div>
<div>
邮件内容:<textarea v-model="content" rows="10" cols="50"></textarea>
</div>
<button @click="send">发送</button>
</template>
<script setup>
import { ref, reactive } from 'vue';
import axios from 'axios';
const mail = ref('')
const content = ref('')
const subject = ref('')
function send() {
axios.post('http://localhost:3000/mail', {
mail: mail.value,
subject: subject.value,
content: content.value
})
.then(function (response) {
console.log(response);
})
}
</script>
<style scoped>
.mail {
margin-bottom: 30px;
}
</style>
最后查看自己邮箱是否有收到就完事了