2015
Oct
05

2015 後,我把這個 Blog 從家裡的伺服器搬到 Google Compute Engine ,為的就是希望能夠有更穩定的網路環境,但是在 Compute Engine 碰到一個問題,就是 sendmail 功能被 Google 給強迫停用了,好在 Google 有提供另一個解決方案,你只要有一台 mail server ,就可以自已指定 mail server host ,幫自已的 service 寄信。

除了自已架 mail server 之外, Google 給予了另一個方案,就是每個 Compute Engine 的用戶可以使用 sendgrid.com 這個服務,並且每個月有 2 萬 5 千封免費的 email 服務,就是你可以寄出 2 萬 5 千封 email,而不用多付任何費用,對於一些小網站來說 , 25000 封信真的是夠用了。


這裡有 Google 提供的 sendmail 教學文件。

文件有寫了很多 postfix 的設定,但是我只需要用到 PHP 來寄信,根本就不會用到那些設定,如果你跟我一樣,那麼可以直接跳過 postfix 設定,只要申請好 sendgrid 的帳號,就能夠直接透過 PHP curl 來送信。

申請 sendgrid 帳號

請先透過 Google 教學中給的連結 [Google partner page.] ,點擊過去就會看到左下方有個 FREE 25,000 的選項。

點擊 "Get Started" 就會自動連到註冊頁,註冊的內容可以隨便打沒關系,但是 Email 一定要填真的,因為對方還會寄兩封英文信給你,每封會問你五個問題,這些問題要如實回答,等到成功通過 sendgrid 的人工審核後,你的帳號就會被開通囉。

剛註冊完成時,新帳號是不能寄信的,一定要等對方人工審核通過,我跟對方來回了幾封 Email ,直到第三天才通過審核。

這裡補上對方問我的問題:

Email Question
  1. We’d like to know a little more about the email you’ll be sending through
  2. 1. The nature of your business, the services you provide, and your potential customer base
  3. 2. Your sending frequency and volume
  4. 3. How you collect your recipient addresses
  5. 4. How you will allow your recipients to opt out of your emails (whether you plan to use SendGrid’s one-click unsubscribe feature, or if you have your own method)
  6. 5. The types of messages you will be sending (transactional or marketing)
  7.  
  8. Could you help us with an answer to the following questions also:
  9. 1. Where did you acquire your recipient list?
  10. 2. What kind of opt-in process do your recipients go through?
  11. 3. How old is your recipient list?
  12. 4. When was the last time you communicated with these recipients?
  13. 5. How do you maintain your recipient list?

用程式寄信

通過審核後,就可以用你 sendgrid 的帳號、密碼來寄信,下面是一個用 Curl 的方式來測試寄信功能,請先把 api_user 與 api_key 改成你自已在 sendgrid 的帳號、密碼,以及修改收信人 Email。

curl -k "https://api.sendgrid.com/api/mail.send.json" --data '[email protected][email protected]&api_user=your_account&api_key=your_password'

另一個方式是先在 sendgrid 建立一個 API Key ,再用這個 API Key 來寄信,這個方式就不需要將帳號密碼寫在程式裡面,比較安全。

Using PHP to send a mail from sendgrid.com
  1. $url = 'https://api.sendgrid.com/';
  2. $pass = 'AK.txxxxxxxxxxxxxxxix';
  3. $params = array(
  4. 'to' => "[email protected]",
  5. 'subject' => "test title",
  6. 'html' => "test content",
  7. 'from' => "admin" . '<[email protected]>',
  8. );
  9.  
  10. $header = array(
  11. 'Authorization: Bearer ' . $pass,
  12. );
  13.  
  14. $request = $url.'api/mail.send.json';
  15. $session = curl_init($request);
  16. curl_setopt ($session, CURLOPT_POST, true);
  17. curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
  18. curl_setopt ($session, CURLOPT_HEADER, false);
  19. curl_setopt ($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
  20. curl_setopt ($session, CURLOPT_RETURNTRANSFER, true);
  21. curl_setopt ($session, CURLOPT_HTTPHEADER, $header);
  22. $response = curl_exec($session);
  23. curl_close($session);

回應 (Leave a comment)