Yii2-symfonymailer - Yii 2 Symfony mailer extension.

Overview

Yii Mailer Library - Symfony Mailer Extension


This extension provides a Symfony Mailer mail solution for Yii framework 2.0.

For license information check the LICENSE-file.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-symfonymailer

or add

"yiisoft/yii2-symfonymailer": "~2.0.0"

to the require section of your composer.json.

Note: Version 2.0 of this extension uses Symfonymailer, which requires PHP 8.

Usage

To use this extension, simply add the following code in your application configuration:

return [
    //....
    'components' => [
        'mailer' => [
            'class' => \yii\symfonymailer\Mailer::class,            
            'transport' => [
                'scheme' => '',
                'host' => '',
                'username' => '',
                'password' => '',
                'port' => 465,
                'options' => ['ssl' => true],
            ],
        ],
    ],
];

or

return [
    //....
    'components' => [
        'mailer' => [
            'class' => \yii\symfonymailer\Mailer::class,            
            'transport' => [
                'dsn' => 'smtp://user:[email protected]:25',
            ],
        ],
    ],
];

You can then send an email as follows:

Yii::$app->mailer->compose('contact/html')
     ->setFrom('[email protected]')
     ->setTo($form->email)
     ->setSubject($form->subject)
     ->send();
Comments
  • Code cleanup

    Code cleanup

    This is a big cleanup PR that fixes a plethora of smaller issues and rewrites other parts.

    | Q | A | ------------- | --- | Breaks BC? | ✔️ big time

    status:code review 
    opened by SamMousa 50
  • Can a default sendFrom address be called by updating the configuration file?

    Can a default sendFrom address be called by updating the configuration file?

    At the moment whenever we create a message we have to call setFrom() to set the send from address.

    I understand the need for this but could we not have a fallback email - set in the mailer component - to use if setFrom() is not set.

    For example a noreply@somedomain email configured at application level

    opened by developedsoftware 11
  • Working within queues support

    Working within queues support

    What steps will reproduce the problem?

    Trying to use yii2-symfonymailer in queue job.

    What's expected?

    Everything is working.

    What do you get instead?

    BadMethodCallException : Cannot serialize Symfony\Component\Mailer\Transport\Smtp\SmtpTransport at \vendor\symfony\mailer\Transport\Smtp\SmtpTransport.php:356

    Additional info

    At the current moment this extension can't be used in queue jobs (with https://github.com/yarcode/yii2-queue-mailer as example), because that jobs are serialized, but initialized Transport object prevents serialization. Deprecated yii2-swiftmailer extension has no such problem. The reason is that, the Transport object is initializing directly in setter, if it passed as array configuration. It seems, that this behavior can be changed easily. This require just to remove Transport object initialization from setTransport() (it all be done in getTransport() anyway). I prepared pull request, that demonstrates my idea, and this code perfectly works within queues. I did not remove the Transport initialization code from setter, in order to not to break current tests, but added a class variable to control the described behavior.

    type:enhancement 
    opened by pozitronik 10
  • Mailer->sendMessage Exception Bug

    Mailer->sendMessage Exception Bug

    What steps will reproduce the problem?

    [ ] In mailer config transport is set up with a "dummy" host. This will cause a TransportException. [ ] $message is set to a proper yii\symfonymailer\Message [ ] $mailer is set to the yii\symfonymailer\Mailer

    	try {
    		$result = $mailer->send($message);
    	} catch (\Throwable $e) {
    		static::$errors[] = $e->getMessage();
    	} catch (\Exception $e) {
    		static::$errors[] = $e->getMessage();
    	}
    

    What's expected?

    \Throwable should catch the TransportException.

    What do you get instead?

    No Throwable or Exception. $result = false

    Additional info

    /**
     * {@inheritDoc}
     *
     * @throws TransportExceptionInterface If sending failed.
     */
    protected function sendMessage($message): bool
    {
        if (!($message instanceof Message)) {
            throw new RuntimeException(sprintf(
                'The message must be an instance of "%s". The "%s" instance is received.',
                Message::class,
                get_class($message),
            ));
        }
    
        $message = $message->getSymfonyEmail();
        if ($this->encryptor !== null) {
            $message = $this->encryptor->encrypt($message);
        }
    
        if ($this->signer !== null) {
            $message = $this->signer instanceof DkimSigner
                ? $this->signer->sign($message, $this->dkimSignerOptions)
                : $this->signer->sign($message)
            ;
        }
        try {
            $this->getSymfonyMailer()->send($message);
      /*****  This catch will catch the TransportException  and then return false *****/
        } catch (\Exception $exception) {
            Yii::getLogger()->log($exception->getMessage(), \yii\log\Logger::LEVEL_ERROR, __METHOD__);
            return false;
        }
        return true;
    }
    

    | Q | A | ----------------------- | --- | Yii version | 2.0.45 | Yii SymfonyMailer version | 2.0.3 | SymfonyMailer version | v6.0.11 | PHP version | 8.1.9 | Operating system | Linux Mint 20.3 with Kernel Linux 5.15.0-46-generic

    opened by nd4c 8
  • Failed to instantiate component or class

    Failed to instantiate component or class "yii\symfonymailer\Mailer::class".

    Hi, If I add :: class show the error: Failed to instantiate component or class "yii\symfonymailer\Mailer::class".

    but if I not use ::class work well 'class' => 'yii\symfonymailer\Mailer',

    I belive that is need change in Readme.

    By the way, I change from 'yii\swiftmailer\Mailer' to 'yii\symfonymailer\Mailer' and for the moment all work well, this is my changes: With Swiftmailer;

    	'mailer' => [
                'class' => 'yii\swiftmailer\Mailer',
                'useFileTransport' => false,
                'transport' =>
                    [
                        'class' => 'Swift_SmtpTransport',
                        'host' => 'email-smtp.eu-west-1.amazonaws.com',
                        'username' => '****',
                        'password' => '****',
                        'port' => '587',
                        'encryption' => 'tls',
                    ]
            ],
    

    and with Symfony:

    'mailer' => [
                'class' => 'yii\symfonymailer\Mailer',
                'transport' =>
                    [
                        'dsn' => 'ses+smtp://USERNAME:[email protected]',
                    ]
            ],		
    
    status:need more info 
    opened by metola 5
  • Implementation try catch for debugging

    Implementation try catch for debugging

    What steps will reproduce the problem?

    What's expected?

    What do you get instead?

    Additional info

    | Q | A | ----------------------- | --- | Yii version | 2.0.45 | Yii SymfonyMailer version | 2.0.3 | SymfonyMailer version | >= 5.4.0 | PHP version | 7.4.20 | Operating system | Ubuntu 20.04

    How to catch error when sending email. My problem is, when in localhost is success, but in production is failed.

     public function kirimEmailPengajuanLoginAccount($userYangMengajukanId): bool
        {
            $settings = Yii::$app->settings;
            $emailTo = $settings->get('Email.pengaktifanUserAccount');
            $senderEmail = $settings->get('Email.senderEmail');
            $senderName = $settings->get('Email.senderName');
    
            $userYangMengajukan = User::findOne($userYangMengajukanId);
    
            $mailer = Yii::$app->mailer->compose('pengajuan_user_account', [
                'model' => $this,
                'userYangMengajukan' => $userYangMengajukan
            ])
                ->setTo($emailTo)
                ->setFrom([$senderEmail => $senderName])
                ->setReplyTo($emailTo)
                ->setSubject('Permohonan pengaktifan user account atas nama: ' . $this->nama);
    
            try {
                return $mailer->send();
            } catch (TransportExceptionInterface $e) {
                $this->addError('nama', $e->getDebug());
            }
    
            return false;
    
    
        }
    

    I got empty array in 'nama' attribute. Thanks for the suggestion

    question 
    opened by ahmadfadlydziljalal 4
  • No Email sent, no error, send() returns true

    No Email sent, no error, send() returns true

    What steps will reproduce the problem?

    config/web.php :

    $config = [
       ...
       'components' => [
          ...
          'mailer' => require(__DIR__ . '/mailer.php'),
          ...
       ],
       ...
    ]
    

    config/mailer.php :

    <?php
    
    $params = require(__DIR__ . '/params.php');
    
    return [
        'class' => \yii\symfonymailer\Mailer::class,
        'transport' => [
            'host' => 'smtp.gmail.com',
            'username' => $params['adminEmail'],
            'password' => '********',
            'port' => '465',
            'options' => ['ssl' => true],
        ],
        'messageConfig' => [
            'from' => $params['adminEmail'], //'bcc' => '<bbc email>',
        ],
    ];
    

    Method to send email:

    public function sendEmail() {
        $mailer = Yii::$app->mailer;
        $oldViewPath = $mailer->viewPath;
        $mailer->viewPath = "@app/mail";
        $isSent = $mailer->compose('testEmail')
                        ->setTo($this->email)
                        ->setSubject(Yii::t('dev', 'Email Test Send'))
                        ->send();
        
        $mailer->viewPath = $oldViewPath;
        return $isSent;
    }
    
    

    $this->email comes from a form

    What's expected?

    Email will be send. ->send() method returns true.

    What do you get instead?

    Email won't be send. -> send() method returns true.

    Additional info

    | Q | A | ----------------------- | --- | Yii version | 2.0.44 | Yii SymfonyMailer version | 2.0.0 | SymfonyMailer version | 6.0.2 | PHP version | 8.0.13 | Operating system | Manjaro

    I switched from yiisoft/yii2-swiftmailer": "~2.1.2 . Sending email with swiftmailer worked. Do I miss additional configuration? As stated from my config I'm trying to send from/over gmail account.

    opened by 1Luc1 4
  • Messy implementation of private $_transport

    Messy implementation of private $_transport

    What steps will reproduce the problem?

    Inspect the code; it is functional but the implementation is messy.

    First of all note that the variable is private:

        /**
         * @var TransportInterface|array Symfony transport instance or its array configuration.
         */
        private $_transport = [];
    

    This means the only way it ever gets set is via setTransport:

    /**
         * @param array|TransportInterface $transport
         * @throws InvalidConfigException on invalid argument.
         */
        public function setTransport($transport): void
        {
            if (!is_array($transport) && !$transport instanceof TransportInterface) {
                throw new InvalidConfigException('"' . get_class($this) . '::transport" should be either object or array, "' . gettype($transport) . '" given.');
            }
            if ($transport instanceof TransportInterface) {
                $this->_transport = $transport;
            } elseif (is_array($transport)) {
                $this->_transport = $this->createTransport($transport);
            }
    
            $this->symfonyMailer = null;
        }
    

    Looking at this code we can actually conclude that $this->_transport will never be an array. In php 8.1 we could write it like this:

    private TransportInterface $_transport;
    
    public function setTransport(TransportInterface|array $transport): void
    {
        $this->_transport = $transport instanceof TransportInterface ? $transport : $this->createTransport($transport);
    }
    

    Given that createTransport() always returns a created transport, or throws an exception we can be 100% sure that after a call to setTransport() we get either an exception or the transport was successfully created and set.

    This means we can, and should remove getTransport() alternatively, at least we should simplify it:

    public function getTransport(): TransportInterface
    {
        return $this->_transport;
    }
    

    Last but not least, Yii uses a pattern where init() is called after configuration which means we should use it to test for correct configuration. This will throw an error closer to the error (on / after instantiation instead of on use)

    public function init() {
        if (!isset($this->_transport)) {
            throw new InvalidConfigException("No transport configured");
        }
    }
    
    opened by SamMousa 3
  • Add option to create transport from Dsn object

    Add option to create transport from Dsn object

    | Q | A | ------------- | --- | Is bugfix? | ❌ | New feature? | ✔️ | Breaks BC? | ❌ | Fixed issues |

    Adds option to create transport from symfony Dsn object

    opened by Swanty 2
  • No exception is thrown to caller when sending mail fails

    No exception is thrown to caller when sending mail fails

    Ref line: https://github.com/yiisoft/yii2-symfonymailer/blob/716243e9e8250c71e30280e287dbcd7ff9f2507f/src/Mailer.php#L213

    This catch does not re-throw the exception and instead does its own logging and returns false. There should be a way to suppress this behavior and let the exception be caught by the caller.

    I have my own logging setup and now I have no way of logging the actual exception the way I want to after upgrading from the old swiftwmailer component.

    Additional info

    | Q | A | ----------------------- | --- | Yii version | | Yii SymfonyMailer version | | SymfonyMailer version | | PHP version | | Operating system |

    opened by RickKukiela 2
  • Improve documentation defaults when swapping from yii2-swiftmailer

    Improve documentation defaults when swapping from yii2-swiftmailer

    When swapping from deprecated https://github.com/yiisoft/yii2-swiftmailer to this extension, two things needed to be changed to keep everything working as before:

    1. Swiftmailer default transport was the SendmailTransport, while this extension will default to a NullTransport (sends no mail). You can use the swiftmailer default by defining in application config:
    'mailer' => [
        'class' => yii\symfonymailer\Mailer::class,
        'transport' => [
            'dsn' => 'sendmail://default',
        ],
    ],
    
    1. Codeceptions TestMailer specifies swiftmailer\Message as a default class in https://github.com/Codeception/module-yii2/blob/master/src/Codeception/Lib/Connector/Yii2/TestMailer.php#L8. This can also be changed by defining in test config:
    'mailer' => [
        'class' => yii\symfonymailer\Mailer::class,
        'messageClass' => \yii\symfonymailer\Message::class,
    ],
    

    Not sure if any of these should be a code change, but I thought it was useful to report and perhaps have it documented in the README.

    type:docs 
    opened by marcovtwout 2
  • Expose symfony mailer events

    Expose symfony mailer events

    What steps will reproduce the problem?

    Currently there is no way to hook on the Mailer Events

    What's expected?

    I expect to be able to set a Yii event for this, and be able to interact with Symfony Mailer prior to message sending, to inline CSS for example.

    What do you get instead?

    Nothing, and that's blocking me from switching from Swift Mailer.

    Let's implement this after https://github.com/yiisoft/yii2-symfonymailer/pull/27 gets finally merged.

    opened by machour 0
  • Document TransportFactoryInterface: Adding Socket Timeout Option to Mailer

    Document TransportFactoryInterface: Adding Socket Timeout Option to Mailer

    What steps will reproduce the problem?

    Migrate from Swift Mailer to Symfony Mailer

    What's expected?

    SwiftMailer has a transport->timeout property that can be set in the config. Defaults to 30.

    What do you get instead?

    The Symfony Mailer does not have an exposed way to set the timeout for the EsmtpTransport. (There is a value and a setter Method, but there is no way to call it since the transport is private...)

    Additional info

    If the Symfony Transport timeout property is not set it will default to the php.ini setting, 'default_socket_timeout' which default to 60.

    We can wrap the mailer->send() call, but it would be nice to be able to config the Mailer's timeout value.

    We cannot add a new property to the transport itself, but we can add one to the yii Mailer class.

    Possible solution:

    class Mailer extends BaseMailer
     {
        /**
         * @var int transport_timeout defaults to 0 since this would only apply to smtp/smtps transports.
         */
        public $transport_timeout = 0;
        ...
        /**
         * {@inheritDoc}
         *
         * @throws TransportExceptionInterface If sending failed.
         */
        protected function sendMessage($message): bool
        {
            ...
            try {
                if (!empty($this->transport_timeout) && (int) $this->transport_timeout > 0) {
                    $default_socket_timeout = ini_set('default_socket_timeout', (int) $this->transport_timeout);
                }
                $this->getSymfonyMailer()->send($message);
            } catch (\Exception $exception) {
                Yii::getLogger()->log($exception->getMessage(), \yii\log\Logger::LEVEL_ERROR, __METHOD__);
                // need to re-throw the exception so that caller can extract transport errors
                throw($exception);
            } finally {
                if (!empty($default_socket_timeout) && (int) $default_socket_timeout > 0) {
                    ini_set('default_socket_timeout', (int) $default_socket_timeout);
                }
            }
            return true;
        }
    }
    

    | Q | A | ----------------------- | --- | Yii version | 2.0.45 | Yii SymfonyMailer version | 2.0.3 | SymfonyMailer version | v6.0.11 | PHP version | 8.1.9 | Operating system | Linux Mint 20.3 with Kernel Linux 5.15.0-46-generic

    type:docs 
    opened by nd4c 5
  • Send email return TRUE but no mail sent

    Send email return TRUE but no mail sent

    What steps will reproduce the problem?

    What's expected?

    What do you get instead?

    Additional info

    | Q | A | ----------------------- | --- | Yii version | 2.0.42.1 | Yii SymfonyMailer version | 2.0.3 | SymfonyMailer version | ^5.4 | PHP version | 7.4.29 | Operating system | ubuntu 18.04

    If i change transport settings, always ->send() return true, also if i set xxx.xxx.xx. as host

    status:need more info type:bug 
    opened by FedericoBenedetti1976 14
  • Logger proxy should be in separate repository

    Logger proxy should be in separate repository

    This library contains a proxy allowing us to provide a PSR LoggerInterface and route its output to Yii's logger. This should be in the core or a separate library, it is a useful tool with and without symfony mailer.

    I'm happy to create a PR if you can create a new repo, or to create a PR for the Yii2 core, but I think that's feature frozen. Of course I could make this in my own repository as well but it would be better if it lives in yiisoft.

    status:ready for adoption 
    opened by SamMousa 10
