Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件

什么是 SendGrid 电子邮件服务?

SendGrid 是一项基于云的电子邮件服务,该服务提供了可靠的事务电子邮件传递、伸缩性、实时分析以及可用于简化自定义集成的灵活的 API。 常见 SendGrid 使用方案包括:

  • 自动向客户发送收据
  • 管理用于每月向客户发送电子传单和特惠产品/服务的通讯组列表
  • 收集诸如已阻止的电子邮件和客户响应性等项目的实时度量值
  • 生成用于帮助确定趋势的报告
  • 转发客户查询
  • 以电子邮件的形式从应用程序发送通知

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

创建 SendGrid 帐户

注册地址:sendgrid

免费客户每月可解锁 40k 封免费电子邮件。 通过每月的这 40k 封免费电子邮件,将可使用高级报告和分析以及所有 API(Web、SMTP、事件、分析等)。 有关 SendGrid 提供的其他服务的信息,请访问 SendGrid 解决方案页。

 

 

查找 SendGrid API 密钥

  1. 在 SendGrid 仪表板中,选择“设置”,并选择左侧菜单中的“API 密钥”。

    Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
    Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
  2. 单击“创建 API 密钥”下拉列表,并选择“常规 API 密钥”。

    Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
    Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
  3. 至少提供“此密钥名称”和对“邮件发送”的完全访问权限,并选择“保存”。

    Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
    Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
  4. 此时会显示一次 API。 请务必安全存储该 API。

 

PHP: 发送电子邮件

可以使用 SMTP 或由 SendGrid 提供的 Web API 发送电子邮件。

SMTP API 

若要使用 SendGrid SMTP API 发送电子邮件,请使用 Swift Mailer,这是用于从 PHP 应用程序中发送电子邮件的基于组件的库。 可以从 http://swiftmailer.org/download v5.3.0 中下载 Swift Mailer 库(使用编辑器安装 Swift Mailer)。 利用库发送电子邮件涉及创建 Swift_SmtpTransportSwift_Mailer 和 Swift_Message 类的实例,设置适当的属性以及调用 Swift_Mailer::send 方法。

$ composer require swiftmailer/swiftmailer
<?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 API

使用 PHP 的 curl 函数来通过 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 谓词是可互换的。

Python: 发送电子邮件

进入仪表盘,点击Setup Guide

Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件

把API key复制下来

Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件

官方python教程地址Github
按照官方教程,我们测试发送一封邮件!

YOUR_API_KEY 就是刚才的api key

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

安装Sendgrid

sudo apt-get python-pip
sudo pip install sendgrid

新建一个文件,比如test.py

sudo vi test.py

官方给出的演示如下

Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件

我们把它复制到test.py

import sendgrid
import os
from sendgrid.helpers.mail import *
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("test@example.com")
to_email = Email("test@example.com")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)

最后 python test.py 

发送成功! 

Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件
Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件

 

Shell Script / cUrl / Bash: 发送电子邮件

自己写的实例:

SENDGIRD_APIKEY='Your API Key'

notify()
{
    EMAIL_TO="info@ikeepstudying.com"
    FROM_EMAIL="no-reply@ikeepstudying.com"
    FROM_NAME="Dev Gideon"
    SUBJECT="[TESTING REPORT]"

    bodyHTML="
    <div style='font-family:sans-serif;color:#212529;background:#c4cdf4;border-radius:8px;padding:1px 20px 12px 20px'>
        <h4 style='font-size:1.25rem;font-size:20px;'>[TESTING REPORT - ${date}] </h4>
        <h5 style='font-size:18px;'> $1 <h5>
        <h5 style='font-size:18px;'> Errors: <h5>
        <ol style='line-height:1.75;font-size:16px;'>
            <li>
                $(cat ${ERROR_FILE} | sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ <\/li><li> /g')
            </li>
        </ol>
    </div>"

    maildata='{"personalizations": [{"to": [{"email": "'${EMAIL_TO}'"}]}],"from": {"email": "'${FROM_EMAIL}'",
        "name": "'${FROM_NAME}'"},"subject": "'${SUBJECT}'","content": [{"type": "text/html", "value": "'$(echo ${bodyHTML} | tr -d '\r\n')'"}]}'

    sudo curl --request POST \
      --url https://api.sendgrid.com/v3/mail/send \
      --header 'Authorization: Bearer '${SENDGIRD_APIKEY} \
      --header 'Content-Type: application/json' \
      --data "'$maildata'"
}

