Zend Mail 2.0附件

6

请问有人能给我提供一些示例,演示如何向ZF2邮件组件添加附件吗?

我尝试了以下方式:

$message = new Message;
$message->setEncoding('utf-8');
$message->setTo($email);
$message->setReplyTo($replyTo);
$message->setFrom($from);
$message->setSubject($subject);
$message->setBody($body);

但在需要添加附件时遇到了困难。 谢谢。

1个回答

9
为了添加附件,您只需创建一个新的MIME部分并将其添加到消息中。
例如:
// create a new Zend\Mail\Message object
$message  = new Message;

// create a MimeMessage object that will hold the mail body and any attachments
$bodyPart = new MimeMessage;

// create the attachment
$attachment = new MimePart(fopen($pathToAttachment));
// or
$attachment = new MimePart($attachmentContent);

// set attachment content type
$attachment->type = 'image/png';

// create the mime part for the message body
// you can add one for text and one for html if needed
$bodyMessage = new MimePart($body);
$bodyMessage->type = 'text/html';

// add the message body and attachment(s) to the MimeMessage
$bodyPart->setParts(array($bodyMessage, $attachment));

$message->setEncoding('utf-8')
        ->setTo($email)
        ->setReplyTo($replyTo)
        ->setFrom($from)
        ->setSubject($subject)
        ->setBody($bodyPart);  // set the body of the Mail to the MimeMessage with the mail content and attachment

以下是有关该主题的一些有用文档:ZF2 - Zend\Mail


我还没有验证它,但似乎这是一个可行的解决方案,因为我也考虑到了与Mime有关的一些问题。谢谢。 - Alex Oleshkevich
6
我不知道为什么决定从邮件类中移除 addAttachment 方法,它在 ZF1 中只会为您创建一个新的 MIME 部分并将其添加到消息中,现在则更加明确。 - drew010
2
我认为在这里值得一提的是,ZF 2中的新MimePart和MimeMessage现在位于Zend\Mime\Part和Zend\Mime\Message中 - 因此您将必须相应地使用它们的命名空间。 - Spencer Mark

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