Zend Mail 2.0 Attachments
Asked Answered
A

1

6

Can anyone provide me with some example on how to add attachments to ZF2 Mail component?

I did like:

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

but got stuck when needed to add an attachment. Thanks.

Asyndeton answered 17/4, 2012 at 12:31 Comment(0)
U
9

To add an attachment, you just have to create a new MIME part and add it to the message.

Example:

// 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

Here is some helpful documentation on the subject: ZF2 - Zend\Mail

Underestimate answered 17/4, 2012 at 17:13 Comment(3)
i have not yet verified it but it seems to be a working solution because I also considered that there should be some deal with Mime. Thanks.Asyndeton
I have no idea why the decision was made to remove the addAttachment method from the Mail class which in ZF1 would just create a new mime part for you and add it to the message, now its a little more explicit.Underestimate
I think it's worth mentioning here that the new MimePart and MimeMessage in ZF 2 are now in the Zend\Mime\Part and Zend\Mime\Message - so you will have to use their namespaces accordingly.Brina

© 2022 - 2024 — McMap. All rights reserved.