3

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!

2 Answers 2

4

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(); 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I was afraid there's no such option when I looked into Swift_Mime_SimpleMessage. I'll try the clone approach for now.
Why do you need to clone? I think you can just use the same instance and change the subject, body, ...
I clone the original $message to avoid bad behavior if I have to send different mail. The case here, is I define $message somewhere in my app and then re-use it every where. (I agree it's not the best solution, but I guess that was my idea when I wrote it)
1

If you use a SwiftMailer ≥ 4 and are familiar with Composer, you can use a Defaults Plugin for SwiftMailer to achieve this.

First install the package:

composer require finesse/swiftmailer-defaults-plugin 

Second set up a Swift_Mailer instance:

$mailer = new Swift_Mailer(/* your transport here */); $mailer->registerPlugin(new Finesse\SwiftMailerDefaultsPlugin\SwiftMailerDefaultsPlugin([ 'from' => ['[email protected]' => 'Sender'] ])); 

And then send emails without specifying the from address:

$mailer->send((new Swift_Message()) ->setSubject('subject') ->setTo(array('[email protected]')) ->setBody('Message')); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.