10

I am using SwiftMailer to send emails from my application.

All is working fine so far. I now need to be able to change the text of the sender dynamically. The code snippet below and the next paragraph should hopefully clarify what I mean.

Currently, my code looks like this:

try{
   $message = Swift_Message::newInstance()
               ->setFrom($from)
               ->setTo($to)
               ->setSubject($subject)
               ->setBody($content);

   $mailer->send($message);
}catch (Exception $e) {
   // do something ...
}

The $from variable contains the email address of the sender - which is sysmail@mydomain.com

However, I want to send daily digests (for example) for different entities (example forums, groups etc), so I want to be able to set the name text of the sender as 'Forum ABC members daily digest', even though the sender is still sysmailer@mydomain.com. I notice that linkedin is doing something similar - they send out different digests under different sender names, even though the sender is always group-digests@linkedin.com.

The default name for sysmailer@mydomain.com is 'System Mailer'. Incidentally, I am using Google Apps as my mailing service provider. It is not practical for me to setup different user accounts, as users can create their own forums etc.

Is there a way whereby I can dynamically (i.e. via code) specify a sender name, although using the same sender email address?

oompahloompah
  • 9,087
  • 19
  • 62
  • 90

2 Answers2

29

You just have to pass $from as an array.

$from = array($from_email => $from_name);

try{
   $message = Swift_Message::newInstance()
               ->setFrom($from)
               ->setTo($to)
               ->setSubject($subject)
               ->setBody($content);

   $mailer->send($message);
}catch (Exception $e) {
   // do something ...
}

Where you change $from_name for each of your mailers.

Hope it helps!

Sukumar
  • 3,502
  • 3
  • 26
  • 29
  • Can you point me to the part in the docs where this comes from?. If this works - I will be forever in your debt :p ! – oompahloompah Jul 09 '11 at 12:09
  • http://swiftmailer.org/docs/sending.html - See the first code snippet. You don't have to be in my debt. Just upvote and accept if it helped you :) – Sukumar Jul 09 '11 at 12:10
2

you can also use

$message = Swift_Message::newInstance()
           ->setFrom($email, $sender_name)
           ->setTo($to)
           ->setSubject($subject)
           ->setBody($content);
Awad Haj
  • 579
  • 7
  • 17