Php电子邮件字符编纂

时间:2012-08-31 10:47:26

标签: php email

我正在使用以下代码从php发送电子邮件。

    $to = 'myemail@domain.com'; 
$subject = 'Test email with attachment'; 
$random_hash = md5(date('r', time())); 
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com"; 
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 
if(isset($_FILES['curriculum_vitae']['name']) && $_FILES['curriculum_vitae']['name'] != ''){ $attachment = chunk_split(base64_encode(file_get_contents($_FILES['curriculum_vitae']['tmp_name']))); }
ob_start();
?> 
--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

Hello World!!! 
This is simple text email message. 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2> 
<p>This is something with <b>HTML</b> formatting.</p> 

--PHP-alt-<?php echo $random_hash; ?>-- 

<?php if(isset($_FILES['curriculum_vitae']['name']) && $_FILES['curriculum_vitae']['name'] != ''){ ?>--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: application/zip; name="<?php echo $_FILES['curriculum_vitae']['name']; ?>"  
Content-Transfer-Encoding: base64  
Content-Disposition: attachment  

<?php echo $attachment; ?> 
--PHP-mixed-<?php echo $random_hash; ?>--
<?php } ?>
<?php 
$message = ob_get_clean(); 
$mail_sent = @mail( $to, $subject, $message, $headers ); 
echo $mail_sent ? "Mail sent" : "Mail failed"; 

然而,当我收到网络邮件上的电子邮件时,我遇到了字符编码问题。像“à”或“ç”这样的字符以奇怪的形式出现。

这是我在上面的代码中定义的编码问题吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

将标题更改为UTF8

text/plain部分

中的

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/plain; charset="UTF-8" 
Content-Transfer-Encoding: 7bit 

并在text/html部分

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/html; charset="UTF-8" 
Content-Transfer-Encoding: 7bit

答案 1 :(得分:0)

使用此代码使用PHP脚本发送邮件

<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>

无需在script.i上设置其他信息。不知道为什么要安排sevral标头和内容类型编码。