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

如何通过 PHP 使用 SendGrid 电子邮件服务How to Use the SendGrid Email Service from PHP

本指南演示了如何在 Azure 上使用 SendGrid 电子邮件服务执行常见编程任务。This guide demonstrates how to perform common programming tasks with the SendGrid email service on Azure. 通过 PHP 编写示例。The samples are written in PHP. 所涉及的任务包括 创建电子邮件发送电子邮件 以及 添加附件The scenarios covered include constructing email, sending email, and adding attachments. 有关 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 门户“市场”屏幕的屏幕截图显示了搜索框中的“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.

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

    完成购买并单击“管理”按钮启动电子邮件验证过程后,用户将收到一封来自 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 帐户页面的“所有设置”打开“设置”页面。

    若要使用 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.

从 PHP 应用程序中使用 SendGridUsing SendGrid from your PHP Application

在 Azure PHP 应用程序中使用 SendGrid 时不需要特殊配置或编码。Using SendGrid in an Azure PHP application requires no special configuration or coding. 由于 SendGrid 是一项服务,可使用从本地应用程序访问该服务的方式从云应用程序中访问该服务。Because SendGrid is a service, it can be accessed in exactly the same way from a cloud application as it can from an on-premises application.

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

可以使用 SMTP 或由 SendGrid 提供的 Web API 发送电子邮件。You can send email using either SMTP or the Web API provided by SendGrid.

SMTP APISMTP API

若要使用 SendGrid SMTP API 发送电子邮件,请使用 Swift Mailer,这是用于从 PHP 应用程序中发送电子邮件的基于组件的库。To send email using the SendGrid SMTP API, use Swift Mailer, a component-based library for sending emails from PHP applications. 可以下载 Swift Mailer 库 v5.3.0(使用 编辑器 安装 Swift Mailer)。You can download the Swift Mailer library v5.3.0 (use Composer to install Swift Mailer). 利用库发送电子邮件涉及创建 Swift\_SmtpTransportSwift\_MailerSwift\_Message 类的实例,设置适当的属性以及调用 Swift\_Mailer::send 方法。Sending email with the library involves creating instances of the Swift\_SmtpTransport, Swift\_Mailer, and Swift\_Message classes, setting the appropriate properties, and calling the Swift\_Mailer::send method.

<?php
 include_once "vendor/autoload.php";
 /*
  * Create the body of the message (a plain-text and an HTML version).
  * $text is your plain-text email
  * $html is your html version of the email
  * If the receiver is able to view html emails then only the html
  * email will be displayed
  */
 $text = "Hi!\nHow are you?\n";
 $html = "<html>
       <head></head>
       <body>
           <p>Hi!<br>
               How are you?<br>
           </p>
       </body>
       </html>";
 // This is your From email address
 $from = array('someone@example.com' => 'Name To Appear');
 // Email recipients
 $to = array(
       'john@contoso.com'=>'Destination 1 Name',
       'anna@contoso.com'=>'Destination 2 Name'
 );
 // Email subject
 $subject = 'Example PHP Email';

 // Login credentials
 $username = 'yoursendgridusername';
 $password = 'yourpassword';

 // Setup Swift mailer parameters
 $transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 587);
 $transport->setUsername($username);
 $transport->setPassword($password);
 $swift = Swift_Mailer::newInstance($transport);

 // Create a message (subject)
 $message = new Swift_Message($subject);

 // attach the body of the email
 $message->setFrom($from);
 $message->setBody($html, 'text/html');
 $message->setTo($to);
 $message->addPart($text, 'text/plain');

 // send message
 if ($recipients = $swift->send($message, $failures))
 {
     // This will let us know how many users received this message
     echo 'Message sent out to '.$recipients.' users';
 }
 // something went wrong =(
 else
 {
     echo "Something went wrong - ";
     print_r($failures);
 }

Web APIWeb API

使用 PHP 的 curl 函数来通过 SendGrid Web API 发送电子邮件。Use PHP's curl function to send email using the SendGrid Web API.