Releases(3.0.0)
Owner
Yii Software
Yii Framework and packages
Yii Software
Simple RBAC Manager for Yii2 (minify of yii2-admin)

Yii2 Mimin Simple RBAC Manager fo Yii 2.0. Minify of yii2-admin extension with awesome features Attention Before you install and use this extension, t

Hafid Mukhlasin 52 Sep 22, 2022
An enhanced Yii 2 widget encapsulating the HTML 5 range input (sub repo split from yii2-widgets)

yii2-widget-rangeinput The RangeInput widget is a customized range slider control widget based on HTML5 range input. The widget enhances the default H

Kartik Visweswaran 19 Mar 12, 2022
A easy way to install your basic yii projetc, we have encrypt database password in phpfile, my class with alot funtions to help you encrypt and decrypt and our swoole server install just run ./yii swoole/start and be happy!

Yii 2 Basic Project Template with swoole and Modules Yii 2 Basic Project Template is a skeleton Yii 2 application best for rapidly creating small proj

null 3 Apr 11, 2022
Yii2 extension for format inputs based on AutoNumeric.js

Yii2 extension for format inputs based on AutoNumeric.js

extead 2 Oct 7, 2019
Yii 2 Bootstrap 5 Extension

Twitter Bootstrap 5 Extension for Yii 2 This is the Twitter Bootstrap extension for Yii framework 2.0. It encapsulates Bootstrap 5 components and plug

