CodeIgniter: Using PHPMailer to Send Email via GMAIL

CodeIgniter 內建的 Email Class 對雙位元文字的處理實在很糟,設了 charset 也無法正確寄出 UTF-8 中文信件,從 1.7.1 到 2.0.3 都沒有解決這個問題。同事的處理手法有點囧,是用 iconv 把繁中轉成 GBK 再寄送,但這個方法也不完美,不是每個 Email Client 都能正確無誤地顯示,而且標題也有字數限制。

最近要處理一個電子報系統,再用 CI 那跛腳 Email Class 大概會被客訴到瘋掉。所以還是認命改用老牌的 PHPMailer Library。稍微試一下,發現在 CI 裡使用 PHPMailer 相當無痛,先到官網下載一份 PHPMailer (本文完成時的最新版本是 5.2.0),解壓縮後把整個資料夾丟到 CI\application\libraries\PHPMailer_5.2.0。接著在 libraries 下建立新檔案,就叫 mailer.php 好了。

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mailer {

	var $mail;

    public function __construct()
    {
		require_once('PHPMailer_5.2.0/class.phpmailer.php');

		// the true param means it will throw exceptions on errors, which we need to catch
		$this->mail = new PHPMailer(true);

		$this->mail->IsSMTP(); // telling the class to use SMTP

		$this->mail->CharSet = "utf-8";                  // 一定要設定 CharSet 才能正確處理中文
		$this->mail->SMTPDebug  = 0;                     // enables SMTP debug information
		$this->mail->SMTPAuth   = true;                  // enable SMTP authentication
		$this->mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
		$this->mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
		$this->mail->Port       = 465;                   // set the SMTP port for the GMAIL server
		$this->mail->Username   = "YOUR_GAMIL@gmail.com";// GMAIL username
		$this->mail->Password   = "YOUR_PASSWORD";       // GMAIL password
		$this->mail->AddReplyTo('YOUR_GAMIL@gmail.com', 'YOUR_NAME');
		$this->mail->SetFrom('YOUR_GAMIL@gmail.com', 'YOUR_NAME');
    }

	public function sendmail($to, $to_name, $subject, $body){
		try{
			$this->mail->AddAddress($to, $to_name);

			$this->mail->Subject = $subject;
			$this->mail->Body    = $body;

			$this->mail->Send();
				echo "Message Sent OK</p>\n";

		} catch (phpmailerException $e) {
			echo $e->errorMessage(); //Pretty error messages from PHPMailer
		} catch (Exception $e) {
			echo $e->getMessage(); //Boring error messages from anything else!
		}
	}
}

/* End of file mailer.php */

接著在 Controller 裡呼叫這支 library 就可以了,範例如下。

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Epaper extends CI_Controller {
	public function __construct(){
		parent::__construct();
	}
	public function send(){
		$mail_body = "落落長的內文";
		$this->load->library('mailer');
		$this->mailer->sendmail(
			'address@example.com',
			'收件人',
			'這是測試信 '.date('Y-m-d H:i:s'),
			$mail_body
		);
	}
}
/* End of file epaper.php */

至於多重收件人之類的設定就要另外再變化了,這邊只是最入門的版本。


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version