Code snippets for symfony 1.x


Refine Tags

Snippets tagged "email"

Render partials in a Task

I needed to send emails from a task using partials. The technique for SF 1.3/4 is explained in the docs, but how to get links to render properly is not. I found some good info on the web that was a bit hidden. Here is what it lead me to come up with.

To be able to use partials you need to set the context correctly:


Since tasks don't have a url as their base for the request, helpers like url_for and link_to won't work correctly and output things like "/symfony/symfony/mymodule/myaction".

to remedy this I created a helper:

class batchHelpers
  public static function url_for($str)
    $url = 'http://'.
            sfConfig::get('app_server_url','') .
    return $url;

the define for the "server_url" is in app.yml

Then in the partial I used this code to call get a correctly generated url:

batchHelpers::url_for('/home', true), array(

I also render the same partial (with the same url_for replacement) inside the web interface and since the urls are absolute, they work correctly.

by Alex Knol on 2010-10-26, tagged email  partial  task  urlfor 

antispam helper for mailto link

Provide 4 functions which crypt e-mail address with javascript in order to not be captured by spammers robots.

by Sylvain PAPET on 2007-11-19, tagged email  helper  spam 

How to use sfMail to encode body of Japanese Email.

How to use sfMail to encode Body of Japanese Email.

The Japanese Email usually use ISO-2022-JP. But, I want to use UTF-8 of any Email template files. For example...

I create PROJECT_DIR/lib/myMail.class.php


class myMail extends sfMail
  public function setBody ($body)
    parent::setBody(mb_convert_encoding($body, "JIS", "UTF-8"));

OK, Use this class from your Action.


  public function executeSendmail()
    $mail = new myMail();
by Kota Sakoda on 2007-02-13, tagged email  encode  iso2022jp  japanese  sfmail  utf8 

Encode URL and caption like Smarty does ;)

This is very simple and effective mail helper. Original code is taken from Smarty's mailto plugin.
This helper scrambles your email addresses so those nasty web bots 'can not' harvest them.

In /lib/helper/MailEncodeHelper.php

function encode_mail($Address, $Caption=null)
  if ($Caption == null)
    $Caption = $Address;
  $string = 'document.write(\'<a href="mailto:'.$Address.'">'.$Caption.'</a>\');';
  $js_encode = '';
  for ($x=0; $x < strlen($string); $x++)
    $js_encode .= '%' . bin2hex($string[$x]);
  return '<script type="text/javascript">eval(unescape(\''.$js_encode.'\'))</script>';

In template

<?php use_helper('MailEncode') ?>
My email: <?php echo encode_mail(''); ?>  
My email: <?php echo encode_mail('', 'Damjan Malis'); ?>
by Damjan Malis on 2006-07-19, tagged email  encode  helper 

Sending batch emails

Sending a large volume of emails using symfony's built-in email support can be problematic because of memory overhead involved in calling the sendEmail action for every email to be sent. In order to overcome this, we will have to use another way. In essence, instead of making multiple symfony mail calls, we will grab the presentation for the email action, then use sfMail directly to send our emails.

In an action

// Get the presentation only for the actual email.
// email/newsletter is the module/action pair that will
// generate the template for the actual email in this example.
$raw_email = $this->getPresentationFor('email', 'newsletter');
require_once sfConfig::get('sf_symfony_lib_dir') . '/addon/sfMail/sfMail.class.php';
$mail = new sfMail();
$mail->setFrom($sender_email, $sender_name);
// To further ensure that we don't choke up on the
// emails, we introduce a throttle. In this example,
// we use 100, which we will use to sleep for a period
// of time for every 100 emails sent.
$throttle = 100;
$i = 0;
// Now, run a loop through all the email addresses in the mailing list.
foreach($email_addrs as $email_addr)
    if ($i % $throttle == 0)
        sleep(10); // Here, we sleep for 10 seconds for every $throttle emails sent.

That's it! Now, just go ahead and set up the email/newsletter pair which will set up the template for the actual email.

Update: In order to beat the maximum execution time limit in PHP, I also use


to remove the limit at the start of my actual script. In addition, it may also be a good idea to run the action as a batch script in the background so that the mass mailing can occur in the background.

by Ron Lim on 2006-06-26, tagged batch  email 

Sending email from a batch script

It can be tricky sending email from a batch script (e.g. for cron use), here's how to do it. Start with your usual batch setup:

define('SF_ROOT_DIR',    realpath(dirname(__FILE__).'/..'));
define('SF_APP',         'app_name');
define('SF_ENVIRONMENT', 'environment');
define('SF_DEBUG',       true);

You can set attributes directly from the batch script if you wish:

sfContext::getInstance()->getRequest()->setAttribute('key', $value);

Then forward on to another module/action to handle processing and forwarding to mail as usual:

sfContext::getInstance()->getController()->forward('action', 'module');
by James McGlinn on 2006-06-22, tagged batch  cli  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