使用 Mailjet 傳送電子郵件


Mailjet 是第三方全球電子郵件服務,Compute Engine 使用者每月可使用此服務的免費方案傳送 6,000 封電子郵件。不僅如此,Mailjet 還提供:

  • API、使用者介面和 SMTP 轉發服務,可用於寄送業務和行銷電子郵件。
  • 遵循歐盟資料隱私權法規。
  • 提供電子郵件和遞送功能,例如可自訂的優先順序設定與自動化的流量管理。
  • Go、PHP、Node.js、Java、Python 和 Ruby 的 API 資源程式庫,可用於管理子帳戶、驗證、聯絡人、廣告活動、自訂酬載、統計資料、即時事件,以及透過 Event API 進行剖析。
  • 整合式 MJML 架構,可用於建立回應式 HTML 電子郵件範本。
  • 提供 4 種語言以上的全球支援服務,24 小時全年無休。
  • 能從 gmail.com 以外的網域傳送電子郵件。

本文件說明如何利用下列方法設定 VM 執行個體以透過 Mailjet 傳送郵件:

  • 使用以下項目透過 SMTP 轉發服務:
  • 使用 Java 直接透過 Mailjet API

如需其他電子郵件解決方案的完整說明文件,包括常見的 SMTP 伺服器、資料庫和架構的整合例子,請參閱 Mailjet 的說明文件

事前準備

  1. 透過 Mailjet 的 Google 合作夥伴頁面* 建立新的 Mailjet 帳戶。註冊時,請提供您要用來傳送電子郵件訊息的網域與電子郵件地址。

  2. 取得 Mailjet SMTP 帳戶憑證

  3. 確定您要用來傳送電子郵件的電子郵件地址已驗證

  4. 設定防火牆規則來允許通訊埠 2525 的 TCP 流量。

* 請注意,若申請付費帳戶,Google 會收到報酬。

將 Mailjet 設為 SMTP 轉發服務

將 Mailjet 設為郵件轉發服務,即可將電子郵件轉寄到 Mailjet,以便遠端遞送。

使用 Postfix

  1. 使用 SSH 連線至 VM,並將 instance-name 替換為您要傳送電子郵件訊息的執行個體名稱:

    gcloud compute ssh instance-name
  2. 在 VM 上安裝 Postfix Mail Transport Agent (Postfix 郵件傳輸代理程式)。系統顯示提示時,請接受網域名稱的預設選擇,但選取 Local Only 設定。

    Debian

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

    CentOS

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

  3. 修改 Postfix 設定選項。Postfix 設定選項可於 main.cf 檔案中設定。請以文字編輯器開啟該檔案,可自由選擇要使用的文字編輯器。

    sudo vi /etc/postfix/main.cf
    
  4. 更新檔案:

    1. 加註下列幾行:

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

      relayhost = in-v3.mailjet.com:2525
      smtp_tls_security_level = encrypt
      smtp_sasl_auth_enable = yes
      smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
      smtp_sasl_security_options = noanonymous
      

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

    3. 儲存變更並關閉檔案。

  5. 透過您選擇的文字編輯器建立 SASL 密碼對應:

    sudo vi /etc/postfix/sasl_passwd
    
  6. sasl_passwd 檔案中,加入下列幾行以提供 Mailjet 的憑據:

    in-v3.mailjet.com:2525 YOUR_API_KEY:YOUR_SECRET_KEY
    
  7. 使用 postmap 公用程式產生 .db 檔案。

    sudo postmap /etc/postfix/sasl_passwd
    sudo ls -l /etc/postfix/sasl_passwd*
    

    您應該會收到下列回應內容:

    -rw------- 1 root root    68 Jun  1 10:50 /etc/postfix/sasl_passwd
    -rw------- 1 root root 12288 Jun  1 10:51 /etc/postfix/sasl_passwd.db
    
  8. 接著,移除內有憑證的檔案,因為現在已不需要該檔案:

    sudo rm /etc/postfix/sasl_passwd
    
  9. 設定 .db 檔案的權限:

    sudo chmod 600 /etc/postfix/sasl_passwd.db
    sudo ls -la /etc/postfix/sasl_passwd.db
    
  10. 最後,重新載入設定,以載入修改後的參數:

    Debian

    sudo /etc/init.d/postfix restart
    

    CentOS

    sudo postfix reload
    

  11. 測試您的設定。安裝 mailxmailutils 套件並測試您的設定。

    Debian

    sudo apt -y install mailutils
    

    CentOS

    sudo yum install mailx -y
    

    傳送測試訊息:

    echo 'Test passed.' | mail -s 'Test-Email' -aFrom:from-email destination-email

    更改下列內容:

    • from-email:已驗證的電子郵件地址。
    • destination-email:要傳送電子郵件訊息的地址。

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

    Debian

    sudo tail -n 5 /var/log/syslog
    

    CentOS

    sudo tail -n 5 /var/log/maillog
    

