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;
}
|