您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

如何使用 SendGrid 从 Node.js 发送电子邮件How to Send Email Using SendGrid from Node.js

本指南演示了如何在 Azure 上使用 SendGrid 电子邮件服务执行常见编程任务。This guide demonstrates how to perform common programming tasks with the SendGrid email service on Azure. 相关示例是使用 Node.js API 编写的。The samples are written using the Node.js API. 涉及的任务包括 创建电子邮件发送电子邮件添加附件使用筛选器更新属性The scenarios covered include constructing email, sending email, adding attachments, using filters, and updating properties. 有关 SendGrid 和发送电子邮件的详细信息,请参阅后续步骤部分。For more information on SendGrid and sending email, see the Next Steps section.

什么是 SendGrid 电子邮件服务?What is the SendGrid Email Service?

SendGrid 是一项基于云的电子邮件服务,该服务提供了可靠的事务电子邮件传递、伸缩性、实时分析以及可用于简化自定义集成的灵活的 API。SendGrid is a cloud-based email service that provides reliable transactional email delivery, scalability, and real-time analytics along with flexible APIs that make custom integration easy. 常见 SendGrid 使用方案包括:Common SendGrid usage scenarios include:

  • 自动向客户发送收据Automatically sending receipts to customers
  • 管理用于每月向客户发送电子传单和特惠产品/服务的通讯组列表Administering distribution lists for sending customers monthly e-fliers and special offers
  • 收集诸如已阻止的电子邮件和客户响应性等项目的实时度量值Collecting real-time metrics for things like blocked e-mail, and customer responsiveness
  • 生成用于帮助确定趋势的报告Generating reports to help identify trends
  • 转发客户查询Forwarding customer inquiries
  • 以电子邮件的形式从应用程序发送通知Email notifications from your application

有关详细信息,请参阅 https://sendgrid.comFor more information, see https://sendgrid.com.

创建 SendGrid 帐户Create a SendGrid Account

注册 SendGrid 帐户To sign up for a SendGrid account

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 在 "Azure 门户" 菜单或 "主页" 中,选择 " 创建资源"。In the Azure portal menu or the home page, select Create a resource.

    选择 "创建资源" 选项的 "Azure 门户" 菜单的屏幕截图。

  3. 搜索并选择 " SendGrid"。Search for and select SendGrid.

    Azure 门户 Marketplace 屏幕的屏幕截图,其中显示搜索框中的 "SendGr",并在搜索结果中选择 SendGrid。

  4. 完成注册表单,并选择“创建”。Complete the signup form and select Create.

    "创建新的 SendGrid 帐户" 对话框的屏幕截图,其中填充了 "名称"、"密码"、"订阅" 和 "资源组" 字段。

  5. 输入“名称”标识 Azure 设置中的 SendGrid 服务。Enter a Name to identify your SendGrid service in your Azure settings. 名称的长度必须介于 1 到 100 个字符之间,并只能包含字母字符、短划线、句点和下划线。Names must be between 1 and 100 characters in length and contain only alphanumeric characters, dashes, dots, and underscores. 名称在订阅的 Azure 应用商店项目的列表中必须是唯一的。The name must be unique in your list of subscribed Azure Store Items.

  6. 输入并确认“密码”。Enter and confirm your Password.

  7. 选择“订阅”。Choose your Subscription.

  8. 新建“资源组”或使用现有资源组。Create a new Resource group or use an existing one.

  9. 在“定价层”对话框中,选择要注册的 SendGrid 计划。In the Pricing tier section select the SendGrid plan you want to sign up for.

    "创建新的 SendGrid 帐户" 对话框的屏幕截图,其中打开了 "选择定价层" 部分

  10. 如果有“促销代码”,请输入。Enter a Promotion Code if you have one.

  11. 输入 联系信息Enter your Contact Information.

  12. 查看并接受 法律条款Review and accept the Legal terms.

  13. 确认你的购买后,你会看到 " 部署成功 " 弹出窗口,你会看到你的帐户已列出。After confirming your purchase you will see a Deployment Succeeded pop-up and you will see your account listed.

    显示列出的新帐户 ContosoSendGrid 的 "SendGrid 帐户" 页的屏幕截图。

    完成购买并单击“管理”按钮启动电子邮件验证过程后,用户将收到一封来自 SendGrid 的电子邮件,要求验证其帐户。After you have completed your purchase and clicked the Manage button to initiate the email verification process, you will receive an email from SendGrid asking you to verify your account. 如果你没有收到此电子邮件,或验证你的帐户时遇到问题,请参阅我们的常见问题解答。If you do not receive this email, or have problems verifying your account, please see our FAQ.

    突出显示 "管理" 按钮的 "ContosoSendGrid 帐户" 页的屏幕截图。

    验证帐户之前,用户每天最多只能发送 100 封电子邮件。You can only send up to 100 emails/day until you have verified your account.

    若要修改订阅计划或查看 SendGrid 联系人设置,请单击 SendGrid 服务的名称以打开 SendGrid Marketplace 仪表板。To modify your subscription plan or see the SendGrid contact settings, click the name of your SendGrid service to open the SendGrid Marketplace dashboard.

    显示 ContosoSendGrid 帐户的 "设置" 页的屏幕截图,可选择 "ContosoSendGrid 帐户" 页中的 "所有设置" 打开。

    若要使用 SendGrid 发送电子邮件,必须提供 API 密钥。To send an email using SendGrid, you must supply your API Key.

