我正试图为我的后端javascript express服务器创建一条路由
server.js
当被调用时,它将使用EmailJS向我的gmail帐户发送一封电子邮件。
如果我尝试这段代码:
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);
}
});
当我用以下命令运行服务器时,服务器立即发生故障
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
如果我将导入行更改为:
const SMTPClient = require("@emailjs/browser")
我的节点服务器正确启动,但一旦路由被命中,就会出现另一个错误:
> 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:\Users\marti\Documents\projects\aws-react-docker-ghactions\server.js:135:20
我是否正确使用了EmailJS包?我如何使用我的gmail地址来使用发送电子邮件功能,这样当server.js路由被点击时,它会向我的帐户发送一封电子邮件
[email protected]