<?php

 $url = 'https://api.sendgrid.com/';
 $user = 'USERNAME';
 $pass = 'PASSWORD';

 $params = array(
      'api_user' => $user,
      'api_key' => $pass,
      'to' => 'john@contoso.com',
      'subject' => 'testing from curl',
      'html' => 'testing body',
      'text' => 'testing body',
      'from' => 'anna@contoso.com',
   );

 $request = $url.'api/mail.send.json';

 // Generate curl request
 $session = curl_init($request);

 // Tell curl to use HTTP POST
 curl_setopt ($session, CURLOPT_POST, true);

 // Tell curl that this is the body of the POST
 curl_setopt ($session, CURLOPT_POSTFIELDS, $params);

 // Tell curl not to return headers, but do return the response
 curl_setopt($session, CURLOPT_HEADER, false);
 curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

 // obtain response
 $response = curl_exec($session);
 curl_close($session);

 // print everything out
 print_r($response);

SendGrid 的 Web API 与 REST API 非常相似,尽管它不是真正的 RESTful API,这是因为在大多数调用中,GET 和 POST 谓词是可互换的。SendGrid's Web API is very similar to a REST API, though it is not truly a RESTful API since, in most calls, both GET and POST verbs can be used interchangeably.

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

SMTP APISMTP API

使用 SMTP API 发送附件涉及在用于通过 Swift Mailer 发送电子邮件的示例脚本中额外添加一行代码。Sending an attachment using the SMTP API involves one additional line of code to the example script for sending an email with Swift Mailer.

<?php
 include_once "vendor/autoload.php";
 /*
  * Create the body of the message (a plain-text and an HTML version).
  * $text is your plain-text email
  * $html is your html version of the email
  * If the receiver is able to view html emails then only the html
  * email will be displayed
  */
 $text = "Hi!\nHow are you?\n";
  $html = "<html>
      <head></head>
      <body>
         <p>Hi!<br>
            How are you?<br>
         </p>
      </body>
      </html>";

 // This is your From email address
 $from = array('someone@example.com' => 'Name To Appear');

 // Email recipients
 $to = array(
      'john@contoso.com'=>'Destination 1 Name',
      'anna@contoso.com'=>'Destination 2 Name'
 );
 // Email subject
 $subject = 'Example PHP Email';

 // Login credentials
 $username = 'yoursendgridusername';
 $password = 'yourpassword';

 // Setup Swift mailer parameters
 $transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 587);
 $transport->setUsername($username);
 $transport->setPassword($password);
 $swift = Swift_Mailer::newInstance($transport);

 // Create a message (subject)
 $message = new Swift_Message($subject);

 // attach the body of the email
 $message->setFrom($from);
 $message->setBody($html, 'text/html');
 $message->setTo($to);
 $message->addPart($text, 'text/plain');
 $message->attach(Swift_Attachment::fromPath("path\to\file")->setFileName("file_name"));

 // send message
 if ($recipients = $swift->send($message, $failures))
 {
      // This will let us know how many users received this message
      echo 'Message sent out to '.$recipients.' users';
 }
 // something went wrong =(
 else
 {
      echo "Something went wrong - ";
      print_r($failures);
 }

额外的代码行如下所示:The additional line of code is as follows:

 $message->attach(Swift_Attachment::fromPath("path\to\file")->setFileName('file_name'));

该代码行对 Swift\_Message 对象调用 attach 方法并对 Swift\_Attachment 类使用静态方法 fromPath 以获取文件并将其附加到邮件。This line of code calls the attach method on the Swift\_Message object and uses static method fromPath on the Swift\_Attachment class to get and attach a file to a message.

Web APIWeb API

使用 Web API 发送附件与使用 Web API 发送电子邮件非常相似。Sending an attachment using the Web API is very similar to sending an email using the Web API. 但请注意,在以下示例中,参数数组必须包含该元素:However, note that in the example that follows, the parameter array must contain this element:

    'files['.$fileName.']' => '@'.$filePath.'/'.$fileName

示例Example