查找 SendGrid API 密钥To find your SendGrid API Key

  1. 单击“管理”。Click Manage.

    突出显示 "管理" 按钮的 "ContosoSendGrid 帐户" 页的屏幕截图。

  2. 在 SendGrid 仪表板中,选择“设置”,并选择左侧菜单中的“API 密钥”。In your SendGrid dashboard, select Settings and then API Keys in the menu on the left.

    SendGrid 仪表板的屏幕截图,其中选择了 "设置" 下拉列表并选择了 "API 密钥"。

  3. 单击“创建 API 密钥”。Click the Create API Key.

    选择了 "创建 API 密钥" 按钮的 API 密钥屏幕屏幕截图。

  4. 至少提供“此密钥名称”和对“邮件发送”的完全访问权限,并选择“保存”。At a minimum, provide the Name of this key and provide full access to Mail Send and select Save.

    "添加新的常规 API 密钥" 屏幕屏幕截图,其中 "邮件发送" 设置为 "完全访问",计划发送设置为 "无访问",突出显示 "保存" 按钮。

  5. 此时会显示一次 API。Your API will be displayed at this point one time. 请务必安全存储该 API。Please be sure to store it safely.

查找 SendGrid 凭据To find your SendGrid credentials

  1. 单击密钥图标,查找“用户名”。Click the key icon to find your Username.

    突出显示了钥匙图标的 "ContosoSendGrid 帐户" 页的屏幕截图。

  2. 密码是用户设置时选择的密码。The password is the one you chose at setup. 若需进行任何更改,可选择“更改密码”或“重置密码”。You can select Change password or Reset password to make any changes.

若要管理电子邮件传递设置,请单击“管理”按钮。To manage your email deliverability settings, click the Manage button. 此操作将重定向到 SendGrid 仪表板。This will redirect to your SendGrid dashboard.

突出显示 "管理" 按钮的 "ContosoSendGrid 帐户" 页的屏幕截图。

有关通过 SendGrid 发送电子邮件的详细信息,请访问电子邮件 API 概述For more information on sending email through SendGrid, visit the Email API Overview.

引用 SendGrid Node.js 模块Reference the SendGrid Node.js Module

可使用以下命令通过 Node 包管理器 (npm) 安装用于 Node.js 的 SendGrid 模块:The SendGrid module for Node.js can be installed through the node package manager (npm) by using the following command:

npm install sendgrid

安装之后,可使用以下代码要求应用程序中的模块:After installation, you can require the module in your application by using the following code:

var sendgrid = require('sendgrid')(sendgrid_username, sendgrid_password);

SendGrid 模块可导出 SendGridEmail 函数。The SendGrid module exports the SendGrid and Email functions. SendGrid 负责通过 Web API 发送电子邮件,而 Email 负责封装电子邮件。SendGrid is responsible for sending email through Web API, while Email encapsulates an email message.

如何:创建电子邮件How to: Create an Email

要使用 SendGrid 模块创建电子邮件,需要先使用 Email 函数创建电子邮件,然后使用 SendGrid 函数发送该邮件。Creating an email message using the SendGrid module involves first creating an email message using the Email function, and then sending it using the SendGrid function. 以下是使用 Email 函数创建新邮件的示例:The following is an example of creating a new message using the Email function:

var email = new sendgrid.Email({
    to: 'john@contoso.com',
    from: 'anna@contoso.com',
    subject: 'test mail',
    text: 'This is a sample email message.'
});

通过设置 html 属性,可以为支持 HTML 邮件的客户端指定该邮件。You can also specify an HTML message for clients that support it by setting the html property. 例如:For example:

html: This is a sample <b>HTML<b> email message.

同时设置文本和 html 属性可以为无法支持 HTML 邮件的客户端提供文本内容的正常反馈。Setting both the text and html properties provides graceful fallback to text content for clients that cannot support HTML messages.

有关 Email 函数支持的所有属性的详细信息,请参阅 sendgrid-nodejsFor more information on all properties supported by the Email function, see sendgrid-nodejs.

如何:发送电子邮件How to: Send an Email

