const http = require('http');
const fs = require('fs');
const url = require('url');
const nodemailer = require('nodemailer');
// 创建一个HTTP服务器
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
// 如果请求的是根路径,返回表单页面
if (parsedUrl.pathname === '/') {
fs.readFile('form.html', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
}
// 如果请求的是提交表单,发送邮件
else if (parsedUrl.pathname === '/sendmail') {
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
const formData = new URLSearchParams(body);
const { name, email, message } = Object.fromEntries(formData);
// 配置邮件发送器
const transporter = nodemailer.createTransport({
host: 'smtp.qq.com',
port: 465,
secure: true,
auth: {
user: '',
pass: '去qq邮箱里面看'
}
});
// 配置邮件内容
const mailOptions = {
from: '发件人自己的邮箱',
to: '对方邮箱',
subject: 'Test Email',
html: `<p><strong>Name:</strong> ${name}</p><p><strong>Email:</strong> ${email}</p><p><strong>Message:</strong> ${message}</p>`
};
// 发送邮件
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
fs.readFile('html.html', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
}
});
});
}
// 如果请求的是其他路径,返回404错误
else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
// 启动服务器
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
通过node发送邮箱教程
最新推荐文章于 2024-11-26 17:59:10 发布