I am using nextjs app Dir. I need to send emails which I am sending with nodemailer, and I am required to use server components since you cannot send with clientside.
I am using typescript in this project and I have some issues using a function that is server side to a client side.
What I done
- I created a function that sends email and accepts parameters with types, the important one being
toEmail
one which should be a string only. I used'use server'
, because I had other errors where the solution was to make it a server component.
'use server'
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
// host: 'smtp.ethereal.email',
// port: 587,
service: 'gmail',
secure: false,
auth: {
user: process.env.EMAIL,
pass: process.env.EMAIL_PASSWORD,
},
});
export const sendEmail = async (toEmail: string, subject: string, html: string) => {
await transporter.sendMail({
from : process.env.EMAIL_ADMIN_QUOTE_RECEIVER,
to: toEmail,
subject: subject,
html: html
});
};
```;
2. Secondly, I created the client component that gets the state and finally the one that sends the email. However, Because I want to use env variables, the `toEmail` parameter cannot accept `string | undefined`, because it should be strictly a string. If i log the `process.env.EMAIL_ADMIN_QUOTE_RECEIVER` in the console, I get the result in the server console, but in the browser is undefined....
This component is a 'use client' component
Here is the function:
const handleSendQuote = async (event: FormEvent) => { event.preventDefault();
const emailHTML = render(<NewQuoteReceived
name={fullName} dateRequired={dateRequired}
vechNeeded={vechiclesRequired} serviceReq={service}
phone={phoneNumber} email={email}
details={details} />)
await sendEmail(process.env.EMAIL_ADMIN_QUOTE_RECEIVER, 'New quote received', emailHTML);
alert('Sent');
clearState();
}