使用 Email 函数创建电子邮件后,可使用 SendGrid 提供的 Web API 发送该邮件。After creating an email message using the Email function, you can send it using the Web API provided by SendGrid.

Web APIWeb API

sendgrid.send(email, function(err, json){
    if(err) { return console.error(err); }
    console.log(json);
});

备注

上面的示例演示传入电子邮件对象和回调函数,还可通过直接指定电子邮件属性来直接调用 send 函数。While the above examples show passing in an email object and callback function, you can also directly invoke the send function by directly specifying email properties. 例如:For example:

sendgrid.send({
to: 'john@contoso.com',
from: 'anna@contoso.com',
subject: 'test mail',
text: 'This is a sample email message.'
});

如何:添加附件How to: Add an Attachment

可通过在 files 属性中指定文件名和路径来将附件添加到邮件中。Attachments can be added to a message by specifying the file name(s) and path(s) in the files property. 下面的示例演示如何发送附件:The following example demonstrates sending an attachment:

sendgrid.send({
    to: 'john@contoso.com',
    from: 'anna@contoso.com',
    subject: 'test mail',
    text: 'This is a sample email message.',
    files: [
        {
            filename:     '',           // required only if file.content is used.
            contentType:  '',           // optional
            cid:          '',           // optional, used to specify cid for inline content
            path:         '',           //
            url:          '',           // == One of these three options is required
            content:      ('' | Buffer) //
        }
    ],
});

备注

使用 files 属性时,必须可通过 fs.readFile 访问文件。When using the files property, the file must be accessible through fs.readFile. 如果要附加的文件托管在 Azure 存储中(如 Blob 容器中),必须先将该文件复制到本地存储或 Azure 驱动器,然后才能使用 files 属性将该文件作为附件发送。If the file you wish to attach is hosted in Azure Storage, such as in a Blob container, you must first copy the file to local storage or to an Azure drive before it can be sent as an attachment using the files property.

如何:使用筛选器启用页脚和跟踪How to: Use Filters to Enable Footers and Tracking

SendGrid 可通过使用筛选器来提供其他电子邮件功能。SendGrid provides additional email functionality through the use of filters. 可将这些设置添加到电子邮件以启用特定功能(例如启用单击跟踪、Google 分析、订阅跟踪等)。These are settings that can be added to an email message to enable specific functionality such as enabling click tracking, Google analytics, subscription tracking, and so on. 有关筛选器的完整列表,请参阅筛选器设置For a full list of filters, see Filter Settings.

可使用 filters 属性将筛选器应用于邮件。Filters can be applied to a message by using the filters property. 每个筛选器均由一个包含特定于筛选器的设置的哈希指定。Each filter is specified by a hash containing filter-specific settings. 以下示例演示了脚注和单击跟踪筛选器:The following examples demonstrate the footer and click tracking filters:

var email = new sendgrid.Email({
    to: 'john@contoso.com',
    from: 'anna@contoso.com',
    subject: 'test mail',
    text: 'This is a sample email message.'
});

email.setFilters({
    'footer': {
        'settings': {
            'enable': 1,
            'text/plain': 'This is a text footer.'
        }
    }
});

sendgrid.send(email);

单击跟踪Click Tracking

var email = new sendgrid.Email({
    to: 'john@contoso.com',
    from: 'anna@contoso.com',
    subject: 'test mail',
    text: 'This is a sample email message.'
});

email.setFilters({
    'clicktrack': {
        'settings': {
            'enable': 1
        }
    }
});

sendgrid.send(email);

如何:更新电子邮件属性How to: Update Email Properties

可使用 setProperty 替代一些电子邮件属性,或使用 addProperty 追加一些电子邮件属性 。Some email properties can be overwritten using setProperty or appended using addProperty. 例如,可使用以下命令添加更多收件人:For example, you can add additional recipients by using

email.addTo('jeff@contoso.com');

或使用以下命令设置筛选器:or set a filter by using

email.addFilter('footer', 'enable', 1);
email.addFilter('footer', 'text/html', '<strong>boo</strong>');

有关详细信息,请参阅 sendgrid-nodejsFor more information, see sendgrid-nodejs.

如何:使用其他 SendGrid 服务How to: Use Additional SendGrid Services

SendGrid 提供了基于 Web 的 API,可通过这些 API 从 Azure 应用程序中使用其他 SendGrid 功能。SendGrid offers web-based APIs that you can use to leverage additional SendGrid functionality from your Azure application. 有关完整详细信息,请参阅 SendGrid API 文档For full details, see the SendGrid API documentation.

后续步骤Next Steps

此时,已了解 SendGrid 电子邮件服务的基础知识,请访问以下链接以了解更多信息。Now that you've learned the basics of the SendGrid Email service, follow these links to learn more.