Yii Software 48 Dec 14, 2022
This extension provides a view renderer for Pug templates for Yii framework 2.0 applications.

This extension provides a view renderer for Pug templates for Yii framework 2.0 applications.

Revin Roman 9 Jun 17, 2022
Extension for creating and sending emails for the Yii PHP framework.

yii-emailer Extension for creating and sending emails for the Yii PHP framework. Usage Migrate the email_message database table by this command: yiic

Digia 12 Mar 30, 2022
This extension provides Flysystem integration for the Yii framework

This extension provides Flysystem integration for the Yii framework. Flysystem is a filesystem abstraction which allows you to easily swap out a local filesystem for a remote one.

Alexander Kochetov 276 Dec 9, 2022
Tarantool connector for yii2 framework. Allow to use activerecord, schemas, widgets and more.

Tarantool connector for yii2 framework Tarantool connector for yii2 framework. Allow to use framework abstractions such as ActiveRecord, Schema, Table

Andrey 11 Nov 21, 2021
Web Push Notifications brought to Yii2

Web Push Notifications for Yii 2 An extension for implementing Web Push Notifications on your website in a breeze. Documentation is at docs/README.md

Mehdi Achour 12 May 19, 2022
yii2-app-advanced with Twitter Bootstrap 5

Yii 2 Advanced Project Template is a skeleton Yii 2 application best for developing complex Web applications with multiple tiers.

