Skip to content

Instantly share code, notes, and snippets.

@CrBoy
Created July 18, 2012 08:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CrBoy/3135053 to your computer and use it in GitHub Desktop.
Save CrBoy/3135053 to your computer and use it in GitHub Desktop.
範例:使用 PHPMailer 透過 Gmail 寄送信件
本範例使用 PHPMailer (http://sourceforge.net/projects/phpmailer/) 發送 email。
首先需要注意的是,下載時有可能讓人困惑,我下載的是 http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/PHPMailer%20v5.1/ 這個版本。
執行方式:使用 command line php 直接執行 `$ php ezgmail.php`
範例中包含設定方式、訊息樣板 (msg)、簡單樣板引擎 (fill_template)、名單的 parser (parse_name_list_tsv)與自動根據名單發信的範例,皆相當容易修改。
需注意的是,Gmail 有發送郵件相關的限制,若超過限制,帳號會被暫時停用一天。
<?php
require_once("PHPMailer_v5.1/class.phpmailer.php");
date_default_timezone_set('Asia/Taipei');
$mail= new PHPMailer();
// Server 資訊
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->CharSet = "utf-8";
// 登入
$mail->Username = "your_gmail_account@gmail.com"; //帳號
$mail->Password = ""; //密碼
// 寄件者
$mail->From = "your_gmail_account@gmail.com"; //寄件者信箱
$mail->FromName = "Your Name"; //寄件者姓名
//$mail->ConfirmReadingTo = "your_gmail_account@gmail.com"; // 讀取回條 (對 Gmail 沒啥用)
// 郵件資訊
$mail->Subject = "title"; //設定郵件標題
$mail->IsHTML(true); //設定郵件內容為HTML
function send_mail($mail_address, $name, $body)
{
global $mail;
$mail->Body = $body;
$mail->ClearAddresses();
$mail->AddAddress($mail_address,$name); //新稱收件者 (郵件及名稱)
//$mail->AddCC("some_other one@gmail.com", "Someone"); // 新稱副本收件者
if(!$mail->Send()) {
echo "Error: " . $mail->ErrorInfo . "\n";
} else {
echo "Send To: " . $mail_address . "\n";
}
}
function msg()
{
return <<<EOF
<p>Hi $%name%,
<p>Here's the HTML template with $%pattern_strings%.
EOF;
}
function fill_template($content, $data)
{
foreach($data as $key => $value){
$content = str_replace('$%'.$key.'%', $value, $content);
}
return $content;
}
function parse_name_list_tsv($filename)
{
$namelist = array();
$file = fopen($filename, 'r');
while($line = fgets($file)){
$line = str_replace("\n", "", $line);
list($name, $mail_address, $vip_code) = explode("\t", $line);
$namelist[] = array('name'=>$name, 'mail_address'=>$mail_address, 'vip_code'=>$vip_code);
}
return $namelist;
}
$namelist = parse_name_list_tsv('list.tsv');
//var_dump($namelist); die(); // convenient for show the name list
// Send email to all persons in name list
foreach($namelist as $data){
$body = fill_template(msg(), $data);
send_mail($data['mail_address'], $data['name'], $body);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment