我创建了一个联系表单,以便在提交表单时向客户发送电子邮件,但在提交表单时不断收到凭据错误。我在这个项目中使用了 React。我的 sendemail.js 文件和服务器文件以及 .env 文件位于根目录中。尽管联系表单位于组件目录中。实际凭据位于 env 文件中。
const nodemailer = require('nodemailer');
const sendEmail = async (formData) => {
// Create a transporter using your email service provider's settings
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.REACT_APP_SMTP_USER, // Ensure these are set in your .env
pass: process.env.REACT_APP_SMTP_PASSWORD, // App-Specific Password for Gmail
}
});
// Setup email data
const mailOptions = {
from: process.env.REACT_APP_SMTP_USER, // Match this with the SMTP_USER
to: formData.email,
subject: formData.subject,
text: `Name: ${formData.name}\nEmail: ${formData.email}\nMessage: ${formData.message}`,
};
// Attempt to send the email
try {
const info = await transporter.sendMail(mailOptions);
console.log('Email sent: ' + info.response);
} catch (error) {
console.error('Error sending email:', error);
throw error; // Consider handling this more gracefully
}
};
module.exports = sendEmail;
const express = require('express');
const sendEmail = require('./sendEmail');
const app = express();
const cors = require('cors');
const port = process.env.PORT || 3001;
const allowedOrigins = ['https://lashesbyjess.net', 'http://localhost:3000'];
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
}));
app.use(express.json());
app.post('/api/send-email', async (req, res) => {
const formData = req.body;
try {
await sendEmail(formData);
res.status(200).send('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
res.status(500).send('Internal Server Error');
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
我尝试过的:
最初,在我运行构建之前,代码就可以运行。意识到我需要重构代码,以便它可以连接到任何服务器,而不仅仅是本地服务器,那就是一切开始改变的时候。
请提供任何帮助,我们将不胜感激,提前致谢!
请验证您的环境文件是否正在nodeMailer函数中加载环境变量。