Question
Backend JavaScript file EmailJS send error
I'm trying to make a route for my backend javascript express server server.js
which will send an email using EmailJS to my gmail account when called.
If I try this code:
const SMTPClient = require("emailjs")
app.post('/emailContactFormSubmission', async (req, res) => {
const { body, email } = req.body;
console.log('Contact form submission received:');
console.log('Body:', body);
console.log('Email:', email);
try {
const client = new SMTPClient({
user: 'myemail@gmail.com',
password: 'abcd abcd abcd abcd', // myemail@gmail.com' app password
host: 'smtp.gmail.com',
ssl: true,
});
const message = await client.sendAsync({
text: 'i hope this works',
from: '',
to: 'myemail@gmail.com',
cc: '',
subject: 'testing emailjs',
});
console.log('message = ', message);
res.sendStatus(200);
} catch (err) {
console.error('send email err: ', err);
res.sendStatus(400);
}
});
The server fails immediately when I run it with node server.js
> node .\server.js
C:\Users\marti\Documents\projects\aws-react-docker-ghactions\server.js:125
const SMTPClient = require("emailjs")
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\marti\Documents\projects\aws-react-docker-ghactions\node_modules\emailjs\email.js from C:\Users\marti\Documents\projects\aws-react-docker-ghactions\server.js not supported.
Instead change the require of email.js in C:\Users\marti\Documents\projects\aws-react-docker-ghactions\server.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (C:\Users\marti\Documents\projects\aws-react-docker-ghactions\server.js:125:20) {
code: 'ERR_REQUIRE_ESM'
}
Node.js v20.15.0
If I change the import line to:
const SMTPClient = require("@emailjs/browser")
My node server launches correctly, but once the route is hit, there's a different error:
> node .\server.js
setSecrets()
isLocal= true
Secrets set successfully
Server is running on port 3030
Contact form submission received:
Body: a
Email: adam@joe.omc
send email err: TypeError: SMTPClient is not a constructor
at C:\Users\marti\Documents\projects\aws-react-docker-ghactions\server.js:135:20
Am I using the EmailJS package correctly? How can I get the send email functionaltiy working with my gmail address, so when the server.js route is hit, it sends an email to my account myemail@gmail.com