使用Vue+Express如何进行发送邮件

本文介绍了如何在Node.js项目中通过Nodemailer组件配置QQ邮箱并发送邮件,包括设置SMTP参数和在Vue.js前端进行交互的示例代码。
摘要由CSDN通过智能技术生成

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>

最后查看自己邮箱是否有收到就完事了

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值