使用 SendGrid 傳送電子郵件


本教學課程說明如何使用 SendGrid,從在 Compute Engine 虛擬機器 (VM) 執行個體上執行的應用程式傳送電子郵件。

目標

  • 在 Compute Engine 執行個體上搭配 Postfix 使用 SendGrid。
  • 在 Compute Engine 執行個體上執行的 Java 程式碼中使用 SendGrid。
  • 在 Compute Engine 執行個體上執行的 Node.js 程式碼中使用 SendGrid。
  • 在 Compute Engine 執行個體上搭配 Microsoft Exchange 邊緣傳輸伺服器使用 SendGrid。

如要進一步瞭解 SendGrid 的設定,請參閱 SendGrid 開發人員說明文件

費用

In this document, you use the following billable components of Google Cloud:

  • Compute Engine

To generate a cost estimate based on your projected usage, use the pricing calculator. New Google Cloud users might be eligible for a free trial.

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Make sure that billing is enabled for your Google Cloud project.

  6. In the Google Cloud console, go to the Create an instance page.

    Go to Create an instance

  7. Set Name to sendgrid-tutorial.
  8. In the Boot disk section, click Change to begin configuring your boot disk.
  9. On the Public images tab, choose a Debian or CentOS image version.
  10. Click Select.
  11. To create the VM, click Create.
  12. 使用 Google Cloud Marketplace 註冊 SendGrid 電子郵件服務。請記下您的 SendGrid SMTP 帳戶憑證,包括使用者名稱、密碼和主機名稱。您的 SMTP 使用者名稱和密碼,即是註冊服務時所用的使用者名稱和密碼。SendGrid 主機名稱為 smtp.sendgrid.net
  13. 建立 API 金鑰:
    1. 登入 SendGrid,並前往「Settings」>「API Keys」
    2. 建立 API 金鑰。
    3. 選取金鑰的權限。至少必須具備「Mail send」權限,才能傳送電子郵件。
    4. 按一下 [Save] 建立金鑰。
    5. SendGrid 會產生一個新金鑰。這是唯一一份金鑰,因此請務必複製並儲存金鑰,以供日後使用。

使用 Postfix 從執行個體傳送郵件

請按照下列步驟連線至 sendgrid-tutorial 執行個體,再以 Postfix 執行 SendGrid。

使用 SSH 連線至 sendgrid-tutorial 執行個體

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances

  2. In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.

透過 Postfix 將 SendGrid 設定為 SMTP 轉發服務

在 SSH 終端機中執行下列指令,藉以透過 Postfix 將 SendGrid 做為 SMTP 轉發使用。

  1. 成為超級使用者:

    sudo su -
    
  2. 設定安全的 umask:

    umask 077
    
  3. 安裝 Postfix Mail Transport Agent (Postfix 郵件傳輸代理程式):

    Debian

    apt update && apt -y install postfix libsasl2-modules

    CentOS

    yum install postfix cyrus-sasl-plain cyrus-sasl-md5 -y

    如果出現系統提示,請選取 [Local Only] (僅限本機) 設定並接受預設的網域名稱。

  4. 修改 Postfix 設定選項。打開 /etc/postfix/main.cf 進行編輯。舉例來說,如要使用 nano 文字編輯器,請輸入下列指令:

    nano /etc/postfix/main.cf
    
  5. 更新檔案:

    1. 加註下列幾行:

      # default_transport = error
      # relay_transport = error
      
    2. 在檔案末尾加入下列幾行:

      relayhost = [smtp.sendgrid.net]:2525
      smtp_tls_security_level = encrypt
      smtp_sasl_auth_enable = yes
      smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
      header_size_limit = 4096000
      smtp_sasl_security_options = noanonymous
      

      以上幾行會針對這些要求強制執行安全資料傳輸層 (SSL)/傳輸層安全標準 (TLS) 支援,並設定 SMTP 驗證。 簡單存取及安全性階層 (SASL) 模組可處理 Postfix 設定中的驗證作業。

  6. 儲存並關閉檔案。

  7. 使用您在「事前準備」一節中產生的 API 金鑰產生 SASL 密碼對應。將 your-api-key 替換為您產生的 API 金鑰。

    echo [smtp.sendgrid.net]:2525 apikey:your-api-key >> /etc/postfix/sasl_passwd
  8. 使用 postmap 公用程式產生 .db 檔案。

    postmap /etc/postfix/sasl_passwd
    
  9. 確認您擁有 .db 檔案:

    ls -l /etc/postfix/sasl_passwd*
    
    -rw------- 1 root root    ...  /etc/postfix/sasl_passwd
    -rw------- 1 root root    ...  /etc/postfix/sasl_passwd.db
    
  10. 移除內含憑證的檔案,因為現在已不需要該檔案:

    rm /etc/postfix/sasl_passwd
    
  11. .db 檔案上設定權限,並確認另一個檔案已移除:

    chmod 600 /etc/postfix/sasl_passwd.db
    ls -la /etc/postfix/sasl_passwd*
    
    -rw------- 1 root root    ...  /etc/postfix/sasl_passwd.db
    
  12. 重新載入設定,以載入修改後的參數:

    Debian

    /etc/init.d/postfix restart
    

    CentOS

    postfix reload
    

  13. 安裝 mailutilsmailx 套件:

    Debian

    apt -y install mailutils

    CentOS

    yum install mailx -y
    

  14. 傳送測試電子郵件:

    echo 'message' | mail -s subject email@example.com

    更改下列內容:

    • message:電子郵件內文。
    • subject:電子郵件主旨。
    • email@example.com:您要傳送訊息的電子郵件地址。

    請在系統記錄中尋找內含 status 的狀態行,以及成功的伺服器回應碼 (250)

    Debian

    tail -n 5 /var/log/syslog
    

    CentOS

    tail -n 5 /var/log/maillog
    

