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

2

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 [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?

Moiety answered 9/7, 2011 at 11:8 Comment(0)
C
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!

Chariness answered 9/7, 2011 at 11:56 Comment(2)
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 !Moiety
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 :)Chariness
B
2

you can also use

$message = Swift_Message::newInstance()
           ->setFrom($email, $sender_name)
           ->setTo($to)
           ->setSubject($subject)
           ->setBody($content);
Batish answered 21/11, 2016 at 15:1 Comment(1)
Care to elaborate?Devine

© 2022 - 2024 — McMap. All rights reserved.