
发送电子邮件是许多 web 应用程序中的常见功能,无论是用于用户注册、密码重置还是营销活动。在本指南中,我们将向您展示如何在 nodemailer 模块的帮助下使用 node.js 发送电子邮件。我们将涵盖从设置项目到发送 html 电子邮件和处理附件的所有内容。
1.开始使用您的 node.js 电子邮件项目
首先,您需要设置一个新的 node.js 项目来发送电子邮件。
创建项目文件夹
mkdir emailtest cd emailtest
初始化您的项目创建包含以下内容的 package.json 文件:
{ "name": "emailtest", "version": "1.0.0", "main": "index.js", "dependencies": { "nodemailer": "^6.0.0" } }
安装 nodemailer通过运行以下命令安装所需的 nodemailer 模块:
npm install
2.发送您的第一封电子邮件
现在您的项目已设置完毕,让我们发送一封简单的电子邮件。
创建一个index.js文件添加以下代码以发送电子邮件:
import nodemailer from 'nodemailer'; const transporter = nodemailer.createtransport({ host: 'smtp.freesmtpservers.com', port: 25 }); const mailoptions = { from: '"test email" ', to: 'someone@example.com', subject: 'hello!', text: 'hello world!', html: 'hello world!
' }; transporter.sendmail(mailoptions, (error, info) => { if (error) { console.log('error:', error); } else { console.log('email sent:', info.response); } });
运行你的代码使用 node.js 运行代码:
node index.js
您应该会看到电子邮件已发送的确认信息。
3.添加附件到您的电子邮件
如果您需要通过电子邮件发送文件,nodemailer 让这一切变得简单。
光子AI
AI电商服饰商拍平台
210 查看详情
带有附件的示例
const mailoptions = { from: '"test email" ', 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 } ] };
4.发送 html 电子邮件
html 电子邮件可以通过格式、图像和链接使您的邮件更具吸引力。
html 电子邮件示例
const mailoptions = { from: '"test email" ', to: 'someone@example.com', subject: 'hello, html!', html: 'hello world!
this is an html email.
' };
5.处理错误
处理错误以确保您的应用程序顺利运行非常重要。
错误处理示例
transporter.sendMail(mailOptions, (error, info) => { if (error) { console.log('Error:', error.message); } else { console.log('Email sent:', info.response); } });
结论
使用 node.js 和 nodemailer 发送电子邮件非常简单。只需几行代码,您就可以发送纯文本或 html 电子邮件、附加文件并高效处理错误。随着您的需求增长,您可以探索更高级的功能,例如与专用电子邮件服务集成和管理异步电子邮件队列。
以上就是掌握 Nodejs 中的电子邮件发送:分步指南的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/457834.html
微信扫一扫
支付宝扫一扫