node.js 基于 STMP 协议和 EWS 协议发送邮件

本文主要介绍 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://lzw.me" rel="external nofollow" rel="external nofollow" >https://lzw.me</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_password)。为字符串时,应为 hex 编码结果 */
 nt_password?: string | Buffer;
 /** 密码加密后的秘钥(NTLMAuth.lm_password)。为字符串时,应为 hex 编码结果 */
 lm_password?: string | Buffer;
 };
 /** Exchange 地址 */
 host?: string;
 /** 邮件主题 */
 subject?: string;
 /** HTML 格式邮件正文内容 */
 html?: string;
 /** TEXT 文本格式邮件正文内容(优先级低于 html 参数) */
 text?: string;
 to?: string;
}

/**
 * 使用 Exchange(EWS) 发送邮件
 */
export async function sendMailByNodeEws(options: IEwsSendOptions) {
 const resultInfo = { code: 0, msg: '', result: null };

 if (!options) {
 resultInfo.code = -1001;
 resultInfo.msg = 'Options can not be null';
 } else if (!options.auth) {
 resultInfo.code = -1002;
 resultInfo.msg = 'Options.auth{user,pass} can not be null';
 } else if (!options.auth.user || (!options.auth.pass && !options.auth.lm_password)) {
 resultInfo.code = -1003;
 resultInfo.msg = 'Options.auth.user or Options.auth.password can not be null';
 }

 if (resultInfo.code) return resultInfo;

 const ewsConfig = {
 username: options.auth.user,
 password: options.auth.pass,
 nt_password: options.auth.nt_password,
 lm_password: options.auth.lm_password,
 host: options.host,
 // auth: 'basic',
 };

 if (ewsConfig.nt_password && typeof ewsConfig.nt_password === 'string') {
 ewsConfig.nt_password = Buffer.from(ewsConfig.nt_password, 'hex');
 }

 if (ewsConfig.lm_password && typeof ewsConfig.lm_password === 'string') {
 ewsConfig.lm_password = Buffer.from(ewsConfig.lm_password, 'hex');
 }

 Object.keys(ewsConfig).forEach(key => {
 if (!ewsConfig[key]) delete ewsConfig[key];
 });

 // initialize node-ews
 const ews = new EWS(ewsConfig);
 // define ews api function
 const ewsFunction = 'CreateItem';
 // define ews api function args
 const ewsArgs = {
 attributes: {
  MessageDisposition: 'SendAndSaveCopy',
 },
 SavedItemFolderId: {
  DistinguishedFolderId: {
  attributes: {
   Id: 'sentitems',
  },
  },
 },
 Items: {
  Message: {
  ItemClass: 'IPM.Note',
  Subject: options.subject,
  Body: {
   attributes: {
   BodyType: options.html ? 'HTML' : 'Text',
   },
   $value: options.html || options.text,
  },
  ToRecipients: {
   Mailbox: {
   EmailAddress: options.to,
   },
  },
  IsRead: 'false',
  },
 },
 };

 try {
 const result = await ews.run(ewsFunction, ewsArgs);
 // console.log('mail sent to:', options.to, ' response:', result);
 resultInfo.result = result;
 if (result.ResponseMessages.MessageText) resultInfo.msg = result.ResponseMessages.MessageText;
 } catch (err) {
 console.log(err.stack);
 resultInfo.code = 1001;
 resultInfo.msg = err.stack;
 }

 return resultInfo;
}

使用 sendMailByNodeEws 方法发送邮件:

sendMailByNodeEws({
 auth: {
 user: 'abc@xxx.com',
 pass: '123456',
 /** 密码加密后的秘钥(NTLMAuth.nt_password)。为字符串时,应为 hex 编码结果 */
 nt_password: '',
 /** 密码加密后的秘钥(NTLMAuth.lm_password)。为字符串时,应为 hex 编码结果 */
 lm_password: '',
 },
 /** Exchange 地址 */
 host: 'https://ews.xxx.com',
 /** 邮件主题 */
 subject: 'subject for test',
 /** HTML 格式邮件正文内容 */
 html: `email content for test: <a href="https://lzw.me" rel="external nofollow" rel="external nofollow" >https://lzw.me</a>`,
 /** TEXT 文本格式邮件正文内容(优先级低于 html 参数) */
 text: '',
 to: 'xxx@lzw.me',
})

