返回

用 Node.js 由内而外深谙两种途径发送邮件,囊括SMTP和MS Exchange

前端

使用 Node.js 发送基于 SMTP 和 MS Exchange 邮件

谈及 Node.js 发送邮件,Nodemailer 模块可谓大名鼎鼎。它简单易用,支持各种邮件服务提供商,是许多开发者的首选。然而,当涉及到与 Microsoft Exchange 服务器的交互时,Nodemailer 就显得力不从心了。这是因为 Exchange 服务器使用的是专有协议 —— Exchange Web Service (EWS),而 Nodemailer 并不能直接支持。

不过,别担心,发送邮件给 Exchange 服务器并非无计可施。你可以借助 Exchange Web Service (EWS) 模块,它能让你轻松实现与 Exchange 服务器的通信。

基于 SMTP 发送邮件

Nodemailer 简介

Nodemailer 是一个功能强大的 Node.js 模块,可以发送邮件。它支持各种邮件服务提供商,如 Gmail、Outlook、Yahoo 等。

要使用 Nodemailer,首先需要安装它。你可以使用以下命令进行安装:

npm install nodemailer

安装完成后,就可以开始使用 Nodemailer 发送邮件了。Nodemailer 提供了多种发送邮件的方法,最常用的是 sendMail() 方法。sendMail() 方法接受一个 mailOptions 对象作为参数,mailOptions 对象包含了邮件的各种信息,比如发件人、收件人、主题、正文等。

以下是一个使用 Nodemailer 发送邮件的示例:

const nodemailer = require('nodemailer');

// 创建一个 SMTP 客户端
const transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  secure: false, // true for 465, false for other ports
  auth: {
    user: 'username', // generated ethereal user
    pass: 'password'  // generated ethereal password
  }
});

// 设置邮件选项
const mailOptions = {
  from: 'example@example.com', // sender address
  to: 'example@example.com', // list of receivers
  subject: 'Hello', // Subject line
  text: 'Hello world!', // plain text body
  html: '<b>Hello world!</b>' // html body
};

// 发送邮件
transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.log(error);
  } else {
    console.log('Message sent: %s', info.messageId);
  }
});

基于 MS Exchange 发送邮件

Exchange Web Service (EWS) 模块简介

Exchange Web Service (EWS) 模块是一个 Node.js 模块,可以让你与 Exchange 服务器进行交互。它提供了多种方法来管理 Exchange 服务器上的邮件、日历、联系人等。

要使用 Exchange Web Service (EWS) 模块,首先需要安装它。你可以使用以下命令进行安装:

npm install exchange-web-service

安装完成后,就可以开始使用 Exchange Web Service (EWS) 模块发送邮件了。Exchange Web Service (EWS) 模块提供了多种发送邮件的方法,最常用的是 sendItem() 方法。sendItem() 方法接受一个 item 对象作为参数,item 对象包含了邮件的各种信息,比如发件人、收件人、主题、正文等。

以下是一个使用 Exchange Web Service (EWS) 模块发送邮件的示例:

const ExchangeService = require('exchange-web-service');

// 创建一个 Exchange 服务客户端
const service = new ExchangeService({
  username: 'username',
  password: 'password',
  url: 'https://outlook.office365.com/EWS/Exchange.asmx'
});

// 设置邮件选项
const item = {
  From: {
    Address: 'example@example.com'
  },
  ToRecipients: [
    {
      Address: 'example@example.com'
    }
  ],
  Subject: 'Hello',
  Body: {
    BodyType: 'Text',
    Value: 'Hello world!'
  }
};

// 发送邮件
service.sendItem(item, (error, result) => {
  if (error) {
    console.log(error);
  } else {
    console.log('Message sent successfully.');
  }
});

总结

本文详细介绍了使用 Node.js 发送邮件的两种主要途径:基于 SMTP 协议和基于 MS Exchange Web Service (EWS) 协议。通过阅读本文,你将了解到如何使用 Nodemailer 和 Exchange Web Service (EWS) 模块来发送邮件,并能够根据自己的需求选择合适的方法。