Using swiftmailer with connection attributes from database and sending attachements

Hi guys,

official documentation of yii2 recommend implementing swiftmailer for sending Emails like this in config file





'components' => [

    ...

    'mailer' => [

        'class' => 'yii\swiftmailer\Mailer',


                'viewPath' => '@common/mail',

                'useFileTransport' => false,        

		'transport' => [

            	'class' => 'Swift_SmtpTransport',

                'host' => 'smtp.gmail.com',

            	'username' => 'username',

                'password' => 'password',

                'port' => '587',

                'encryption' => 'tls',

                ],

    	],

    ...

],



This works, but I get connection data from database.

Ever an anon, user should be able to define connection parameters by a DropDownbox of at least three different Mailserver.

Is it possible using Swiftmailer in order to get my intention realized,or should I use an extension?

If it is possible using Swiftmailer, how should I define connection parameters.

I cant use example above,any more!

Sure it is ;)

I am using https://github.com/twisted1919/yii2-options to store app params in database and https://github.com/twisted1919/yii2-shortcut-functions to access the components via shortcuts, and here’s how such implementation looks like:




<?php


namespace common\yii\swiftmailer;


use yii\swiftmailer\Mailer as BaseMailer;


/**

 * Class Mailer

 * @package common\yii\swiftmailer

 */

class Mailer extends BaseMailer

{

    /**

     * @inheritdoc

     */

    public function init()

    {

        /* call parent implementation */

        parent::init();

        

        /* see if we need to set our transport */

        $hostname   = options()->get('app.settings.email.hostname');

        $username   = options()->get('app.settings.email.username');

        $password   = options()->get('app.settings.email.password');

        $port       = options()->get('app.settings.email.port', 25);

        $encryption = options()->get('app.settings.email.encryption', '');

        $timeout    = options()->get('app.settings.email.timeout', 30);

        

        if ($hostname && $username && $password) {

            $this->setTransport([

                'class'      => 'Swift_SmtpTransport',

                'host'       => $hostname,

                'username'   => $username,

                'password'   => $password,

                'port'       => $port,

                'encryption' => $encryption,

                'timeout'    => $timeout,

            ]);

        }

    }

}



And in the config :




'mailer' => [

            'class' => 'common\yii\swiftmailer\Mailer',

            'viewPath' => '@common/mail',

 ],



of course, the above is just an example, to give you a starting point.

you don’t even need to mess with the mailer class you can call setTransport direct on the component registered with yii like so




public function actionContact()

{


// $config = Config::find()->getMailerConfig();


$mailer = Yii::$app->mailer->setTransport([

    'class' => 'Swift_SmtpTransport',

    'host' => 'localhost', // or $config['host']

    'username' => 'username', // or $config['username']

    'password' => 'password', // or $config['password']

    'port' => '587', // or $config['port']

    'encryption' => 'tls', // or $config['encryption']

]);


// composer you mail

$mailer->compose('contact/html', ['contactForm' => $form])

    ->setFrom('from@domain.com')

    ->setTo($form->email)

    ->setSubject($form->subject)

    ->send();


// ...


}

Oh, thank you very much for this. Another question I have is sending attachements. By now, I forbid uploading more than three files once and code like this. As U can see, it’s not a comfortable way of programming. So, is it possible sending attachements as array instead of each element of array using several conditions??





            if ($model->gesendet != 0) {

                if ($anhangszaehler == 0) {

                    Yii::$app->mailer->compose()->setFrom($model_eingang->mail_adresse_absender)

                            ->setTo($model->mail_antwortadresse)

                            ->setSubject($model->betreff)

                            ->setTextBody($model->bodytext)

                            ->send();

                } else if ($anhangszaehler == 1) {


                    Yii::$app->mailer->compose()->setFrom($model_eingang->mail_adresse_absender)

                            ->setTo($model->mail_antwortadresse)

                            ->setSubject($model->betreff)

                            ->setTextBody($model->bodytext)

                            ->attach($folder_write . $anhang[0])

                            ->send();

                } else if ($anhangszaehler == 2) {


                    Yii::$app->mailer->compose()->setFrom($model_eingang->mail_adresse_absender)

                            ->setTo($model->mail_antwortadresse)

                            ->setSubject($model->betreff)

                            ->setTextBody($model->bodytext)

                            ->attach($folder_write . $anhang[0])

                            ->attach($folder_write . $anhang[1])

                            ->send();

                } else if ($anhangszaehler == 3) {


                    Yii::$app->mailer->compose()->setFrom($model_eingang->mail_adresse_absender)

                            ->setTo($model->mail_antwortadresse)

                            ->setSubject($model->betreff)

                            ->setTextBody($model->bodytext)

                            ->attach($folder_write . $anhang[0])

                            ->attach($folder_write . $anhang[1])

                            ->attach($folder_write . $anhang[2])

                            ->send();

                }

                $session = new Session();

                $session->addFlash("info", "Die Mail wurde versandt.Bitte überprüfen sie ihren Maileingang");

                return $this->redirect(['index']);

            }



My intentions is sending unlimited amount of attachements without using conditions!

you can break out of the method chain an loop over the attachments add each one to the email you composing here is an example


<?php


$attachments = [1, 2, 3, 4, 5];


$email = Yii::$app->mailer->compose()->setFrom($model_eingang->mail_adresse_absender)

    ->setTo($model->mail_antwortadresse)

    ->setSubject($model->betreff)

    ->setTextBody($model->bodytext);


foreach ($attachments as $attachment) {

    $email->attach($attachment);

}


$email->send();

Great. A very nice solution. In earlier days, samdark was person, who gave me brilliant answers like this. Now,it’s yours!

Thx a lot of this. I gave U reputation points for ur efforts

This thread can be solved as succesfully finished