如您在設定 Postfix 搭配 Mailjet 時發生問題,請參閱 Mailjet Postfix 設定操作說明

使用 Nodemailer

以下操作說明描述如何在 Debian Wheezy 上使用 Mailjet 搭配 Node.js。

Debian
  1. 使用 SSH 連線至您的執行個體:
    gcloud compute ssh instance-name
  2. 更新套件存放區:
    user@test-wheezy:~# sudo apt update
  3. 安裝 Node.js 依附元件:
    user@test-wheezy:~# sudo apt -y install git-core curl build-essential openssl libssl-dev
  4. 從 github 複製 Node.js 存放區:
    user@test-wheezy:~# git clone https://github.com/nodejs/node
  5. 將目錄變更為 Node.js 來源樹狀結構:
    user@test-wheezy:~# cd node
  6. 為此 OS 與虛擬機器設定節點軟體:
    user@test-wheezy:~# ./configure
  7. 建構 Node.js、npm 及相關物件:
    user@test-wheezy:~# sudo make

    這項作業可能需要幾分鐘才能完成。

  8. 在預設位置安裝 Node.js、npm 及其他軟體:
    user@test-wheezy:~# sudo make install
  9. 安裝郵件程式套件:
    user@test-wheezy:~# npm install nodemailer nodemailer-smtp-transport
  10. node 目錄中,建立名為 sendmail.js 的新檔案,其中含有下列 JavaScript:
    const mailer = require('nodemailer');
    const smtp = require('nodemailer-smtp-transport');
    
    async function mailjet() {
      const transport = mailer.createTransport(
        smtp({
          host: 'in.mailjet.com',
          port: 2525,
          auth: {
            user: process.env.MAILJET_API_KEY || '<your-mailjet-api-key',
            pass: process.env.MAILJET_API_SECRET || '<your-mailjet-api-secret>',
          },
        })
      );
    
      const json = await transport.sendMail({
        from: 'ANOTHER_EMAIL@ANOTHER_EXAMPLE.COM', // From address
        to: 'EMAIL@EXAMPLE.COM', // To address
        subject: 'test email from Node.js on Google Cloud Platform', // Subject
        text: 'Hello!\n\nThis a test email from Node.js.', // Content
      });
      console.log(json);
    }
    mailjet();
  11. 執行程式以透過 Mailjet 傳送電子郵件訊息:
    user@test-wheezy:~# node sendmail.js
