Imap邮件无法正常工作

时间:2013-12-23 07:51:47

标签: php imap

我的项目中有以下代码。问题是邮件(电子邮件的正文)没有正确显示。

--37cd8764df1f86bc509d0994d83f1d26 Content-type: text/plain;charset="iso-8859-1" Content-Transfer-Encoding: 7bit hello --37cd8764df1f86bc509d0994d83f1d26 Content-type: text/html;charset="iso-8859-1" Content-Transfer-Encoding: 7bit hello --37cd8764df1f86bc509d0994d83f1d26--

它在电子邮件中显示上述结果。其中“你好”是正文。

另一个问题是,如果我附上文件,则不会显示正文,并且正确发送附件。我有以下代码。

<?php
session_start();
ob_start();
?>
<?php
include("validation/lg_check.php");
?>
<?php
$to1=trim($_POST['txt_to']);
$sub=trim($_POST['txt_sub']);
$msg=$_POST['txt_body'];
$_SESSION['err_mail']=array();

if(empty($to1))
{
$_SESSION['err_mail']['to']="Please Enter The Recepient";
exit;
}
$imap = imap_open("{myserver}", $_SESSION['user']);
$return_path = $_SESSION['user'];
$to = $to1;
$subject = $sub;

# Get a random 32 bit number using time() as seed.

$boundary=md5(date('r',time()));
$message=' --'.$boundary."\n";
$message .='Content-type: text/plain;charset="iso-8859-1"'."\n";
$message .='Content-Transfer-Encoding: 7bit'."\n\n";
$message .=$msg."\n";
$message .='--'.$boundary."\n";
$message .='Content-type: text/html;charset="iso-8859-1"'."\n";
$message .='Content-Transfer-Encoding: 7bit'."\n\n";
$message .=$msg."\n";
$message .='--'.$boundary.'--';

if(isset($_FILES['file_upload']) && !empty($_FILES['file_upload']))
{
$fnm=time()."_".$_FILES['file_upload']['name'];
$tmp_file=$_FILES['file_upload']['tmp_name'];
$file_upload=move_uploaded_file($tmp_file,"upload/".$fnm);

}

if($file_upload)
{
# Define the attachment section
# Open a file
$file_name="upload/".$fnm;
$file = fopen( $file_name, "r" );
if( $file == false )
{
echo "Error in opening file";
exit();
}
# Read the file into a variable
$size = filesize("upload/".$fnm);
$content = fread( $file, $size);
# encode the data for safe transit
# and insert \r\n after every 76 chars.
$encoded_content = chunk_split( base64_encode($content));
$headers .= "Content-Type: application/octet-stream; name=".$fnm." ";
$headers .= "name=".$fnm."\r\n";
$headers .= "Content-Transfer-Encoding:base64\r\n";
$headers .= "Content-Disposition: attachment;";
$headers .= "filename=".$fnm."\r\n\n";
$headers .= "$encoded_content\r\n";
$headers .= "--$num--";
}       

# Send email now
$retval = imap_mail($to,$subject,$message,$headers, $return_path);
if( $retval == true )
{
echo "Message sent successfully...";
/* print $header;
print $message;
echo '<br>';
print $to;
echo '<br>';
print $subject;
echo '<br>';
print $message;
echo '<br>';
print $fnm; */
}
else
{
echo "Message could not be sent...";
}
?>

1 个答案:

答案 0 :(得分:0)

如果您尝试在一个邮件正文中发送多个编码,首先必须告诉客户您这样做以及实际拆分的边界是什么。

因此,在开始使用多个消息体之前,必须将其包装到“Content-type:multipart / alternative”中,该参数具有以下参数:“boundary =”---您的边界---“:

$message='Content-Type: multipart/alternative; 
     boundary="' . $boundary . '"' . "\r\n" . "\r\n";

你需要通过CR和LF来终止每一行! 并且Headers需要两次分开身体。

你应该真正阅读RFC的邮件标题,这很烦人,我知道,但发送格式错误的电子邮件也是如此。有比MS Outlook更多的邮件客户端!