Question

I have a config array with some smtp settings. I am looking for a way to extend Swiftmailer to auto fill in these details.

I cannot find anything about extending swiftmailer. I did found some information about plugins, but these existing plugins of swiftmailer won't tell me anything.

// automatic use smtp.domain.com, username, password ??
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance('Test')
  ->setFrom(array('mail@domain.com' => 'from user'))
  ->setTo(array('mail@domain.com' => 'from user'))
  ->setBody('Body')
  ;

$result = $mailer->send($message);

Can anyone tell me how to do this?

Was it helpful?

Solution

I don't see why you should extend SwiftMailer for that requirement. It's much easier to create a class that handles the preparation e.g.

class SwiftMailerPreparator {
    private $mailer;

    public __construct(Swift_Mailer $mailer) {
        $this->mailer = $mailer;
    }

    public function prepare(array $settings) {
        // do your thing here
    }
}

Also since SwiftMailer is opensource you can just look at the code and see how it works.

OTHER TIPS

You could wrap everything into a service class like this:

class MyMailerAssistant
{
    /**
     * Service method to fastly send a message
     * @param $subject
     * @param $body
     */
    public static function sendMessage($subject, $body)
    {
        // automatic use smtp.domain.com, username, password ??
        $transport = Swift_MailTransport::newInstance();
        $mailer = Swift_Mailer::newInstance($transport);

        $message = Swift_Message::newInstance('Test')
                ->setSubject($subject)
                ->setFrom(array('mail@domain.com' => 'from user'))
                ->setTo(array('mail@domain.com' => 'from user'))
                ->setBody($body);

        $result = $mailer->send($message);
    }
}

and calling it simply in this way:

MyMailerAssistant::sendMessage('Hello', 'This is the email content');

Anyway I strongly discourage you inserting your configuration into a method, I would always load it from a modular external configuration file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top