使用Swift Mailer发送多部分/可选邮件

4
我无法使用 Swift Mailer 发送多部分/备选内容(我没有找到任何参考资料,所以可能无法使用此功能),以下是我的代码:
$file[1]=html_entity_decode($file[1]);
//Prepare plain/html body
foreach($rep as $find => $sost)
    $file[1]=str_replace($find,$sost,$file[1]);
//Prepare plain/text body
$plain=strip_tags(str_replace('&nbsp;',' ',str_replace('<br/>',"\n",$file[1])));
$boundary=uniqid('n_=_p');
//Prepare mail body                 
$body = "--".$boundary."\r\n";
$body .= "Content-type: text/plain;\r\ncharset=utf-8\r\nContent-Transfer-Encoding: 7bit\r\n";
$body .= $plain;
$body .= "\r\n--".$boundary."\r\n";
$body .= "Content-type: text/html;\r\ncharset=utf-8\r\nContent-Transfer-Encoding: 7bit\r\n";
$body .= "<html><body>".$file[1]."</body></html>";
$body .= "r\n--".$boundary ."--";
//Send Mail
$message = Swift_Message::newInstance();
$message->setFrom(array($stmp[2]=>$stmp[1]));
$message->setReplyTo(array($stmp[2]=>$stmp[1]));
$message->setSubject($file[0]);
$message->setContentType("multipart/alternative");  
$message->setBody($body);
$message->setTo($mail);
$message->setBoundary($boundary);

if($stmp[0]==0)
    $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -t');
else if($stmp[0]==1){
    if($stmp[5]==0)
        $transport = Swift_SmtpTransport::newInstance($stmp[2],$stmp[4]);
    else
        $transport = Swift_SmtpTransport::newInstance($stmp[2],$stmp[4],'ssl');

    if($stmp[6]==1){
        $transport->setUsername($stmp[7]);
        $transport->setPassword($stmp[8]);
    }
}

$mailer = Swift_Mailer::newInstance($transport);

if(!$mailer->send($message,$failure))
    file_put_contents('send_mail_Send_error',print_r($failure,true));

通常我会收到一条无法理解的信息或一个名为“noname”的附件文件。有人能帮助我吗?谢谢。

2
你正在严重滥用SwiftMailer。完全没有必要设置自己的标题。使用->setBody('html content here', 'text/html')->addPart('plaintext alternative here', 'text/plain')即可。 - Marc B
我还没有理解->addPart的用法,谢谢。出于垃圾邮件的原因,将默认内容类型设置为text/plain并在之后附加HTML部分是否更好?谢谢。 - Razorphyn
1
大多数人在非HTML邮件中使用备用文本,这样那些没有HTML支持的人仍然可以阅读到你的电子邮件内容。至于垃圾邮件目的,我不能确定。我非常怀疑备用文本与主体内容的相对位置是否相关,但这完全取决于个别的垃圾邮件过滤器/评分系统。 - Marc B
可能是Multipart email with swift的重复问题。 - flu
1个回答

8
一个解决方案(来自Marc B的评论):
$message = Swift_Message::newInstance();
$message->setFrom($stmp[2])
  ->setReplyTo($stmp[2])
  ->setSubject($file[0])
  ->setContentType("text/plain; charset=UTF-8")
  ->setBody($plain,'text/plain')                
  ->addPart($file[1],'text/html');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接