7

如何在 zf2 中发送带有 text/plain、text/html 和附件的电子邮件?我使用此代码通过 smtp 发送电子邮件:

$files = $this->params()->fromFiles();
$smtp = new \Zend\Mail\Transport\Smtp();
$smtp->setAutoDisconnect(true);
$optn = new \Zend\Mail\Transport\SmtpOptions(array(
    'host'              => 'mail.myserver.com',
    'connection_class'  => 'login',
    'connection_config' => array(
        'username' => 'user@myserver.com',
        'password' => 'mypassword',
    ),
));
$smtp->setOptions($optn);


$htmlPart = new \Zend\Mime\Part('<p>some html</p>');
$htmlPart->type = Mime::TYPE_HTML;

$textPart = new \Zend\Mime\Part('some text');
$textPart->type = Mime::TYPE_TEXT;

$i=0;
$attaches = array();
foreach($files as $file){
    if ($file['error'])
        continue;
    $attaches[$i] = new \Zend\Mime\Part(file_get_contents($file['tmp_name']));
    $attaches[$i]->type = $file['type'].'; name="'.$file['name'].'"';
    $attaches[$i]->encoding = 'base64';
    $attaches[$i]->disposition = 'attachment';
    $attaches[$i]->filename = $file['name'];
    $i++;
}

$parts = array();
if (count($attaches)>0) {
    $parts = array_merge(array($textPart,$htmlPart),$attaches);
    $type = Mime::MULTIPART_MIXED;
}
else{
    $parts = array($textPart, $htmlPart);
    $type = Mime::MULTIPART_ALTERNATIVE ;
}
$body = new \Zend\Mime\Message();
$body->setParts($parts);

$message = new \Zend\Mail\Message();
$message->setFrom('user@myserver.com');
$message->addTo('receiver@myserver.com');
$message->setSubject('subject');
$message->setEncoding("UTF-8");
$message->setBody($body);
$message->getHeaders()->get('content-type')->setType($type);

$smtp->send($message);

如果我附加文件,它会发送文件和内容,但它会在接收者收件箱中同时显示纯文本和 html 文本:

<p>some html</p>
some text

当我不附加任何文件时,它会单独显示 html 文本:

some html

有什么帮助吗?

4

4 回答 4

13

目前在 ZF2 (2.2) 中没有简单的方法将多部分/替代正文(html 与不能/不想使用 html 的客户端的文本替代)与附件相结合。如果您将“multipart/alternative”内容类型标头添加到整个邮件,在某些电子邮件客户端中,附件(链接)将不会显示。

解决方案是将消息分成两部分,正文(文本和 html)和附件:

http://jw-dev.blogspot.com.es/2013/01/zf2-zend-mail-multipartalternative-and.html

一个例子:

        $content  = new MimeMessage();
        $htmlPart = new MimePart("<html><body><p>Sorry,</p><p>I'm going to be late today!</p></body></html>");
        $htmlPart->type = 'text/html';
        $textPart = new MimePart("Sorry, I'm going to be late today!");
        $textPart->type = 'text/plain';
        $content->setParts(array($textPart, $htmlPart));

        $contentPart = new MimePart($content->generateMessage());        
        $contentPart->type = 'multipart/alternative;' . PHP_EOL . ' boundary="' . $content->getMime()->boundary() . '"';

        $attachment = new MimePart(fopen('/path/to/test.pdf', 'r'));
        $attachment->type = 'application/pdf';
        $attachment->encoding    = Mime::ENCODING_BASE64;
        $attachment->disposition = Mime::DISPOSITION_ATTACHMENT;

        $body = new MimeMessage();
        $body->setParts(array($contentPart, $attachment));

        $message = new Message();
        $message->setEncoding('utf-8')
        ->addTo('mywife@home.com')
        ->addFrom('myself@office.com')
        ->setSubject('will be late')
        ->setBody($body);

        $transport = new SmtpTransport();
        $options   = new SmtpOptions($transportConfig),
        ));

        $transport->setOptions($options);
        $transport->send($message);

对于上述情况,您需要以下使用语句:

