站长图库向大家介绍了node.js,基于 STMP 协议, EWS 协议,发送邮件等相关知识,希望对您有所帮助
这篇文章主要介绍了node.js 基于 STMP 协议和 EWS 协议发送邮件的示例,帮助大家更好的理解和使用node.js,感兴趣的朋友可以了解下
本文主要介绍 node.js 发送基于 STMP 协议和 MS Exchange Web Service(EWS) 协议的邮件的方法。文中所有参考代码均以 TypeScript 编码示例。
1、基于 STMP 协议的 node.js 发送邮件方法
提到使用 node.js 发送邮件,基本都会提到大名鼎鼎的 Nodemailer 模块,它是当前使用 STMP 方式发送邮件的首选。
基于 NodeMailer 发送 STMP 协议邮件的文章网上已非常多,官方文档介绍也比较详细,在此仅列举示例代码以供对比参考:
封装一个 sendMail 邮件发送方法:
/** * 使用 Nodemailer 发送 STMP 邮件 * @param {Object} opts 邮件发送配置 * @param {Object} smtpCfg smtp 服务器配置 */async function sendMail(opts, smtpCfg) { const resultInfo = { code: 0, msg: '', result: null }; if (!smtpCfg) { resultInfo.msg = '未配置邮件发送信息'; resultInfo.code = - 1009; return resultInfo; } // 创建一个邮件对象 const mailOpts = Object.assign( { // 发件人 from: `Notify <${smtpCfg.auth.user}>`, // 主题 subject: 'Notify', // text: opts.content, // html: opts.content, // 附件内容 // /*attachments: [{ // filename: 'data1.json', // path: path.resolve(__dirname, 'data1.json') // }, { // filename: 'pic01.jpg', // path: path.resolve(__dirname, 'pic01.jpg') // }, { // filename: 'test.txt', // path: path.resolve(__dirname, 'test.txt') // }],*/ }, opts ); if (!mailOpts.to) mailOpts.to = []; if (!Array.isArray(mailOpts.to)) mailOpts.to = String(mailOpts.to).split(','); mailOpts.to = mailOpts.to.map(m => String(m).trim()).filter(m => m.includes('@')); if (!mailOpts.to.length) { resultInfo.msg = '未配置邮件接收者'; resultInfo.code = - 1010; return resultInfo; } const mailToList = mailOpts.to; const transporter = nodemailer.createTransport(smtpCfg); // to 列表分开发送 for (const to of mailToList) { mailOpts.to = to.trim(); try { const info = await transporter.sendMail(mailOpts); console.log('mail sent to:', mailOpts.to, ' response:', info.response); resultInfo.msg = info.response; } catch (error) { console.log(error); resultInfo.code = -1001; resultInfo.msg = error; } } return resultInfo;}使用 sendMail 方法发送邮件:
const opts = { subject: 'subject for test', /** HTML 格式邮件正文内容 */ html: `email content for test: <a href="https://www.zztuku.com" rel="external nofollow" rel="external nofollow" >https://www.zztuku.com</a>`, /** TEXT 文本格式邮件正文内容 */ text: '', to: 'xxx@lzw.me', // 附件列表 // attachments: [],};const smtpConfig = { host: 'smtp.qq.com', //QQ: smtp.qq.com; 网易: smtp.163.com port: 465, //端口号。QQ邮箱 465,网易邮箱 25 secure: true, auth: { user: 'xxx@qq.com', //邮箱账号 pass: '', //邮箱的授权码 },};sendMail(opts, smtpConfig).then(result => console.log(result));2、基于 MS Exchange 邮件服务器的 node.js 发送邮件方法
对于使用微软的 Microsoft Exchange Server 搭建的邮件服务,Nodemailer 就无能为力了。Exchange Web Service(EWS)提供了访问 Exchange 资源的接口,在微软官方文档中对其有详细的接口定义文档。针对 Exchange 邮件服务的流行第三方库主要有 node-ews 和 ews-javascript-api。
2.1 使用 node-ews 发送 MS Exchange 邮件
下面以 node-ews 模块为例,介绍使用 Exchange 邮件服务发送邮件的方法。
2.1.1 封装一个基于 node-ews 发送邮件的方法
封装一个 sendMailByNodeEws 方法:
import EWS from 'node-ews';export interface IEwsSendOptions { auth: { user: string; pass?: string; /** 密码加密后的秘钥(NTLMAuth.nt_passwor