notify "this is a testing"

或者其他模板:

sendgrid.bash

#!/bin/bash

SENDGRID_API_KEY=""
EMAIL_TO=""
FROM_EMAIL=""
FROM_NAME=""
SUBJECT=""

bodyHTML="<p>Email body goes here</p>"

maildata='{"personalizations": [{"to": [{"email": "'${EMAIL_TO}'"}]}],"from": {"email": "'${FROM_EMAIL}'", 
	"name": "'${FROM_NAME}'"},"subject": "'${SUBJECT}'","content": [{"type": "text/html", "value": "'${bodyHTML}'"}]}'

curl --request POST \
  --url https://api.sendgrid.com/v3/mail/send \
  --header 'Authorization: Bearer '$SENDGRID_API_KEY \
  --header 'Content-Type: application/json' \
  --data "'$maildata'"

curl

curl --request POST \
  --url https://api.sendgrid.com/v3/mail/send \
  --header "Authorization: Bearer $SENDGRID_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{"personalizations": [{"to": [{"email": "test@example.com"}]}],"from": {"email": "test@example.com"},"subject": "Sending with SendGrid is Fun","content": [{"type": "text/plain", "value": "and easy to do anywhere, even with cURL"}]}'

Node.js

// using SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: 'test@example.com',
  from: 'test@example.com',
  subject: 'Sending with SendGrid is Fun',
  text: 'and easy to do anywhere, even with Node.js',
  html: 'and easy to do anywhere, even with Node.js',
};
sgMail.send(msg);

Ruby

# using SendGrid's Ruby Library
# https://github.com/sendgrid/sendgrid-ruby
require 'sendgrid-ruby'
include SendGrid

from = Email.new(email: 'test@example.com')
to = Email.new(email: 'test@example.com')
subject = 'Sending with SendGrid is Fun'
content = Content.new(type: 'text/plain', value: 'and easy to do anywhere, even with Ruby')
mail = Mail.new(from, subject, to, content)

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.mail._('send').post(request_body: mail.to_json)
puts response.status_code
puts response.body
puts response.headers

Python

# using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python
import sendgrid
import os
from sendgrid.helpers.mail import *

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("test@example.com")
to_email = Email("test@example.com")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)

Java

// using SendGrid's Java Library
// https://github.com/sendgrid/sendgrid-java
import com.sendgrid.*;
import java.io.IOException;

public class Example {
  public static void main(String[] args) throws IOException {
    Email from = new Email("test@example.com");
    String subject = "Sending with SendGrid is Fun";
    Email to = new Email("test@example.com");
    Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
    Mail mail = new Mail(from, subject, to, content);

    SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
    Request request = new Request();
    try {
      request.setMethod(Method.POST);
      request.setEndpoint("mail/send");
      request.setBody(mail.build());
      Response response = sg.api(request);
      System.out.println(response.getStatusCode());
      System.out.println(response.getBody());
      System.out.println(response.getHeaders());
    } catch (IOException ex) {
      throw ex;
    }
  }
}

 

如何:添加附件

SMTP API

使用 SMTP API 发送附件涉及在用于通过 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 reciever 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);
 }

额外的代码行如下所示:

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

该代码行对 Swift_Message 对象调用 attach 方法并对 Swift_Attachment 类使用静态方法 fromPath 以获取文件并将其附加到邮件。

Web API

使用 Web API 发送附件与使用 Web API 发送电子邮件非常相似。 但请注意,在以下示例中,参数数组必须包含该元素:

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

示例:

<?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);

 

后续步骤

此时,已了解 SendGrid 电子邮件服务的基础知识,请访问以下链接以了解更多信息。

有关详细信息,另请参阅 PHP 开发人员中心

 

本文:Linux Shell:使用 SendGrid Email API 发送邮件, SendGrid App for google cloud platform, php, phython, shell script 发送邮件

Loading

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.