要通过React.js/Express.js中的用户输入字段向地址发送电子邮件,可以按照以下步骤进行:
nodemailer
库来发送电子邮件。nodemailer
库的createTransport
方法创建一个邮件传输对象。sendMail
方法发送邮件,将用户输入的字段作为邮件的收件人、主题和内容。以下是一个示例代码:
在React.js中的表单组件:
import React, { useState } from 'react';
const EmailForm = () => {
const [recipient, setRecipient] = useState('');
const [subject, setSubject] = useState('');
const [content, setContent] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
fetch('/send-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ recipient, subject, content }),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error:', error);
});
};
return (
<form onSubmit={handleSubmit}>
<label>
Recipient:
<input
type="email"
value={recipient}
onChange={(e) => setRecipient(e.target.value)}
/>
</label>
<label>
Subject:
<input
type="text"
value={subject}
onChange={(e) => setSubject(e.target.value)}
/>
</label>
<label>
Content:
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
/>
</label>
<button type="submit">Send Email</button>
</form>
);
};
export default EmailForm;
在Express.js中的路由:
const express = require('express');
const nodemailer = require('nodemailer');
const router = express.Router();
router.post('/send-email', (req, res) => {
const { recipient, subject, content } = req.body;
const transporter = nodemailer.createTransport({
host: 'your-smtp-host',
port: 587,
secure: false,
auth: {
user: 'your-email',
pass: 'your-password',
},
});
const mailOptions = {
from: 'your-email',
to: recipient,
subject,
text: content,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error(error);
res.status(500).json({ message: 'Failed to send email' });
} else {
console.log('Email sent:', info.response);
res.json({ message: 'Email sent successfully' });
}
});
});
module.exports = router;
请注意,上述代码中的SMTP服务器、端口号、身份验证信息需要根据你使用的邮件服务提供商进行配置。此外,还需要在Express.js应用程序中配置路由和中间件来处理这个路由。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)
领取专属 10元无门槛券
手把手带您无忧上云