Nedarta 1 Nov 5, 2021
Prometheus exporter for Yii2

yii2-prometheus Prometheus Extension for Yii 2 This extension provides a Prometheus exporter component for Yii framework 2.0 applications. This extens

Mehdi Achour 3 Oct 27, 2021
Yii2 console application used to write our processors of methods to responsible to client calling.

Microservice Application Skeleton Yii2 console application used to write our processors of methods to responsible to client calling. This application

Jafaripur 0 Mar 10, 2022
Date/Time Picker widget for Yii2 framework Based on Eonasdan's Bootstrap 3 Date/Time Picker

Yii2 Date/Time Picker Widget Date/Time Picker widget for Yii2 framework Based on Eonasdan's Bootstrap 3 Date/Time Picker Demo Since this is a part of

Yevhen Terentiev 8 Mar 14, 2022
Yii2 SwitchInput widget turns checkboxes and radio buttons into toggle switchinputes

Yii2 SwitchInput widget turns checkboxes and radio buttons into toggle switchinputes

Kartik Visweswaran 38 Sep 21, 2022
An enhanced FileInput widget for Bootstrap 4.x/3.x with file preview, multiple selection, and more features (sub repo split from yii2-widgets)

yii2-widget-fileinput The FileInput widget is a customized file input widget based on Krajee's Bootstrap FileInput JQuery Plugin. The widget enhances

Kartik Visweswaran 227 Nov 6, 2022
A Yii2 module for embedding social plugins and widgets.

yii2-social Module that enables access to social plugins for Yii Framework 2.0. It includes support for embedding plugins from the following networks

Kartik Visweswaran 92 May 29, 2022
Pug Yii2 adapter

Yii 2 Pug (ex Jade) extension This extension provides a view renderer for Pug templates for Yii framework 2.0 applications. Support GutHub issues Inst

Pug PHP 8 Jun 17, 2022
This is Yii2 utilities

YII2-UTILITY This is Yii2 utilities. Requirements PHP >= 7.4 Curl extension for PHP7 must be enabled. Download Using Composer From your project direct

null 0 Jun 30, 2022