Skip to main content

Sending attachments with ZendMail

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

I had a hard time figuring out how to properly send attachments with ZendMail. All the hints I found on the internet did not work for me. After an intense debugging session I came up with the following "short" snippet that I`d like to share with you. To display the attachments correctly in your favorite MUA you have to supply the correct mime type for the file you want to attach to the mail message. Use this article here as a source for some in-depth insights how you can detect the mime-type for a file with a decent fallback routine (if needed).

In case there's an easier way for sending attachments feel free to leave a comment. I am curious to know if I did the "right thing"(tm) ;)

$server    = 'smtp.localhost';
$port = 25;
$username = 'foo';
$password = 'bar';
$recipient = 'foo@bar.org';
$sender = 'bar@foo.org';
$subject = 'Mail with attachment';
$bodyPart = new \Zend\Mime\Message();
$parts = array();

// list attachments here
$attachments = array(
'/tmp/attachment.txt' => 'text/plain'
);

// create Mime part for the message body
$bodyMessage = new \Zend\Mime\Part($message->getBody());
$bodyMessage->type = 'text/plain';
$parts[] = $bodyMessage;

// create attachment parts
foreach($attachments as $filename => $mimetype)
{
// read content and build {@link \Zend\Mime\Part} with it
$content = file_get_contents($filename);
$attachment = new \Zend\Mime\Part($content);
$attachment->filename = basename($filename);
$attachment->disposition = 'attachment';
$attachment->type = $mimetype;
$attachment->encoding = 'base64';
$parts[] = $attachment;
}

// add all parts to the $bodyPart
$bodyPart->setParts($parts);

// create the MailMessage object
$mail = new \Zend\Mail\Message();
$mail->setEncoding('utf-8')
->addTo($recipient)
->addFrom($sender)
->setSubject($subject)
->setBody($bodyPart);

// set-up transport
$protocol = new \\Zend\\Mail\\Protocol\\Smtp\\Auth\\Login(
$server,
$port,
array(
'username' => $username,
'password' => $password
)
);

$protocol->connect();
$protocol->helo('localhost');
$transport = new \\Zend\\Mail\\Transport\\Smtp();
$transport->setConnection($protocol);

// send the mail
$transport->send($mail);