Posts Tagged ‘Mail’

PHP學習筆記 – 寄送Mail

Saturday, June 13th, 2009

MyMailer.php

其中用到Base64 Encode的方式,信件的寄件者和標題中文才不會變亂碼

<?php
class MyMailer {
  const headerFormat = '=?utf-8?b?%s?=';

  public static function mail($from, $to, $subject, $body) {
    // convert to base64 string
    $from = sprintf(self::headerFormat, base64_encode($from));
    $subject = sprintf(self::headerFormat, base64_encode($subject));

    // To send HTML mail, you can set the Content-type header.
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    $headers .= "From: ". $from . "\r\n"; // 寄件者
    //$headers .= "Cc: xxxgmail.com\r\n"; // 副本
    //$headers .= "Bcc: yyy@gmail.com\r\n"; // 密件副本

    return mail($to, $subject, $body, $headers);
  }
}
?>

Example

";
$to = "Z先生 ";
$subject = "中文標題測試! 許功蓋...測試一下~~~ !@#$%^&*()_+=-0987654321|\:\";'{}[]<>?,./-*/+   123";
$body = <<< HTML_BODY





許功蓋...測試!!
!@#$%^&*()_+=-0987654321|\:";'{}[]<>?,./-*/+ 123 abcdeffghijklmnopqrstuvwxyz HTML_BODY; $result = MyMailer::mail($from, $to, $subject, $body); if( $result ) echo "寄送成功!"; else echo "寄發失敗!"; ?>

Gmail收到信顯示的結果