PHP前端开发

掌握 Nodejs 中的电子邮件发送:分步指南

百变鹏仔 3天前 #JavaScript
文章标签 邮件发送

发送电子邮件是许多 web 应用程序中的常见功能,无论是用于用户注册、密码重置还是营销活动。在本指南中,我们将向您展示如何在 nodemailer 模块的帮助下使用 node.js 发送电子邮件。我们将涵盖从设置项目到发送 html 电子邮件和处理附件的所有内容。


1.开始使用您的 node.js 电子邮件项目

首先,您需要设置一个新的 node.js 项目来发送电子邮件。

  mkdir emailtest  cd emailtest
  {    "name": "emailtest",    "version": "1.0.0",    "main": "index.js",    "dependencies": {      "nodemailer": "^6.0.0"    }  }
  npm install

2.发送您的第一封电子邮件

现在您的项目已设置完毕,让我们发送一封简单的电子邮件。

  import nodemailer from 'nodemailer';  const transporter = nodemailer.createtransport({    host: 'smtp.freesmtpservers.com',    port: 25  });  const mailoptions = {    from: '"test email" <test>',    to: 'someone@example.com',    subject: 'hello!',    text: 'hello world!',    html: '<p>hello world!</p>'  };  transporter.sendmail(mailoptions, (error, info) =&gt; {    if (error) {      console.log('error:', error);    } else {      console.log('email sent:', info.response);    }  });</test>
  node index.js

您应该会看到电子邮件已发送的确认信息。


3.添加附件到您的电子邮件

如果您需要通过电子邮件发送文件,nodemailer 让这一切变得简单。

  const mailoptions = {    from: '"test email" <test>',    to: 'someone@example.com',    subject: 'hello with attachments!',    text: 'please find the attached files.',    attachments: [      {        filename: 'test.txt',        path: './test.txt' // local file      },      {        filename: 'example.txt',        content: 'this is a text file content.' // content as string      }    ]  };</test>

4.发送 html 电子邮件

html 电子邮件可以通过格式、图像和链接使您的邮件更具吸引力。

  const mailoptions = {    from: '"test email" <test>',    to: 'someone@example.com',    subject: 'hello, html!',    html: '<h1>hello world!</h1><p>this is an html email.</p>'  };</test>

5.处理错误

处理错误以确保您的应用程序顺利运行非常重要。

  transporter.sendMail(mailOptions, (error, info) =&gt; {    if (error) {      console.log('Error:', error.message);    } else {      console.log('Email sent:', info.response);    }  });

结论

使用 node.js 和 nodemailer 发送电子邮件非常简单。只需几行代码,您就可以发送纯文本或 html 电子邮件、附加文件并高效处理错误。随着您的需求增长,您可以探索更高级的功能,例如与专用电子邮件服务集成和管理异步电子邮件队列。