Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift mailer default sender

I'm trying to set a default sender to all messages in Swift Mailer 4.3.0, but couldn't find a proper solution. I want to avoid using ->setFrom() in every message, since it'll be a future headache. I could use a constant for that, but I was looking for a more elegant solution.

$message = Swift_Message::newInstance()
                ->setSubject('subject')
                ->setFrom(array('[email protected]' => 'Sender'))
                ->setTo(array('[email protected]'))
                ->setBody('Message');

Thanks!

like image 544
Stingus Avatar asked Sep 02 '26 10:09

Stingus


1 Answers

You can't.

As far as I know, you can't omit this parameter.

A From: address is required and is set with the setFrom() method of the message. From: addresses specify who actually wrote the email, and usually who sent it.

This is maybe the best solution:

->setFrom(MyClass::FROM_EMAIL);

Once thing you can try, is to create an instance once in your application, and clone it when you want to send a new mail without re-defining the from part:

// somewhere early in your app
$message = Swift_Message::newInstance()
            ->setFrom(array('[email protected]' => 'Sender'));

And then, somewhere else:

$newMessage = clone $message;
$newMessage
    ->setSubject('subject')
    ->setTo(array('[email protected]'))
    ->setBody('Message')
    ->send();
like image 118
j0k Avatar answered Sep 04 '26 00:09

j0k