2012-12-05 27 views
0

我要發這封郵件中UTF8編碼的消息發送電子郵件..如何UTF8

我能爲這個

include 'functions.php'; 
    $name = stripslashes($_POST['name']); 
    $email = trim($_POST['email']); 
    $subject = stripslashes($_POST['subject']); 
    $message = stripslashes($_POST['message']); 
    $cap=strtoupper($_POST['cap']); 

    $error = ''; 


$mail = mail(WEBMASTER_EMAIL,$subject,$message, 
     "From: ".$name." <".$email.">\r\n" 
     ."Reply-To: ".$email."\r\n" 
     ."X-Mailer: PHP/" . phpversion()); 

我能在UTF8發送該怎麼辦?

+0

不使用電子郵件()它的使用非常有限,直接與郵件服務器的接口庫之一。 [phpmailer]的[Swiftmailer](http://swiftmailer.org/)(http://phpmailer.worxware.com/) – 2012-12-05 20:59:51

回答

2

您可以在電子郵件標題指定編碼,就像這樣:

$mail = mail(WEBMASTER_EMAIL,$subject,$message, 
     "From: ".$name." <".$email.">\r\n" 
     ."Reply-To: ".$email."\r\n" 
     ."Content-type: text/html; charset=UTF-8\r\n" 
     ."X-Mailer: PHP/" . phpversion()); 
1

您可以使用php的utf8_encode函數。像這樣:

$message = utf8_encode(stripslashes($_POST['message'])); 

這將存儲在$消息變量或任何其他爲此事編碼字符串UTF8。

編輯

如果使用swiftmailer庫,它會默認爲utf8編碼。

+0

這可能比編碼消息更多一點工作。其他參數和郵件標題也需要進行編碼。這裏有一個來自'mail()'[文檔頁面](http://php.net/manual/en/function.mail.php)註釋的例子:'$ from_user =「=?UTF-8?B? 」 .base64_encode($ FROM_USER)。 「=」;?'。用戶貢獻的筆記有幾個例子。 – sierrasdetandil

+0

是的。再次,使用一個好的郵件圖書館通常會爲你處理這些事情。 – Pjottur

0

你需要設置在標題中的UTF-8編碼和也編碼的主題,因爲它很容易被損壞。我個人創建自己的功能,其中還增加設置發件人的ADRESS的能力:

function mail_utf8 ($to, $subject='', $message='', $from='', $header='') { 
    if (preg_match("/\<html.*\>/i", $message)) 
    $content_type = "html"; 
    else 
    $content_type = "plain"; 

    $header .= "\nMIME-Version: 1.0"; 
    $header .= "\nContent-type: text/$content_type; charset=UTF-8"; 
    if ($from) 
    $header .= "\nFrom: ".$from; 
    mail($to, "=?UTF-8?B?".base64_encode($subject)."?=", $message, trim($header)); 
} 
+0

PS:我知道這個問題是5個月大,但我不想每次我想發送電子郵件都寫這樣的函數。也許別人也會使用它。 –