最近有需求,实现每天查询数据库获取数据后自动发邮件,在网上找node发邮件的资料,大多数是使用nodemailer
,然而公司内部不能访问外网,也即不能通过QQ、网易邮箱这类的发邮件,要想对外发邮件,只能使用公司邮箱。公司邮箱服务器为exchange,Google找了下,发现node-ews
、ews-javascript-api
都可以实现这个功能,前者貌似不怎么更新了,因此最终选择了后者。
实现代码:
const ews = require('ews-javascript-api');
const ewsAuth = require('ews-javascript-api-auth');
const { logger } = require('../log/log');
const credential = {
username: 'username',
password: 'password'
}
ews.ConfigurationApi.ConfigureXHR(new ewsAuth.ntlmAuthXhrApi(credential.username, credential.password));
const exch = new ews.ExchangeService(ews.ExchangeVersion.Exchange2010);
exch.Credentials = new ews.WebCredentials(credential.username, credential.password);
exch.Url = new ews.Uri('https://host/Ews/Exchange.asmx')
// ews.EwsLogging.DebugLogEnabled = true;
/*
subject: 邮件主题
mailAddress: 收件人地址
fileName: 发送附件的名称
data: 附件内容,base64格式
*/
exports.sendEwsMail = (subject, mailAddress, fileName, data) => {
const msgattach = new ews.EmailMessage(exch);
msgattach.Subject = subject;
msgattach.Body = new ews.MessageBody('DO NOT REPLY! This is Automatic E-Mail Sent');
msgattach.ToRecipients.Add(mailAddress);
msgattach.Attachments.AddFileAttachment(fileName, data);
msgattach.SendAndSaveCopy().then((res) => {
logger.info(res)
}, (err) => {
logger.info(err.stack)
})
}
一开始未引入ews-javascript-api-auth
这个库,执行代码报错401 UnAuthorized
,身份验证不通过,引入该库,并加上下面这句代码解决。
ews.ConfigurationApi.ConfigureXHR(new ewsAuth.ntlmAuthXhrApi(credential.username, credential.password));