I'm trying to send a message to the owner of a listing but recipient is getting the email from my gmail account and not of the user that is contacting the owner. It's using 'process.env.EMAIL_USER' rather than the currentUserEmail. Maybe it's using the email from process.env.EMAIL_USER but I thought that's to make setup so that we can send emails
import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux';
export default function Contact({listing}) {
const {currentUser} = useSelector((state) => state.user);
const currentUserEmail = currentUser.email;
const [landlord, setLandlord] = useState(null);
const [message, setMessage] = useState('');
const onChange = (e) => {
setMessage(e.target.value);
}
const sendEmail = async () => {
try {
const res = await fetch('/api/contact/send-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: currentUserEmail,
to: landlord.email,
subject: `Regarding ${listing.name}`,
text: message,
})
});
if (!res.ok) {
throw new Error('Failed to send email');
}
alert('Email sent successfully');
const data = await res.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
useEffect(()=>{
const fetchLandlord = async () => {
try {
const res = await fetch(`/api/user/${listing.userRef}`);
const data = await res.json();
setLandlord(data);
} catch (error) {
console.log(error);
}
}
fetchLandlord();
}, [listing.userRef])
return (
<>
{landlord && (
<div className='flex flex-col gap-2'>
<p>Contact <span className='font-semibold'>{landlord.username}</span> for <span className='font-semibold'>{listing.name.toLowerCase()}</span></p>
<textarea name="message" id="message" rows="2" value={message} onChange={onChange} placeholder='Enter your message here...' className='w-full border p-3 rounded-lg '></textarea>
<button onClick={sendEmail} className='bg-slate-700 text-white text-center p-3 rounded-lg uppercase hover:opacity-95'>
Send Message
</button>
</div>
)}
</>
)
}
This is the controller:
import nodemailer from 'nodemailer';
import dotenv from "dotenv";
dotenv.config();
export const sendEmail = async (req, res, next) => {
const { from, to, subject, text } = req.body;
try {
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS
}
});
const mailOptions = {
from: from,
to: to,
subject: subject,
text: text
};
await transporter.sendMail(mailOptions);
res.status(200).json({ success: true, message: "Email send successfully." });
} catch (error) {
next(error);
}
};