Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the name text of sender when sending mail with Swift_Message?

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 [email protected]

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 [email protected]. I notice that linkedin is doing something similar - they send out different digests under different sender names, even though the sender is always [email protected].

The default name for [email protected] 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?

like image 327
oompahloompah Avatar asked Jul 09 '11 11:07

oompahloompah


1 Answers

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!

like image 170
Sukumar Avatar answered Sep 21 '22 11:09

Sukumar