2012-04-17 37 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