在 PHP 專案裡,借助 PEAR 的 Mail 套件可以輕鬆完成郵件寄送。它支援三種底層發送方式,可依環境挑選最合適的一種。
<?php
require_once('Mail/Mail.php');
$recipients = '111@111.com';
$headers['From'] = '111@111.com';
$headers['To'] = '111@111.com';
$headers['Subject']= 'Test message';
$body = 'Test message';
$params['username'] = '111@111.com';
$params['password'] = '111';
$params['auth'] = true;
// 以 Mail::factory 建立郵件物件
$mail_object =& Mail::factory('mail', $params);
$mail_object->send($recipients, $headers, $body);
?>
若要寄送 HTML 內容或夾帶附件,則需搭配 Mail_mime 類別來組裝郵件主體與標頭。
<?php
include('Mail.php');
include('Mail/mime.php');
$text = 'This is a Christmas email from www.omni-batties.com.';
$html = '<html><body><h3><font color=red>This is a Christmas email from www.omni-batties.com.</font></h3></body></html>';
$file = 'Special_Offer_For_Christmas.htm';
$crlf = "\n";
$hdrs = array(
'From' => '111@111.com',
'To' => 'Merry Christmas',
'Subject' => 'Christmas Message from www.omni-batties.com'
);
$mime = new Mail_mime();
$mime->setTXTBody($text);
$mime->setHtmlBody($file, true);
$mime->addAttachment($file, 'text/html');
$body = $mime->get();
$hdrs = $mime->headers($hdrs);
$params['host'] = 'mail.111.com';
$params['auth'] = true;
$params['username'] = '111@111.com';
$params['password'] = '111';
$recipients = array('111@111.com', '222@111.com');
$send = @$mail = &Mail::factory('smtp', $params);
$mail->send($recipients, $hdrs, $body);
if (PEAR::isError($send)) {
echo($send->getMessage());
} else {
echo("send successfully");
}
show_source($_SERVER['PHP_SELF']);
?>
實務上請務必將範例中的帳號、密碼與主機位址替換為自己環境的實際設定,並避免把敏感憑證寫死在原始碼中。