<?php

 $url = 'https://api.sendgrid.com/';
 $user = 'USERNAME';
 $pass = 'PASSWORD';

 $fileName = 'myfile';
 $filePath = dirname(__FILE__);

 $params = array(
     'api_user' => $user,
     'api_key' => $pass,
     'to' =>'john@contoso.com',
     'subject' => 'test of file sends',
     'html' => '<p> the HTML </p>',
     'text' => 'the plain text',
     'from' => 'anna@contoso.com',
     'files['.$fileName.']' => '@'.$filePath.'/'.$fileName
 );

 print_r($params);

 $request = $url.'api/mail.send.json';

 // Generate curl request
 $session = curl_init($request);

 // Tell curl to use HTTP POST
 curl_setopt ($session, CURLOPT_POST, true);

 // Tell curl that this is the body of the POST
 curl_setopt ($session, CURLOPT_POSTFIELDS, $params);

 // Tell curl not to return headers, but do return the response
 curl_setopt($session, CURLOPT_HEADER, false);
 curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

 // obtain response
 $response = curl_exec($session);
 curl_close($session);

 // print everything out
 print_r($response);

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

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.

可使用 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 example enables the footer filter and specifies a text message that will be appended to the bottom of the email message. 在此示例中,我们将使用 sendgrid-php 库For this example we will use sendgrid-php library.

使用编辑器安装库:Use Composer to install library:

php composer.phar require sendgrid/sendgrid 2.1.1

示例Example

<?php
 /*
  * This example is used for sendgrid-php V2.1.1 (https://github.com/sendgrid/sendgrid-php/tree/v2.1.1)
  */
 include "vendor/autoload.php";

 $email = new SendGrid\Email();
 // The list of addresses this message will be sent to
 // [This list is used for sending multiple emails using just ONE request to SendGrid]
 $toList = array('john@contoso.com', 'anna@contoso.com');

 // Specify the names of the recipients
 $nameList = array('Name 1', 'Name 2');

 // Used as an example of variable substitution
 $timeList = array('4 PM', '5 PM');

 // Set all of the above variables
 $email->setTos($toList);
 $email->addSubstitution('-name-', $nameList);
 $email->addSubstitution('-time-', $timeList);

 // Specify that this is an initial contact message
 $email->addCategory("initial");

 // You can optionally setup individual filters here, in this example, we have
 // enabled the footer filter
 $email->addFilter('footer', 'enable', 1);
 $email->addFilter('footer', "text/plain", "Thank you for your business");
 $email->addFilter('footer', "text/html", "Thank you for your business");

 // The subject of your email
 $subject = 'Example SendGrid Email';

 // Where is this message coming from. For example, this message can be from
 // support@yourcompany.com, info@yourcompany.com
 $from = 'someone@example.com';

 // If you do not specify a sender list above, you can specify the user here. If
 // a sender list IS specified above, this email address becomes irrelevant.
 $to = 'john@contoso.com';

 # Create the body of the message (a plain-text and an HTML version).
 # text is your plain-text email
 # html is your html version of the email
 # if the receiver is able to view html emails then only the html
 # email will be displayed

 /*
  * Note the variable substitution here =)
  */
 $text = "
 Hello -name-,
 Thank you for your interest in our products. We have set up an appointment to call you at -time- EST to discuss your needs in more detail.
 Regards,
 Fred";

 $html = "
 <html>
 <head></head>
 <body>
 <p>Hello -name-,<br>
 Thank you for your interest in our products. We have set up an appointment
 to call you at -time- EST to discuss your needs in more detail.

 Regards,

 Fred<br>
 </p>
 </body>
 </html>";

 // set subject
 $email->setSubject($subject);

 // attach the body of the email
 $email->setFrom($from);
 $email->setHtml($html);
 $email->addTo($to);
 $email->setText($text);

 // Your SendGrid account credentials
 $username = 'sendgridusername@yourdomain.com';
 $password = 'example';

 // Create SendGrid object
 $sendgrid = new SendGrid($username, $password);

 // send message
 $response = $sendgrid->send($email);

 print_r($response);

后续步骤Next Steps

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

有关详细信息,另请参阅 PHP 开发人员中心For more information, see also the PHP Developer Center.