use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
use Zend\Mime\Mime;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;

ZF1 有一种自动执行此操作的_buildBody()方法。Zend_Mail_Transport_Abstract

于 2013-07-05T10:37:03.533 回答
2

我发现它是一个更好的解决方案,所以我正在写它。

Namespace YourNamesapace;

use Zend\Mail\Message as ZendMessage;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
use Zend\Mail\Transport\Sendmail;
class Testmail
{
    public static function sendMailWithAttachment($to, $subject, $htmlMsg, $dir, $fileName)
    {
        $fileFullPath = $dir . '/' . $fileName;
        // Render content from template
        $htmlContent = $htmlMsg;
        // Create HTML part
        $htmlPart = new MimePart($htmlContent);
        $htmlPart->type = "text/html";
        // Create plain text part
        $stripTagsFilter = new \Zend\Filter\StripTags();
        $textContent = str_ireplace(array("<br />", "<br>"), "\r\n", $htmlContent);
        $textContent = $stripTagsFilter->filter($textContent);
        $textPart = new MimePart($textContent);
        $textPart->type = "text/plain";

        // Create separate alternative parts object
        $alternatives = new MimeMessage();
        $alternatives->setParts(array($textPart, $htmlPart));
        $alternativesPart = new MimePart($alternatives->generateMessage());
        $alternativesPart->type = "multipart/alternative;\n boundary=\"".$alternatives->getMime()->boundary()."\"";

        $body = new MimeMessage();
        $body->addPart($alternativesPart);


        $attachment = new MimePart( file_get_contents($fileFullPath) );
        $attachment->type = \Zend\Mime\Mime::TYPE_OCTETSTREAM;
        $attachment->filename = basename($fileName);
        $attachment->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
        $attachment->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
        $body->addPart($attachment);
        // Create mail message
        $mailMessage = new ZendMessage();
        $mailMessage->setFrom('noreply@example.com', 'from Name');
        $mailMessage->setTo($to);
        $mailMessage->setSubject($subject);
        $mailMessage->setBody($body);
        $mailMessage->setEncoding("UTF-8");
        $mailMessage->getHeaders()->get('content-type')->setType('multipart/mixed');
        $transport = new Sendmail();
        $transport->send($mailMessage);
    }
}
于 2016-03-08T05:44:03.167 回答
0

设置类型:

$attaches[$i]->type = $file['type'].'; name="'.$file['name'].'"';

到:

$attaches[$i]->type = \Zend\Mime\Mime::TYPE_OCTETSTREAM;

您还需要确认,如果您使用的是 SMTP 服务,它们是否允许通过协议进行附件。

于 2013-06-12T19:48:43.253 回答
-4

带附件的电子邮件

$mail = new Zend\Mail\Message();
// build message...
$mail->createAttachment($someBinaryString);
$mail->createAttachment($myImage,
                        'image/gif',
                        Zend\Mime\Mime::DISPOSITION_INLINE,
                        Zend\Mime\Mime::ENCODING_BASE64);

如果您想对为此附件生成的 MIME 部分进行更多控制,您可以使用 createAttachment() 的返回值来修改其属性。createAttachment() 方法返回一个 Zend\Mime\Part 对象:

$mail = new Zend\Mail\Message();

$at = $mail->createAttachment($myImage);
$at->type        = 'image/gif';
$at->disposition = Zend\Mime\Mime::DISPOSITION_INLINE;
$at->encoding    = Zend\Mime\Mime::ENCODING_BASE64;
$at->filename    = 'test.gif';

$mail->send();

另一种方法是创建 Zend\Mime\Part 的实例并使用 addAttachment() 添加它:

$mail = new Zend\Mail\Message();

$at = new Zend\Mime\Part($myImage);
$at->type        = 'image/gif';
$at->disposition = Zend\Mime\Mime::DISPOSITION_INLINE;
$at->encoding    = Zend\Mime\Mime::ENCODING_BASE64;
$at->filename    = 'test.gif';

$mail->addAttachment($at);

$mail->send();

参考 1 参考2 参考3

于 2013-06-13T16:51:33.873 回答