首页 > 语言 > JavaScript > 正文

node.js发送邮件email的方法详解

2024-05-06 15:03:26
字体:
来源:转载
供稿:网友

本文实例讲述了node.js发送邮件email的方法。分享给大家供大家参考,具体如下:

通常我们做node项目时,可能我们会碰到做一个简单的邮件反馈,那么我们今天就来讨论一下,其中遇到的各种坑。

总的来说做这个东西,我们可能需要node第三方依赖模块,来实现我们要达到的效果。

这里我推荐两个模块:https://github.com/pingfanren/Nodemailer

npm install nodemailer//这个模块不错,github上星也比较多,还经常有维护,但是坑也比较多

另一个,https://github.com/eleith/emailjs

npm install emailjs --save

这里我用的是nodemailer模块,毕竟用的人比较多,跟随主流呢

它的特点:

使用Unicode编码
支持Windows系统,不需要安装依赖
支持纯文本和HTML格式
支持发送附件(包括大型附件)
在HTML中嵌入图片
支持SSL/STARTTLS安全协议
不同的传输方法,可以使用内置也可以使用外部插件的形式
提供自定义插件支持(比如增加DKIM签名,使用markdown代替HTML等等)
支持XOAUTH2登录验证(以及关于更新的令牌反馈)

安装使用

npm install nodemailer --save

使用内置传输发送邮件,可以查看支持列表:https://github.com/andris9/nodemailer-wellknown#supported-services

var nodemailer = require('nodemailer');var transporter = nodemailer.createTransport({  //https://github.com/andris9/nodemailer-wellknown#supported-services 支持列表  service: 'qq',  port: 465, // SMTP 端口  secureConnection: true, // 使用 SSL  auth: {    user: '768065158@qq.com',    //这里密码不是qq密码,是你设置的smtp密码    pass: '*****'  }});// NB! No need to recreate the transporter object. You can use// the same transporter object for all e-mails// setup e-mail data with unicode symbolsvar mailOptions = {  from: '768065158@qq.com', // 发件地址  to: '528779822@qq.com', // 收件列表  subject: 'Hello sir', // 标题  //text和html两者只支持一种  text: 'Hello world ?', // 标题  html: '<b>Hello world ?</b>' // html 内容};// send mail with defined transport objecttransporter.sendMail(mailOptions, function(error, info){  if(error){    return console.log(error);  }  console.log('Message sent: ' + info.response);});

发送邮件成功以后我们很少会有操作,但也有极少数情况需要在成功以后会处理一些特殊信息的,这时候info对象就能发挥余热了。info对象中包含了messageId、envelop、accepted和response等属性,具体看文档我不一一介绍了。

使用其他传输插件   https://github.com/andris9/nodemailer-smtp-transport

npm install nodemailer-smtp-transport --save

其他代码类似,差别只是在创建transport上,所以这里我就写一部分代码:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选