CentOS
  1. 使用 SSH 連線至您的執行個體:
    gcloud compute ssh instance-name
  2. 更新套件存放區:
    user@test-centos:~# sudo yum update -y
  3. 安裝 Node.js 依附元件:
    user@test-centos:~# sudo yum install git-core curl openssl openssl-dev -y
    ...
    user@test-centos:~# sudo yum groupinstall "Development Tools" -y
    ...
  4. 從 github 複製 Node.js 存放區:
    user@test-centos:~# git clone https://github.com/nodejs/node
  5. 將目錄變更為 Node.js 來源樹狀結構:
    user@test-centos:~# cd node
  6. 為此 OS 與虛擬機器設定節點軟體:
    user@test-centos:~# ./configure
  7. 建構 Node.js、npm 及相關物件:
    user@test-centos:~# sudo make

    這項作業可能需要幾分鐘才能完成。

  8. 在預設位置安裝 Node.js、npm 及其他軟體:
    user@test-centos:~# sudo make install
  9. 安裝郵件程式套件:
    user@test-centos:~# npm install npm install nodemailer nodemailer-smtp-transport
  10. node 目錄中,建立名為 sendmail.js 的新檔案,其中含有下列 JavaScript:
    const mailer = require('nodemailer');
    const smtp = require('nodemailer-smtp-transport');
    
    async function mailjet() {
      const transport = mailer.createTransport(
        smtp({
          host: 'in.mailjet.com',
          port: 2525,
          auth: {
            user: process.env.MAILJET_API_KEY || '<your-mailjet-api-key',
            pass: process.env.MAILJET_API_SECRET || '<your-mailjet-api-secret>',
          },
        })
      );
    
      const json = await transport.sendMail({
        from: 'ANOTHER_EMAIL@ANOTHER_EXAMPLE.COM', // From address
        to: 'EMAIL@EXAMPLE.COM', // To address
        subject: 'test email from Node.js on Google Cloud Platform', // Subject
        text: 'Hello!\n\nThis a test email from Node.js.', // Content
      });
      console.log(json);
    }
    mailjet();
  11. 執行程式以透過 Mailjet 傳送電子郵件訊息:
    user@test-centos:~# node sendmail.js

使用 Java 透過 Mailjet API 傳送郵件

如需更多使用 Mailjet API 的例子,請參閱 Mailjet 官方說明文件

Debian
  1. 使用 SSH 連線至您的執行個體:
    gcloud compute ssh instance-name
  2. 更新您的套件存放區並安裝所需套件:
    user@test-instance:~# sudo apt update && sudo apt install git-core openjdk-8-jdk maven
  3. 從 GitHub 複製 Java 存放區:
    user@test-instance:~# git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
  4. 前往範例的主要原始碼位置,即:
    /root/java-docs-samples/compute/mailjet/src/main/java/com/example/compute/mailjet
  5. 設定 Mailjet 設定。請參閱 Mailjet 驗證說明文件,瞭解如何替換下列變數:

    • your-mailjet-api-key:Mailjet 帳戶的 API 金鑰。
    • your-mailjet-secret-key:Mailjet 帳戶對應的密鑰。

    public class MailjetSender {
    
      public static void main(String[] args) throws MailjetException {
        final String mailjetApiKey = "YOUR-MAILJET-API-KEY";
        final String mailjetSecretKey = "YOUR-MAILJET-SECRET-KEY";
        ClientOptions options =
            ClientOptions.builder().apiKey(mailjetApiKey).apiSecretKey(mailjetSecretKey).build();
        MailjetClient client = new MailjetClient(options);
    
        MailjetSender sender = new MailjetSender();
        sender.sendMailjet(args[0], args[1], client);
      }
    
      public MailjetResponse sendMailjet(String recipient, String sender, MailjetClient client)
          throws MailjetException {
        MailjetRequest email =
            new MailjetRequest(Emailv31.resource)
                .property(
                    Emailv31.MESSAGES,
                    new JSONArray()
                        .put(
                            new JSONObject()
                                .put(
                                    Emailv31.Message.FROM,
                                    new JSONObject().put("Email", sender).put("Name", "pandora"))
                                .put(
                                    Emailv31.Message.TO,
                                    new JSONArray().put(new JSONObject().put("Email", recipient)))
                                .put(Emailv31.Message.SUBJECT, "Your email flight plan!")
                                .put(
                                    Emailv31.Message.TEXTPART,
                                    "Dear passenger, welcome to Mailjet!" 
                                    + "May the delivery force be with you!")
                                .put(
                                    Emailv31.Message.HTMLPART,
                                    "<h3>Dear passenger, welcome to Mailjet!</h3>"
                                    + "<br />May the delivery force be with you!")));
    
        try {
          // trigger the API call
          MailjetResponse response = client.post(email);
          // Read the response data and status
          System.out.println(response.getStatus());
          System.out.println(response.getData());
          return response;
        } catch (MailjetException e) {
          System.out.println("Mailjet Exception: " + e);
          return null;
        }
      }
    }
  6. mailjet 目錄,使用 Maven 將類別封裝為 JAR 檔案:
    user@test-instance:~# mvn clean package
  7. 確認您使用的是 OpenJDK 8:
    user@test-instance:~# sudo update-alternatives --config java
  8. 如要傳送電子郵件,請從目標目錄中執行 JAR 檔案,並以收件者與寄件者的電子郵件地址做為引數:
    user@test-instance:~# java -jar
            compute-mailjet-1.0-SNAPSHOT-jar-with-dependencies.jar
            recipient-email sender-email
