使用 Gmail 帐户通过 Nodemailer 在 Node.JS 中发送电子邮件

2025-06-08

使用 Gmail 帐户通过 Nodemailer 在 Node.JS 中发送电子邮件

环境和依赖项

  • Nodemailer是一个用于发送电子邮件的 Node.JS npm 模块。它已成为大多数 NodeJS 开发者在其应用程序中发送电子邮件的首选解决方案。
  • 确保您已安装 NodeJS 作为运行环境。

先决条件

• 具备 JavaScript 编程的基础知识。
• 了解 Node.JS • 会使用VSCode
等代码编辑器

入门

转到您的项目目录

  • 创建 package.json 文件

npm init -y

  • 安装依赖项

npm i nodemailer -s

  • 创建入口文件邮件文件和邮件模板

touch index.js mailer.js mail-template.js

项目结构

项目结构

注意:要使用 ES6 synthax 导入依赖项,请在 package.json 文件中设置类型:'module'。

包.json

执行

注意:为了了解如何浏览 nodemailer 代码库并了解其实现方式,我使用了askyourcode 这将节省您大量在线查找代码片段和实现的时间。
动图

mail.js

  • 在这个文件中,你首先要从 Nodemailer 创建邮件transporter对象。这个传输器对象会用到你用于发送电子邮件的服务、主机以及最重要的一个auth对象。auth对象基本上就是你的邮箱 ID 和邮箱密码。
import nodemailer from "nodemailer";

// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
  service: "gmail",
  host: "smtp.gmail.com",
  port: 587,
  secure: false,
  auth: {
    user: "MAILID@gmail.com",
    pass: "YOUR PASSWORD",
  },
});
Enter fullscreen mode Exit fullscreen mode
  • 接下来是创建一个可重用的SEND_MAIL函数。该函数应该接受两个参数:邮件详细信息和一个用于处理响应的回调函数。
/** create reusable sendmail function 
@params {object} options - mail options (to, subject, text, html)
@params {function} callback - callback function to handle response
*/
const SENDMAIL = async (mailDetails, callback) => {
  try {
    const info = await transporter.sendMail(mailDetails)
    callback(info);
  } catch (error) {
    console.log(error);
  } 
};
Enter fullscreen mode Exit fullscreen mode
  • 导出此功能,以便您想要发出 SEND_MAIL 的任何文件都可以访问它。
export default SENDMAIL;
Enter fullscreen mode Exit fullscreen mode

HTML 模板 (mail-template.js)

在大多数应用程序中,开发人员需要发送符合应用程序或公司主题的样式化电子邮件。这可以通过 Nodemailer 发送邮件来实现。您需要创建自己的样式化 HTML 模板。以下是模板示例及其使用方法。

// an email template that can be used with Nodemailer to send emails

const HTML_TEMPLATE = (text) => {
  return `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>NodeMailer Email Template</title>
        <style>
          .container {
            width: 100%;
            height: 100%;
            padding: 20px;
            background-color: #f4f4f4;
          }
          .email {
            width: 80%;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
          }
          .email-header {
            background-color: #333;
            color: #fff;
            padding: 20px;
            text-align: center;
          }
          .email-body {
            padding: 20px;
          }
          .email-footer {
            background-color: #333;
            color: #fff;
            padding: 20px;
            text-align: center;
          }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="email">
            <div class="email-header">
              <h1>EMAIL HEADER</h1>
            </div>
            <div class="email-body">
              <p>${text}</p>
            </div>
            <div class="email-footer">
              <p>EMAIL FOOTER</p>
            </div>
          </div>
        </div>
      </body>
    </html>
  `;
}

export default HTML_TEMPLATE;
Enter fullscreen mode Exit fullscreen mode

index.js

这是发送电子邮件的入口文件。它可以是任何您想要执行 SEND_MAIL 命令的文件。
在这里,您需要提供待发送邮件的详细信息,并最终使用mailer.js文件中的 SEND_MAIL 函数。

  • 示例电子邮件详细信息以及如何使用创建的 HTML 模板
import HTML_TEMPLATE from "./mail-template.js";
const message = "Hi there, you were emailed me through nodemailer"
const options = {
    from: "TESTING <sender@gmail.com>", // sender address
    to: "someone@gmail.com", // receiver email
    subject: "Send email in Node.JS with Nodemailer using Gmail account", // Subject line
    text: message
    html: HTML_TEMPLATE(message),
}
Enter fullscreen mode Exit fullscreen mode

注意:message如果您不想使用任何模板,则 html 值可以只是文本变量。

  • 使用创建的对象启动 SEND_MAIL 命令options
import SENDMAIL from "./mailer.js" 
// send mail with defined transport object and mail options
SENDMAIL(options, (info) => {
    console.log("Email sent successfully");
    console.log("MESSAGE ID: ", info.messageId);
});
Enter fullscreen mode Exit fullscreen mode

成功输出

安慰

电子邮件

常见错误

使用 gmail 通过 nodemailer 发送电子邮件时经常遇到的一个错误是Application-specific password required错误。

Error: Invalid login: 534-5.7.9 Application-specific password required. Learn more at
534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor r27-20020a056402035b00b00459012e5145sm10361434edw.70 - gsmtp
    at SMTPConnection._formatError (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:790:19)
    at SMTPConnection._actionAUTHComplete (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:1542:34)   
    at SMTPConnection.<anonymous> (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:546:26)
    at SMTPConnection._processResponse (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:953:20)       
    at SMTPConnection._onData (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:755:14)
    at TLSSocket.SMTPConnection._onSocketData (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:193:44)
    at TLSSocket.emit (node:events:526:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at TLSSocket.Readable.push (node:internal/streams/readable:228:10) {
  code: 'EAUTH',
  response: '534-5.7.9 Application-specific password required. Learn more at\n' +
    '534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor r27-20020a056402035b00b00459012e5145sm10361434edw.70 - gsmtp',
  responseCode: 534,
  command: 'AUTH PLAIN'
}
Enter fullscreen mode Exit fullscreen mode

此错误是由于 Google 使用的安全层保护您的帐户而导致的。您需要创建一个应用密码才能在此情况下使用。

如何修复此错误

  • 登录您的谷歌帐户
  • 在侧边栏中,单击“安全”
  • 向下滚动到使用 Google 登录
  • 单击“应用程序密码”以生成新的应用程序密码仪表盘

生成密码
这将生成一个 16 位字符的xxxx xxxx xxxx xxxx应用密码。
最后,用生成的密码替换 mailer.js 文件中的实际密码(不要包含空格)。
这样应该就能修复错误了!

如果您在实现过程中遇到任何错误,请随时在下面评论。让我们互相帮助。

结论

在本文中,我们仅学习了如何使用 Gmail 服务通过 nodemailer 在 NodeJS 中实现发送电子邮件。
您可以使用askyourcode探索包代码库nodemailer,以获得更多改进 html 模板实现的方法。

快乐黑客!

黑客

如果您觉得本文有用,请点赞、评论并分享。关注我们,获取更多关于 NodeJS 的文章。

鏂囩珷鏉ユ簮锛�https://dev.to/documatic/send-email-in-nodejs-with-nodemailer-using-gmail-account-2gd1
PREV
将 SVG 导入 Next.js 作为文件导入您应该使用哪一个?
NEXT
利用这些技巧和最佳实践来提高代码质量