2020-01-20

CodeIgniter 3 利用 Email Library 透過 gmail smtp over tls 寄信

在寫公司的網站系統時,有個功能是讓瀏覽者看到有興趣的課程時可以留下資料,在留下資料時,若是有填寫 email 資訊的,在確認資訊正確後,會直接由系統將該課程的 dm 資料寄 email 的方式給該瀏覽者。

我是用 CodeIgniter 3 的 php mvc framework 來寫這個網站的,那正好在使用它自己的 email library 時有遇到一些狀況,而在網路上找資料的過程中發現的一些資訊,特此留下一個記錄。

參考資料


Support for SMTP over TLS(STARTTLS): https://forum.codeigniter.com/thread-31578.html


Load library: email and initialize:
$this->load->library('email', array(
'validate' => true,
'protocol' => 'smtp',
'charset' => 'utf-8',
'smtp_host' => 'tcp://smtp.gmail.com',
'smtp_port' => '25',
'smtp_crypto' => 'tls',
'smtp_timeout' => '30',
'smtp_user' => 'gmail account',
'smtp_pass' => 'gmail password',
'newline' => "\r\n",
'mailtype' => 'html',
'wordwarp' => true
));
那個 from, to, subject, message, send...我就不寫了,因為主要就是上面 config 的部份。

一開始我按照官方寫的 preferences 設定時,我原本是這樣設定 config 的
$this->load->library('email', array(
'validate' => true,
'protocol' => 'smtp',
'charset' => 'utf-8',
'smtp_host' => 'tls://smtp.gmail.com',
'smtp_port' => '587',
'smtp_timeout' => '30',
'smtp_user' => 'gmail account',
'smtp_pass' => 'gmail password',
'newline' => "\r\n",
'mailtype' => 'html',
'wordwarp' => true
));
這樣一直無法寄出,看了 print_debugger() 的訊息都會寫
(前略)
Failed to send AUTH LOGIN command. Error: 530 5.7.0 Must issue a STARTTLS command first. ________________ - gsmtp
Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.
(後略)
這時如果將 tls 改為用 ssl 的話,config 如下
$this->load->library('email', array(
'validate' => true,
'protocol' => 'smtp',
'charset' => 'utf-8',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => '465',
'smtp_timeout' => '30',
'smtp_user' => 'gmail account',
'smtp_pass' => 'gmail password',
'newline' => "\r\n",
'mailtype' => 'html',
'wordwarp' => true
));
是可以正常寄出,但我還是想要是透過 tls 的方式…後來在 CodeIgniter forum 中翻到「Support for SMTP over TLS(STARTTLS)」才瞭解,原來是要改用 tcp 限定 25 port 的方式下再增加 smtp_crypto 來指定是要用 tls 或 ssl 加密方式;但很奇怪的是網路上有不少文章是說用 ssl:// 限定 465 port 或 tls:// 限定 587 port 就行了…而 ssl 的方式也確實可以,就 tls 一直測不出來,連 print_debugger() 回應的也是「Must issue a STARTTLS command first」…

網路上也有找到不少在討論 CodeIgniter 在 email 這邊的文章都會說改用 phpmailer 的方式就好,但其實個人覺得 CodeIgniter 3 的 email library 是融入 phpmailer 了,所以沒道理改用 phpmailer 可以正常,而 CI 自己的 email library 就不行…

而且,就算用 phpmailer ,大部份也是看到去用 gmail by ssl 的方式,但感覺以後 ssl 會被棄用,還是早早 over 到 tls 會比較好。

沒有留言: