nodejs :通过自定义 smtp 服务器发送邮件

Flo*_*rel 5 email node.js

我的服务器上安装了 SMTP 服务器,我希望我的 Nodejs 应用程序能够使用它发送邮件。这意味着基本上从 Node js 运行这个命令:

echo "Hello" | mail -s "Test" recipient@domain.com
Run Code Online (Sandbox Code Playgroud)

我知道我可以运行上述命令,但是是否有(希望)更干净的方法来执行此操作?谢谢。

Rid*_*ara 7

如果您想从 node.js 运行任何 CLI 命令来发送邮件,请使用shelljs从您的应用程序运行命令。

\n\n
const shell = require(\'shelljs\');\nshell.exec(\'echo "Hello" | mail -s "Test" recipient@domain.com\')\n
Run Code Online (Sandbox Code Playgroud)\n\n

但一个好方法是使用任何邮件发送包。如果您想使用自己的 SMTP 服务器或外部服务器从 node.js 发送电子邮件,那么Nodemailer是最好的包。

\n\n
const nodemailer = require(\'nodemailer\');\n\n// Generate test SMTP service account from ethereal.email\n// Only needed if you don\'t have a real mail account for testing\nnodemailer.createTestAccount((err, account) => {\n\n    // create reusable transporter object using the default SMTP transport\n    let transporter = nodemailer.createTransport({\n        host: \'smtp.ethereal.email\',\n        port: 587,\n        secure: false, // true for 465, false for other ports\n        auth: {\n            user: account.user, // generated ethereal user\n            pass: account.pass  // generated ethereal password\n        }\n    });\n\n    // setup email data with unicode symbols\n    let mailOptions = {\n        from: \'"Fred Foo " <foo@example.com>\', // sender address\n        to: \'bar@example.com, baz@example.com\', // list of receivers\n        subject: \'Hello \xe2\x9c\x94\', // Subject line\n        text: \'Hello world?\', // plain text body\n        html: \'<b>Hello world?</b>\' // html body\n    };\n\n    // send mail with defined transport object\n    transporter.sendMail(mailOptions, (error, info) => {\n        if (error) {\n            return console.log(error);\n        }\n        console.log(\'Message sent: %s\', info.messageId);\n        // Preview only available when sending through an Ethereal account\n        console.log(\'Preview URL: %s\', nodemailer.getTestMessageUrl(info));\n\n        // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>\n        // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...\n    });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

  • 我要使用nodemailer,看起来更好。但我不知道 shelljs,有一天我会尝试一下。 (3认同)