I am trying to set up an emailing system for users on my website. I am using nextJS and have an api endpoint to send emails. To send the emails I am using emailJS and sending the email to myself with a custom body. Here is the code for my email.js file:
import { SMTPClient } from 'emailjs';
export default function handler(req, res) {
const {body, subject}=req.body;
// console.log(process.env)
const client = new SMTPClient({
user: "[email protected]",
password: "passward",
host: 'smtp.gmail.com',
ssl:true
});
try{
client.send(
{
text: `${body}`,
from: "[email protected]",
to: "[email protected]",
subject: `${subject}`,
}
)
}
catch (e) {
res.status(400).end(JSON.stringify({ message: e.message }))
return;
}
res.status(200).end(JSON.stringify({ message:'Mail sending' }))
}
The code works when I use it on localhost but it does not work when I deploy to amplify. When I try to make a post request on amplify I get status 200 with the {"message":"Mail sending"}. However, the gmail account never gets the email. I do not get an error message. I do not have 2 step verification on and have allowed less secure apps, but still no emails are being sent. I would really appreciate any help.
The emailjs
library utilizes a queuing system for sending emails. This means that the send
method adds the email to the queue and sends it at a later time. This can cause issues when using the send method within a lambda function, as the function may close before the email has been sent. To ensure that the email is sent before the lambda function closes, you can use the sendAsync
method instead. This method returns a promise that will be resolved when the email has been successfully sent.
To send an email using the sendAsync
method, you can do the following:
await client.sendAsync(
{
text: `${body}`,
from: "[email protected]",
to: "[email protected]",
subject: `${subject}`,
}
)