尝试获取它,以便当单击“发送电子邮件”按钮时,它会将其发送到 mailhog 收件箱,但它实际上什么也没做,甚至没有任何控制台错误或终端中的任何内容。我想做的是使用nodemailer将表单中的姓名、电子邮件、选择的计划和消息发送到mailhog地址,但是当我单击发送按钮时,终端或浏览器控制台中没有显示任何内容,它所做的只是当我将其与网站上的其余内容设置好后,用代码缩进网址。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="test.css">
</head>
<body>
<section id="contact" class="fade-in">
<h2>Contact Us</h2>
<p>Let's discuss your project! Fill out the form below.</p>
<form id="contactForm" onsubmit="submitOrder(event)" >
<!-- Your form fields here -->
<!-- Example: -->
<input type="text" name="name" id="name" placeholder="Your Name" required>
<input type="email" name="email" id="email" placeholder="Your Email" required>
<input type="text" name="chosen-plan" id="chosen-plan" placeholder="Chosen Plan" required>
<textarea name="message" id="message" placeholder="Your Message" rows="4" required></textarea>
<button id="msg-btn">
<div class="svg-wrapper-1">
<div class="svg-wrapper">
<svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0h24v24H0z" fill="none"></path>
<path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path>
</svg>
</div>
</div>
<span>Send Message</span>
</button>
</form>
</section>
<footer>
<div class="container">
<p>footer/p>
</div>
</footer>
<script>
async function submitOrder(event) {
event.preventDefault(); // Prevent form submission and page reload
console.log('Function executed');
// Get customer details from the form
const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
const chosenPlanInput = document.getElementById('chosen-plan');
const messageInput = document.getElementById('message');
const name = nameInput.value;
const email = emailInput.value;
const chosenPlan = chosenPlanInput.value;
const message = messageInput.value;
console.log('Customer:', { name, email, chosenPlan, message });
// You can add more fields to the customer object if needed
const customer = {
name,
email,
chosenPlan,
message,
};
try {
// Send the data to the server
const response = await fetch('/send-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ customer }),
});
console.log('Response:', response);
if (response.ok) {
// Email sent successfully
console.log('Email sent successfully');
// Handle any further actions or display success message if needed
} else {
// Error sending email
console.error('Error sending email');
// Handle error if needed
}
} catch (error) {
console.error('Error sending email:', error);
// Handle error if needed
}
}
const sendButton = document.getElementById('msg-btn');
sendButton.addEventListener('click', submitOrder);
</script>
</body>
</html>
发送电子邮件.js:
const nodemailer = require('nodemailer');
async function sendEmail(customer) {
try {
// Create a Nodemailer transporter with SMTP credentials
const transporter = nodemailer.createTransport({
host: 'localhost',
port: 1025, });
// Construct the email message
const message = {
from: 'noreply@mailhog.example',
to: 'example@mailhog.example',
subject: 'New Contact Request',
html: `
<h3>Contact Request</h3>
<p>Name: ${customer.name}</p>
<p>Email: ${customer.email}</p>
<p>Chosen Plan: ${customer.chosenPlan}</p>
<p>Message: ${customer.message}</p>
`,
};
// Send the email
const info = await transporter.sendMail(message);
console.info('Email sent:', info.messageId);
} catch (error) {
console.error('Error sending email:', error);
throw error; // Re-throw the error to be caught in the calling function (in your server file)
}
}
module.exports = sendEmail;
服务器.js:
const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const sendEmail = require('./sendEmail'); // Import the Nodemailer function
const app = express();
const PORT = 3000; // Choose a suitable port number
// Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Enable CORS
app.use(cors());
app.use(express.static('pb'));
app.get('*', async (req, res, next) => {
try {
res.status(200);
res.send();
} catch (error) {
next(error);
}
});
// POST endpoint for receiving order details and sending email
app.post('/send-email', async (req, res) => {
console.log('Received POST request:', req.body); // Add this line to check the received data
const { customer } = req.body;
// Check if 'order' and 'customer' objects are present in the request body
if (!customer) {
res
.status(400)
.send('Invalid request: "customer" objects are required.');
return;
}
// Check if 'name', 'email', and 'phone' properties are present in the 'customer' object
if (!customer.name || !customer.email) {
res
.status(400)
.send(
'Invalid request: "name", "email" properties are required in the "customer" object.',
);
return;
}
const payload = { ...customer };
try {
// Send the email using the sendEmail function with the payload
await sendEmail(payload);
res.status(200).send('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
res.status(500).send('Error sending email');
}
});
// Error handling middleware
app.use((req, res) => res.status(404).send('Not Found'));
app.use((err, req, res) => {
console.error('Unhandled error', err);
res.status(500);
res.send(JSON.stringify(err));
});
// Start the server
app.listen(PORT, () => {
console.info(`Server started on port ${PORT}`);
});
您的 sendEmail.js 文件中缺少传输器中的配置
const transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "******@gmail.com",
pass: "gmail_password"
}
});
您必须提供要从哪个电子邮件地址发送邮件的凭据。
如果您想要一个不会泄露密码的更安全的选项,您可以查看此博客https://dev.to/chandrapantachhetri/sending-emails-securely-using-node-js-nodemailer-smtp-gmail-and-oauth2-g3a