Code snippets for symfony 1.x


Refine Tags

Snippets tagged "view email"

Helper: Embedding images in emails

Embedding images in emails as described in the symfony book has one drawback: it breaks the MVC paradigm by setting properties of the view (embedding the image) in the controller.

This is probably more obvious when embedding images such as company logos that are not part of a query result, but instead are 'static' visual enhancements of the view.

Besides being not good practice, this results in more code and potential mistakes when using several images, as you need to keep track of cid's both in the action and in the template.

This helper lets you treat images in emails similar to images in regular HTML views. There are no calls to $mail->addEmbeddedImage() needed in the action, embedding is done exclusively in the view, and you can forget about cid's.

Update: In the original version, an image used twice in the email would also be embedded twice, increasing email size. This bug is fixed.


Images are embedded like this:

<?php echo embedded_image($this, '/myImageDir/myImage.jpg' [, $altText [, $encoding [, $mimeType]]]); ?>

The parameters are:

$this: a reference to the current sfMailView

filename: the path to the image to be embedded

$altText: alternative name for attachment, default is ''

$encoding: encoding, default is base64

$mimeType: mime type, when omitted, mime type is determined using the file extension of the image

The Helper

function embedded_image(
    $altText = '',
    $encoding = 'base64',
    $mimeType = null
) {
    // get list of files already embedded
    $embeddedList = $mailView->getParameter('embedList', array(), 'email_helper');
    if (array_key_exists($fileName, $embeddedList)) {
        // if image was already embedded, use its old cid
        $embedString = $embeddedList[$fileName];
    } else {
        // find mime type
        if ($mimeType == null) {
            $mimeMap = array(
                'gif' => 'image/gif',
                'jpg' => 'image/jpeg',
                'png' => 'image/png'
            $ext = strtolower(array_pop(explode('.', $fileName)));
            if (array_key_exists($ext, $mimeMap)) {
                $mimeType = $mimeMap[$ext];
            } else {
                $mimeType = 'image/jpeg';
        // increment embedded image count
        $imgID = $mailView->getParameter('embedIndex', 0, 'email_helper') + 1;
        $mailView->setParameter('embedIndex', $imgID, 'email_helper');
        $embedString = 'embID_' . $imgID;
        // add image to mail
        // remember embedded file
        $embeddedList[$fileName] = $embedString;
        $mailView->setParameter('embedList', $embeddedList, 'email_helper');
    return '<img src="cid:' . $embedString . '" />';
by donharold on 2006-05-31, tagged email  helper  mvc  view