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: '[email protected]',
password: 'abcd abcd abcd abcd', // [email protected]' app password
host: 'smtp.gmail.com',
ssl: true,
});
const message = await client.sendAsync({
text: 'i hope this works',
from: '',
to: '[email protected]',
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:UsersmartiDocumentsprojectsaws-react-docker-ghactionsserver.js:125
const SMTPClient = require("emailjs")
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:UsersmartiDocumentsprojectsaws-react-docker-ghactionsnode_modulesemailjsemail.js from C:UsersmartiDocumentsprojectsaws-react-docker-ghactionsserver.js not supported.
Instead change the require of email.js in C:UsersmartiDocumentsprojectsaws-react-docker-ghactionsserver.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (C:UsersmartiDocumentsprojectsaws-react-docker-ghactionsserver.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: [email protected]
send email err: TypeError: SMTPClient is not a constructor
at C:UsersmartiDocumentsprojectsaws-react-docker-ghactionsserver.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 [email protected]
2
Answers
The package you’re trying to use is an ES Module. To use it in CommonJS (files that use
require()
, import it this way):Alternatively, switch to ESM yourself. It’s the future and more and more packages will switch to this format.
Use this
const {SMTPClient} = require('emailjs')
since to use the SMTPClient from the emailjs package with CommonJS syntax, you should import it using curly braces, similar to the ES6 module import shown in the official guide.