最近需要实现客户提交表单后,把表单的内容作为邮件发送到对应的邮箱,不通过后端服务,前端直接进行发送。嘶——,说干就干!
一通搜索下来,get到方法有很多种,但是。。。都尝试了一遍之后,只有一个成功了。
先罗列一下我搜到的方法:
1、formspree:前端实现发送邮件功能(Formspree)
这个注册完formspree的账号之后,准备创建项目表单的时候,一直弹出系统崩溃的表单,额…
2、SmtpJS:SmtpJS发送邮件教程
这一篇似乎看起来很靠谱,于是乎,我一通猛如虎的操作下来。。。它总是给我弹出一个报错:Only elasticemail is supported as an SMTP host. To open an account please visit https://elasticemail.com/account#/create-account?r=20b444a2-b3af-4eb8-bae7-911f6097521c
,大概意思是:只支持elasticemail作为SMTP主机。如需开户,请访问https://elasticemail.com/account#/create-account?r=20b444a2-b3af-4eb8-bae7-911f6097521c,呃…
3、EmailJS:EmailJS 一款不需要服务端实现的邮件发送
这篇文章看起来似乎更靠谱了,可是它告诉我,需要国外的手机号来认证Gmail账号,(⊙o⊙)…
4、nodemailer:「nodemailer」Node 邮件发送模块
好叭,天无绝人之路,我们还是老老实实用node写个接口叭…
1、打开网易邮箱–>设置–>【POP3/SMTP/IMAP】
2、开启POP3/SMTP/IMAP服务
3、获取授权密码
4、可以记一下这个
5、初始化你的项目:npm init -y
6、添加依赖:npm install express@next dotenv nodemailer --save
dotenv:加载 .env 文件中的变量到 process.env 中
nodemailer:Node.JS 邮件发送模块
7、配置.env信息
<form id="myForm">
<label for="name">姓名:</label>
<input class="text" type="text" id="name" name="name"><br><br>
<label for="gender">性别:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">男</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">女</label><br><br>
<label for="age">年龄:</label>
<input class="text" type="number" id="age" name="age"><br><br>
<input class="submit" type="submit" value="提交">
</form>
<script>
// 在这里可以添加 JavaScript 代码来处理表单提交等操作
const myform = document.getElementById('myForm');
myform.addEventListener('submit', function (event) {
event.preventDefault();
const name = myform.elements.name.value;
const gender = myform.elements.gender.value;
const age = myform.elements.age.value;
const form = `name=${name}&gender=${gender}&age=${age}`
var ajaxObj = new XMLHttpRequest();
ajaxObj.open("POST", 'http://localhost:3000/send', true);
ajaxObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
ajaxObj.send(form);
ajaxObj.onreadystatechange = function () {
if (ajaxObj.readyState == 4 && ajaxObj.status == 200) {
console.log(ajaxObj.responseText)
}
}
});
</script>
emailsend.js
var nodemailer = require('nodemailer');
module.exports = class Email {
constructor() {
this.config = {
host: process.env.smtp,
port: 25,
auth: {
user: process.env.mailFrom, //刚才注册的邮箱账号
pass: process.env.mailPwd //邮箱的授权码,不是注册时的密码
}
};
this.transporter = nodemailer.createTransport(this.config);
}
sendEmail(mail) {
return new Promise((resolve, reject) => {
this.transporter.sendMail(mail, function (error, info) {
if (error) {
console.log(error)
reject(error)
}
resolve(true)
});
})
}
}
serve.js
const app = require('express')()
require('dotenv').config()
const sendEmail = require('./emailsend')
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.get('/', async (req, res) => {
res.send('hello')
})
app.post('/send', async (req, res) => {
res.header('Access-Control-Allow-Origin', '*')
const formData = req.body;
console.log(formData);
const send = new sendEmail();
const emailContent = `
姓名:${formData.name}
性别:${formData.gender}
年龄:${formData.age}
`;
try {
let email = await send.sendEmail({
from: '[email protected]',//发送人邮箱
to: '[email protected]',//接收人邮箱
subject: "xxx请查收!",//标题
text: emailContent,
})
if (email) {
console.log("发送成功!");
res.send('发送成功!')
}
} catch (e) {
console.log("发送失败");
res.send(e)
}
})
app.listen(3000, () => {
console.log('http://localhost:3000')
})