2.1.2 基于 NTLMAuth 的认证配置方式

直接配置 pass 密码可能会导致明文密码泄露,我们可以将 pass 字段留空,配置 nt_password 和 lm_password 字段,使用 NTLMAuth 认证模式。此二字段基于 pass 明文生成,其 nodejs 生成方式可借助 httpntlm 模块完成,具体参考如下:

import { ntlm as NTLMAuth } from 'httpntlm';

/** 将输入的邮箱账号密码转换为 NTLMAuth 秘钥(hex)格式并输出 */
const getHashedPwd = () => {
 const passwordPlainText = process.argv.slice(2)[0];

 if (!passwordPlainText) {
 console.log('USEAGE: \n\tnode get-hashed-pwd.js [password]');
 return;
 }

 const nt_password = NTLMAuth.create_NT_hashed_password(passwordPlainText.trim());
 const lm_password = NTLMAuth.create_LM_hashed_password(passwordPlainText.trim());

 // console.log('\n password:', passwordPlainText);
 console.log(` nt_password:`, nt_password.toString('hex'));
 console.log(` lm_password:`, lm_password.toString('hex'));

 return {
 nt_password,
 lm_password,
 };
};

getHashedPwd();

2.2 使用 ews-javascript-api 发送 MS Exchange 邮件

基于 ews-javascript-api 发送邮件的方式,在其官方 wiki 有相关示例,但本人在测试过程中未能成功,具体为无法取得服务器认证,也未能查证具体原因,故以下代码仅作参考:

/**
 * 使用 `ews-javascript-api` 发送(MS Exchange)邮件
 */
export async function sendMailByEwsJApi(options: IEwsSendOptions) {
 const resultInfo = { code: 0, msg: '', result: null };

 if (!options) {
 resultInfo.code = -1001;
 resultInfo.msg = 'Options can not be null';
 } else if (!options.auth) {
 resultInfo.code = -1002;
 resultInfo.msg = 'Options.auth{user,pass} can not be null';
 } else if (!options.auth.user || (!options.auth.pass && !options.auth.lm_password)) {
 resultInfo.code = -1003;
 resultInfo.msg = 'Options.auth.user or Options.auth.password can not be null';
 }

 const ews = require('ews-javascript-api');
 const exch = new ews.ExchangeService(ews.ExchangeVersion.Exchange2010);
 exch.Credentials = new ews.WebCredentials(options.auth.user, options.auth.pass);
 exch.Url = new ews.Uri(options.host);
 ews.EwsLogging.DebugLogEnabled = true; // false to turnoff debugging.

 const msgattach = new ews.EmailMessage(exch);
 msgattach.Subject = options.subject;
 msgattach.Body = new ews.MessageBody(ews.BodyType.HTML, escape(options.html || options.text));
 if (!Array.isArray(options.to)) options.to = [options.to];
 options.to.forEach(to => msgattach.ToRecipients.Add(to));
 // msgattach.Importance = ews.Importance.High;

 // 发送附件
 // msgattach.Attachments.AddFileAttachment('filename to attach.txt', 'c29tZSB0ZXh0');

 try {
 const result = await msgattach.SendAndSaveCopy(); // .Send();
 console.log('DONE!', result);
 resultInfo.result = result;
 } catch (err) {
 console.log('ERROR:', err);
 resultInfo.code = 1001;
 resultInfo.msg = err;
 }
 return resultInfo;
}

3 扩展参考

nodemailer.com/about/
github.com/CumberlandG…
github.com/gautamsi/ew…
github.com/lzwme/node-…

以上就是node.js 基于 STMP 协议和 EWS 协议发送邮件的详细内容,更多关于node.js 发送邮件的资料请关注我们其它相关文章!

(0)

