使用JavaScript即时发送电子邮件可以通过以下步骤实现:
以下是一个简单的示例代码:
前端代码(HTML和JavaScript):
<form id="emailForm">
<label for="to">收件人邮箱:</label>
<input type="email" id="to" required><br>
<label for="subject">主题:</label>
<input type="text" id="subject" required><br>
<label for="message">正文:</label>
<textarea id="message" required></textarea><br>
<button type="submit">发送邮件</button>
</form>
<script>
document.getElementById('emailForm').addEventListener('submit', function(e) {
e.preventDefault();
var to = document.getElementById('to').value;
var subject = document.getElementById('subject').value;
var message = document.getElementById('message').value;
var data = {
to: to,
subject: subject,
message: message
};
fetch('/sendEmail', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(function(response) {
if (response.ok) {
alert('邮件发送成功!');
} else {
alert('邮件发送失败!');
}
})
.catch(function(error) {
console.error('邮件发送失败:', error);
});
});
</script>
后端代码(使用Node.js和Nodemailer):
const express = require('express');
const nodemailer = require('nodemailer');
const app = express();
app.use(express.json());
app.post('/sendEmail', function(req, res) {
var to = req.body.to;
var subject = req.body.subject;
var message = req.body.message;
var transporter = nodemailer.createTransport({
host: 'your-smtp-server',
port: 587,
secure: false,
auth: {
user: 'your-username',
pass: 'your-password'
}
});
var mailOptions = {
from: 'your-email@example.com',
to: to,
subject: subject,
text: message
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.error('邮件发送失败:', error);
res.status(500).send('邮件发送失败');
} else {
console.log('邮件发送成功:', info.response);
res.sendStatus(200);
}
});
});
app.listen(3000, function() {
console.log('服务器已启动,监听端口3000');
});
请注意,上述代码仅为示例,你需要根据实际情况进行适当的修改和配置。另外,确保在使用邮件服务器时遵守相关的法律和隐私政策。
领取专属 10元无门槛券
手把手带您无忧上云