Preface
Recently, it is necessary to realize that after the customer submits the form, the content of the form is sent to the corresponding mailbox as an email. The front-end sends it directly without going through the back-end service. Hiss——, just do it!
After searching, there are many ways to get it, but. . . After trying them all, only one succeeded.
Let me first list the methods I found:
1. formspree: The front-end implements the function of sending emails (Formspree) a>
After registering a formspree account, when I was about to create a project form, a system crash form kept popping up. Well...
2. SmtpJS:SmtpJS Tutorial for Sending Emails
This article seemed to be reliable, so I started to operate it like a tiger. Come down. . . It always pops up an error for me: 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
, which probably means: only elasticemail is supported as the SMTP host. To open an account, please visit https://elasticemail.com/account#/create-account?r=20b444a2-b3af-4eb8-bae7-911f6097521c, uh...
3. EmailJS:EmailJS is an email sending that does not require server implementation
This article seems more reliable, but It told me that I need a foreign mobile phone number to authenticate my Gmail account, (⊙o⊙)…
4. nodemailer:「nodemailer」Node email sending module
Okay, there is no perfect way, we still use node honestly Write an interface...
Email configuration
1. Open NetEase Mailbox–>Settings–>[POP3/SMTP/IMAP]
2. Enable POP3/SMTP/IMAP service
3. Obtain the authorization password
4. Remember this
5. Initialize your project: npm init -y
6. Add dependencies :npm install express@next dotenv nodemailer --save
dotenv: Load variables in the .env file into process.env
nodemailer: Node.JS email sending module
7. Configure .env information
Complete code
memory
index.html
<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')
})
The above can successfully send the email!