CentOS
  1. 使用 SSH 連線至您的執行個體:
    gcloud compute ssh instance-name
  2. 更新您的套件存放區並安裝所需套件:
    user@test-centos:~# sudo yum update && sudo yum install git-core openjdk-8-jdk maven
  3. 從 GitHub 複製 Java 存放區:
    user@test-centos:~# git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
  4. 前往範例的主要原始碼位置,即:
    /root/java-docs-samples/compute/mailjet/src/main/java/com/example/compute/mailjet
  5. 設定 Mailjet 設定。如要瞭解如何取代下列變數,請參閱 Mailjet 的驗證說明文件:

    • your-mailjet-api-key:Mailjet 帳戶的 API 金鑰。
    • your-mailjet-secret-key:Mailjet 帳戶對應的密鑰。

    public class MailjetSender {
    
      public static void main(String[] args) throws MailjetException {
        final String mailjetApiKey = "YOUR-MAILJET-API-KEY";
        final String mailjetSecretKey = "YOUR-MAILJET-SECRET-KEY";
        ClientOptions options =
            ClientOptions.builder().apiKey(mailjetApiKey).apiSecretKey(mailjetSecretKey).build();
        MailjetClient client = new MailjetClient(options);
    
        MailjetSender sender = new MailjetSender();
        sender.sendMailjet(args[0], args[1], client);
      }
    
      public MailjetResponse sendMailjet(String recipient, String sender, MailjetClient client)
          throws MailjetException {
        MailjetRequest email =
            new MailjetRequest(Emailv31.resource)
                .property(
                    Emailv31.MESSAGES,
                    new JSONArray()
                        .put(
                            new JSONObject()
                                .put(
                                    Emailv31.Message.FROM,
                                    new JSONObject().put("Email", sender).put("Name", "pandora"))
                                .put(
                                    Emailv31.Message.TO,
                                    new JSONArray().put(new JSONObject().put("Email", recipient)))
                                .put(Emailv31.Message.SUBJECT, "Your email flight plan!")
                                .put(
                                    Emailv31.Message.TEXTPART,
                                    "Dear passenger, welcome to Mailjet!" 
                                    + "May the delivery force be with you!")
                                .put(
                                    Emailv31.Message.HTMLPART,
                                    "<h3>Dear passenger, welcome to Mailjet!</h3>"
                                    + "<br />May the delivery force be with you!")));
    
        try {
          // trigger the API call
          MailjetResponse response = client.post(email);
          // Read the response data and status
          System.out.println(response.getStatus());
          System.out.println(response.getData());
          return response;
        } catch (MailjetException e) {
          System.out.println("Mailjet Exception: " + e);
          return null;
        }
      }
    }
  6. mailjet 目錄,使用 Maven 將類別封裝為 JAR 檔案:
    user@test-centos:~# mvn clean package
  7. 確認您使用的是 OpenJDK 8:
    user@test-centos:~# sudo alternatives --config java
  8. 如要傳送電子郵件,請從目標目錄中執行 JAR 檔案,並以收件者與寄件者的電子郵件地址做為引數:
    user@test-centos:~# java -jar
            compute-mailjet-1.0-SNAPSHOT-jar-with-dependencies.jar
            recipient-email sender-email

Mailjet SMTP 設定

以下是針對 Mailjet 專屬 SMTP 設定提供的用戶端設定快速參考資訊:

  • 主機:in-v3.mailjet.com
  • 通訊埠:2525

後續步驟

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