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)