在執行個體上以 Java 傳送郵件

使用 SSH 連線至 sendgrid-tutorial 執行個體

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances

  2. In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.

建構並傳送電子郵件

以下操作說明會使用 SendGrid Java 用戶端程式庫,透過 SendGrid 來建構和傳送電子郵件。您可在 GitHub 上檢視完整範例。

在 SSH 終端機中:

  1. 成為超級使用者並設定安全的 umask:

    sudo su -
    umask 077
    
  2. 安裝 Java 和 Maven:

    apt -y update && apt -y install git-core openjdk-11-jdk maven
    
  3. 複製 GitHub 存放區:

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
    
  4. 前往範例的主要原始碼:

    cd /root/java-docs-samples/compute/sendgrid/src/main/java/com/example/compute/sendgrid
    
  5. 開啟 SendEmailServelet.java 進行編輯。

    • your-sendgrid-api-key 替換為您 SendGrid 帳戶的 API 金鑰

    • your-sendgrid-from-email 替換為您要用來發送郵件的電子郵件地址。

    • destination-email 替換為您要傳送郵件到其中的目標電子郵件地址。

  6. 前往程式碼範例的根目錄:

    cd /root/java-docs-samples/compute/sendgrid
    
  7. 建立 Java 類別套件:

    mvn clean package
    
  8. 前往新的 target目錄:

    cd target
    
  9. 設定權限,允許您執行 jar 檔案:

    chmod +x compute-sendgrid-1.0-SNAPSHOT-jar-with-dependencies.jar
    
  10. 執行替代的 Java 版本選取器:

    update-alternatives --config java
    

    選取 java-11-openjdk-amd64 選項。

  11. 執行 Java 檔案:

    java -jar compute-sendgrid-1.0-SNAPSHOT-jar-with-dependencies.jar
    

在執行個體上透過 Node.js 傳送郵件

如要執行此範例,VM 執行個體上必須已安裝 Node.js 7.6 以上版本。

使用 SSH 連線至 sendgrid-tutorial 執行個體

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances

  2. In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.

建構並傳送電子郵件

在 SSH 終端機中:

  1. 成為超級使用者並設定安全的 umask:

    sudo su -
    umask 077
    
  2. 更新套件存放區:

    Debian

    apt update
    

    CentOS

    yum update -y
    

  3. 安裝 Node.js 依附元件:

    Debian

    apt -y install git-core curl build-essential openssl libssl-dev
    

    CentOS

    yum install git-core curl openssl openssl-devel -y
    yum groupinstall "Development Tools" -y
    

  4. 安裝 Node.js。根據預設,安裝程序也會安裝 npm

    Debian

    curl -sL https://deb.nodesource.com/setup_14.x | sudo bash -
    sudo apt -y install nodejs
    

    CentOS

    curl --silent --location https://rpm.nodesource.com/setup_14.x | bash -
    

    然後再安裝 Node.js:

    yum -y install nodejs
    

  5. 安裝 SendGrid Node.js 用戶端:

    npm install sendgrid
    
  6. 複製範例存放區:

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
    
  7. 前往含有 SendGrid 範例的目錄:

    cd nodejs-docs-samples/compute
    
  8. 複製 sendgrid.js 檔案:

    cp sendgrid.js sendmail.js
    
  9. 開啟 sendmail.js 進行編輯。

    • your-sendgrid-api-key 替換為您 SendGrid 帳戶的 API 金鑰

    • from-email@example.com 替換為您要用來發送郵件的電子郵件地址。

    • to-email@example.com 替換為您要傳送郵件到其中的目標電子郵件地址。

    // This sample is based off of:
    // https://github.com/sendgrid/sendgrid-nodejs/tree/master/packages/mail
    const sendgrid = require('@sendgrid/mail');
    sendgrid.setApiKey(process.env.SENDGRID_API_KEY || '<your-sendgrid-api-key>');
    
    async function sendgridExample() {
      await sendgrid.send({
        to: 'to_email@example.com',
        from: 'from_email@example.com',
        subject: 'Sendgrid test email from Node.js on Google Cloud Platform',
        text: 'Well hello! This is a Sendgrid test email from Node.js on Google Cloud Platform.',
      });
    }
    sendgridExample();

  10. 執行程式以透過 SendGrid 傳送電子郵件:

    node sendmail.js
    

透過 Exchange 邊緣傳輸伺服器傳送郵件

您可以設定外寄傳送連接器,讓 Microsoft Exchange 透過 SendGrid 傳送外寄電子郵件。詳情請參閱「在 Compute Engine 上部署 Microsoft Exchange Server 2016」。

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

刪除專案

如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。

如要刪除專案:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

刪除 Compute Engine 執行個體

如要刪除 Compute Engine 執行個體:

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances

  2. Select the checkbox for your sendgrid-tutorial instance.
  3. To delete the instance, click More actions, click Delete, and then follow the instructions.

後續步驟

探索 Google Cloud 的參考架構、圖表和最佳做法。歡迎瀏覽我們的雲端架構中心