Reputation: 1
I'm having trouble with my Node.js application where I'm using Nodemailer to send emails through a contact form. The request seems to be processing correctly, and I'm getting a successful response from the Nodemailer sendMail method, but I'm not receiving any emails in my inbox.
Setup:
Backend: Node.js with Express and Nodemailer Email Service: Gmail (using SMTP) Environment: Local development on localhost
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const nodemailer = require('nodemailer');
const app = express();
// CORS Middleware
app.use(cors({
origin: 'http://localhost:3000',
methods: ['GET', 'POST'],
credentials: true,
}));
// Middleware
app.use(express.json());
// Nodemailer setup
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS
}
});
// Contact Form API endpoint
app.post('/api/contact', (req, res) => {
const { name, email, message } = req.body;
const mailOptions = {
from: email,
to: process.env.EMAIL_USER,
subject: `Contact Form Submission from ${name}`,
text: message
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error("Error sending mail: ", error);
return res.status(500).send(error.toString());
}
console.log('Message sent: %s', info.messageId);
res.status(200).send('Message sent: ' + info.response);
});
});
// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
What I've Tried:
Verified that process.env.EMAIL_USER and process.env.EMAIL_PASS are set correctly. Tested with hardcoded email values to rule out issues with form data. Checked the spam/junk folder for the emails. Used Postman to send a test request and received a successful response (Message sent: 250 2.0.0 OK). Question: Despite receiving a success message from Nodemailer, I'm not getting any emails. Are there any common pitfalls or additional settings I should check to resolve this issue? Any insights or troubleshooting steps would be greatly appreciated!
Upvotes: 0
Views: 107
Reputation: 32
The issue is in POST endpoint. The createTransport function is set up for process.env.EMAIL_USER while you are assiging this to "to". process.env.EMAIL_USER should go to "from" attribute and the email from body should go to "to" attribute.
//fix
const mailOptions = {
from: process.env.EMAIL_USER,
to: email,
subject: `Contact Form Submission from ${name}`,
text: message
};
Upvotes: 0