2012-04-17 58 views
6

任何人都可以提供一些关于如何添加附件到ZF2 Mail组件的例子吗?Zend Mail 2.0附件

我不喜欢:

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

但需要添加附件时卡住了。 谢谢。

回答

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

+0

我尚未确认,但它似乎是一个有效的解决方案,因为我还认为,应该有一定的交易与Mime。谢谢。 – 2012-04-18 15:59:58

+6

我不知道为什么决定从Mail类中删除'addAttachment'方法,这个方法在ZF1中只会为你创建一个新的MIME部分,并将它添加到消息中,现在更加明确一些。 – drew010 2012-04-18 16:39:33

+2

我认为这里值得一提的是,ZF 2中的新MimePart和MimeMessage现在在Zend \ Mime \ Part和Zend \ Mime \ Message中,因此您必须相应地使用它们的命名空间。 – 2012-08-02 09:46:09