相关推荐

  • 基于Node.js实现nodemailer邮件发送

    Nodemailer是一个简单易用的Node.js邮件发送组件,具体操作如下 1.安装nodemailer npm install nodemailer --save 2.特点 Nodemailer的主要特点包括: 支持Unicode编码 支持Window系统环境 支持HTML内容和普通文本内容 支持附件(传送大附件) 支持HTML内容中嵌入图片 支持SSL/STARTTLS安全的邮件发送 支持内置的transport方法和其他插件实现的transport方法 支持自定义插件处理消息 支持XOA

  • 利用Node.JS实现邮件发送功能

    第一步.配置篇 首先需要安装nodemailer库 npm install nodemailer//默认会安装最新的版本. 关于这个库的文档参见nodemailer 第二步.库的一些使用介绍 这个库使用方法很简单的.首先是要创建一个用于发送邮件的实例 var transporter = nodemailer.createTransport(transport[, defaults]) transport参数属性 属性太多了就只写一些关键的属性 port:连接的端口号,一般就是465 host:你

  • Node.js实现发送邮件功能

    本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下 var nodemailer = require("nodemailer"); var mailTitle='http://handsupowo.pl/:Releases HandsUp Info'; var child_process = require('child_process'); var fs= require('fs'); child_process.execFile('phantomj

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

    本文实例讲述了node.js发送邮件email的方法.分享给大家供大家参考,具体如下: 通常我们做node项目时,可能我们会碰到做一个简单的邮件反馈,那么我们今天就来讨论一下,其中遇到的各种坑. 总的来说做这个东西,我们可能需要node第三方依赖模块,来实现我们要达到的效果. 这里我推荐两个模块:https://github.com/pingfanren/Nodemailer npm install nodemailer //这个模块不错,github上星也比较多,还经常有维护,但是坑也比较多

  • node.js使用nodemailer发送邮件实例

    一.安装 nodemailer 复制代码 代码如下: npm install nodemailer --save 二.调用 复制代码 代码如下: var nodemailer = require("nodemailer"); // 开启一个 SMTP 连接池var smtpTransport = nodemailer.createTransport("SMTP",{  host: "smtp.qq.com", // 主机  secureConne

  • Node.js使用NodeMailer发送邮件实例代码

    0.目标 这一节,我将实现一个简单的发送邮件功能. 1.部署 1.1 部署Express 如果不知道如何部署,可参照:部署Express 1.2 准备一个邮箱并开始SMTP服务 为了实现这个功能,你首先要有一个邮箱:由于需要使用SMTP方式发送,你还需要开启相关功能.你可以登录你的邮箱,然后开启这个设置,以新浪邮箱和QQ邮箱为例: 2.服务器端 2.1 使用nodemailer 这里要用到nodemailer,需要自行安装: npm install nodemailer --save 在rout

  • node.js 基于 STMP 协议和 EWS 协议发送邮件

    本文主要介绍 node.js 发送基于 STMP 协议和 MS Exchange Web Service(EWS) 协议的邮件的方法.文中所有参考代码均以 TypeScript 编码示例. 1 基于 STMP 协议的 node.js 发送邮件方法 提到使用 node.js 发送邮件,基本都会提到大名鼎鼎的 Nodemailer 模块,它是当前使用 STMP 方式发送邮件的首选. 基于 NodeMailer 发送 STMP 协议邮件的文章网上已非常多,官方文档介绍也比较详细,在此仅列举示例代码以供

  • Java下载远程服务器文件到本地(基于http协议和ssh2协议)

    Java中java.io包为我们提供了输入流和输出流,对文件的读写基本上都依赖于这些封装好的关于流的类中来实现.前段时间遇到了以下两种需求: 1.与某系统对接,每天获取最新的图片并显示在前端页面.该系统提供的是一个http协议的图片URL,本来获取到该系统的图片地址以后在HTML中显示就可以了,但是该系统不太稳定,图片URL经常不能使用,而且每天生成图片不一定成功, 对自己系统的功能影响很大,emm...所以就考虑每天从该系统下载最新的图片到本地更新保存,没有新图片就继续使用上次的图片. 2.公

  • node.js基于express使用websocket的方法

    本文实例讲述了node.js基于express使用websocket的方法.分享给大家供大家参考,具体如下: 这个效果我也是翻了好长时间的资料,测试才成功的,反正成功,大家看看吧 首先你需要安装socket.io模块 npm install socket.io --save 然后打开express的app.js将模块引入,在12行左右的 var app = express(); 下面添加两行 var server = require('http').Server(app); var io = r

  • node.js基于fs模块对系统文件及目录进行读写操作的方法详解

    本文实例讲述了node.js基于fs模块对系统文件及目录进行读写操作的方法.分享给大家供大家参考,具体如下: 如果要用这个模块,首先需要引入,fs已经属于node.js自带的模块,所以直接引入即可 var fs = require('fs'); 1.读取文件readFile方法使用 fs.readFile(filename,[option],callback) 方法读取文件. 参数说明: filename String 文件名 option Object   encoding String |n

  • node.js基于dgram数据报模块创建UDP服务器和客户端操作示例

    本文实例讲述了node.js基于dgram数据报模块创建UDP服务器和客户端操作.分享给大家供大家参考,具体如下: node.js中 dgram 模块提供了udp数据包的socket实现,可以方便的创建udp服务器和客户端. 一.创建UDP服务器和客户端 服务端: const dgram = require('dgram'); //创建upd套接字 //参数一表示套接字类型,'udp4' 或 'udp6' //参数二表示事件监听函数,'message' 事件监听器 let server = dg

  • node.js基于socket.io快速实现一个实时通讯应用

    随着web技术的发展,使用场景和需求也越来越复杂,客户端不再满足于简单的请求得到状态的需求.实时通讯越来越多应用于各个领域. HTTP是最常用的客户端与服务端的通信技术,但是HTTP通信只能由客户端发起,无法及时获取服务端的数据改变.只能依靠定期轮询来获取最新的状态.时效性无法保证,同时更多的请求也会增加服务器的负担. WebSocket技术应运而生. WebSocket概念 不同于HTTP半双工协议,WebSocket是基于TCP 连接的全双工协议,支持客户端服务端双向通信. WebSocke

  • Node.js中Request模块处理HTTP协议请求的基本使用教程

    这里来介绍一个Node.js的模块--request.有了这个模块,http请求变的超简单. Request使用超简单,同时支持https和重定向. var request = require('request'); request('http://www.google.com', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // 打印goo

  • 解决Node.js mysql客户端不支持认证协议引发的问题

    前言 mysql模块(项目地址为https://github.com/mysqljs/mysql)是一个开源的.JavaScript编写的MySQL驱动,可以在Node.js应用中来操作MySQL.但在使用过程中,出现了"ER_NOT_SUPPORTED_AUTH_MODE"问题. 本文介绍了出现该问题的原因及解决方案. 报错信息 当我试图使用mysql模块来连接MySQL 8时,出现了如下错误信息: D:\workspaceGithub\nodejs-book-samples\sam

  • 解析Node.js基于模块和包的代码部署方式

    模块路径解析规则 有经验的 C 程序员在编写一个新程序时首先从 make 文件写起.同样的,使用 NodeJS 编写程序前,为了有个良好的开端,首先需要准备好代码的目录结构和部署方式,就如同修房子要先搭脚手架.本章将介绍与之相关的各种知识. 模块路径解析规则 我们已经知道,require函数支持斜杠(/)或盘符(C:)开头的绝对路径,也支持./开头的相对路径.但这两种路径在模块之间建立了强耦合关系,一旦某个模块文件的存放位置需要变更,使用该模块的其它模块的代码也需要跟着调整,变得牵一发动全身.因

  • node.js 基于cheerio的爬虫工具的实现(需要登录权限的爬虫工具)

    公司有过一个需求,需要拿一个网页的的表格数据,数据量达到30w左右:为了提高工作效率. 结合自身经验和网上资料.写了一套符合自己需求的nodejs爬虫工具.也许也会适合你的. 先上代码.在做讲解 'use strict'; // 引入模块 const superagent = require('superagent'); const cheerio = require('cheerio'); const Excel = require('exceljs'); var baseUrl = '';

随机推荐