GithubHelp home page GithubHelp logo

yiisoft / yii2-swiftmailer Goto Github PK

View Code? Open in Web Editor NEW
117.0 27.0 72.0 9.69 MB

Yii 2 swiftmailer extension.

Home Page: http://www.yiiframework.com

License: BSD 3-Clause "New" or "Revised" License

PHP 98.44% Makefile 1.56%
yii yii2 mail email mailer swiftmailer hacktoberfest

yii2-swiftmailer's Introduction

SwiftMailer Extension for Yii 2


This extension provides a SwiftMailer 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-swiftmailer

or add

"yiisoft/yii2-swiftmailer": "~2.1.0"

to the require section of your composer.json.

Note: Version 2.1 of this extensions uses Swiftmailer 6, which requires PHP 7. If you are using PHP 5, you have to use version 2.0 of this extension, which uses Swiftmailer 5, which is compatible with PHP 5.4 and higher. Use the following version constraint in that case:

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

Usage

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

return [
    //....
    'components' => [
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
        ],
    ],
];

You can then send an email as follows:

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

For further instructions refer to the related section in the Yii Definitive Guide.

yii2-swiftmailer's People

Contributors

andersonamuller avatar bwoester avatar cebe avatar creocoder avatar crtlib avatar egorpromo avatar ext4yii avatar gevik avatar gonimar avatar kartik-v avatar klimov-paul avatar lancecoder avatar larryullman avatar lucianobaraglia avatar mdomba avatar mohorev avatar nineinchnick avatar pmoust avatar qiangxue avatar qiansen1386 avatar ragazzo avatar resurtm avatar rinatio avatar samdark avatar schmunk42 avatar sensorario avatar slavcodev avatar suralc avatar tarasio avatar tonydspaniard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-swiftmailer's Issues

SwiftMailer 6.0+ support

A breaking change in 6.0+ is that they removed the newInstance() static methods in all of the classes. This library uses that function in Mailer.php function createSwiftMailer(). Changing it to return new \Swift_Mailer($this->getTransport()); shouldn't break old versions of SwiftMailer, and would allow support for 6.0+

Some context: I need SwiftMailer dev 6.0+ in my project because it implements stream context options, see here: swiftmailer/swiftmailer@d791ebe

I'm not sure if this is the only change needed, I haven't tried it yet. There may be other breaking changes in 6.0 that I haven't noticed, see here: https://github.com/swiftmailer/swiftmailer/blob/master/CHANGES

Thanks

yii\swiftmailer\Mailer::setTransport has no effect after sending of first message

What steps will reproduce the problem?

// you have to setup these variables
$host = '';
$username = '';
$password = '';
$port = '';
$recipient = '';

$transport = [
    'class' => 'Swift_SmtpTransport',
    'encryption' => 'tls',
    'host' => $host,
    'username' => $username,
    'password' => $password,
    'port' => $port,
];

$message = (new \yii\swiftmailer\Message())
    ->setFrom('[email protected]')
    ->setTo($recipient)
    ->setSubject('Test')
    ->setTextBody('Hello world!');

Yii::$app->mailer->setTransport($transport);
Yii::$app->mailer->send($message);

$transport['password'] = null;
// wrong password, we expect Swift_TransportException

Yii::$app->mailer->setTransport($transport);
Yii::$app->mailer->send($message);

What's expected?

Message successfully sent for the first time, the second time - Swift_TransportException.

What do you get instead?

Message sent successfully twice.

Additional info

Q A
Yii version 2.0.15.1
Yii SwiftMailer version 2.1.0
SwiftMailer version 5.4.9
PHP version 5.5.9
Operating system Ubuntu 14.04

setTransport has no effect on further emails sending because Swift_Mailer object is cached after first call of getSwiftMailer

public function getSwiftMailer()
{
if (!is_object($this->_swiftMailer)) {
$this->_swiftMailer = $this->createSwiftMailer();
}
return $this->_swiftMailer;
}

While it can be workarounded, I think current behavior is unexpected.

how get parameters from compose()?

how get parameters from compose()?

I try:

/controllers/SiteController

Yii::$app->mailer->compose('layouts/html.php', ['model' => 'trtrtrtrt',])
 ->setFrom('[email protected]')
 ->setTo('[email protected]')
 ->setSubject('TEST')
 ->send();

mail/layouts/html.php

<?php
use yii\helpers\Html;
use yii\mail\BaseMailer;


/* @var $this \yii\web\View view component instance */
/* @var $message \yii\mail\MessageInterface the message being composed */
/* @var $content string main view render result */
?>
<?php $this->beginPage() ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=<?= Yii::$app->charset ?>" />
    <title><?= Html::encode($this->title) ?>Тестовое письмо</title>
    <?php $this->head() ?>
</head>
<body>
    <?php $this->beginBody() ?>

    utyhtth
    <div style="background-color: green;">Приветик !</div>

<?= Html::encode($model) ?>

    <?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

i get error "Undefined variable: model" - <?= Html::encode($model) ?>

how get parameters from compose()?

Priority setup as High if value is empty

What steps will reproduce the problem?

set a priority with empty value $priority = ''

What's expected?

priority "Normal" or not setup

What do you get instead?

Priority is setup as High

Additional info

Fixed in my code by not setting up priority if value is empty

if (isset($posted['Tickets']['priority']) AND !empty($posted['Tickets']['priority'])){
if(method_exists($message,'setPriority')) {
$message->setPriority($posted['Tickets']['priority']);
}
}

Q A
Yii version
Yii SwiftMailer version "version": "2.0.7",
SwiftMailer version "version": "v5.4.8",
PHP version
Operating system Linux

Swift_Mime_HeaderFactory not found in Swift_Mime_SimpleHeaderFactory

What steps will reproduce the problem?

Not sure why the email is not sent. Not sure how to debug this. I checked all config files, advanced template, only one mailer component.

What's expected?

autoresponse email sent.

What do you get instead?

Error: [error][yii\base\ErrorException:1] exception 'yii\base\ErrorException' with message 'Interface 'Swift_Mime_HeaderFactory' not found' in /home/lansingc/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderFactory.php:17

Additional info

Q A
Yii version 2.0.8
PHP version 5.6.3
Operating system web host apache

Default mailer can't send email via gmail without from field

This issue has originally been reported by @Deele at yiisoft/yii2#16257.
Moved here by @samdark.


It seems that app can't send an email through smtp.gmail.com via Mailer: Cannot send message without a sender address and there is no way for me to configure message default "from" field value.

That results in various components (like logger) that use mailer to send mail with default config, to fail sending anything.

What steps will reproduce the problem?

Have mailer config to something like:

[
    'class' => 'yii\\swiftmailer\\Mailer'
    'viewPath' => '@common/mail'
    'transport' => [
        'class' => 'Swift_SmtpTransport'
        'host' => 'smtp.gmail.com'
        'username' => '[email protected]'
        'password' => 'user-password'
        'port' => '465'
        'encryption' => 'ssl'
    ]
]

What is the expected result?

E-mail is successfully sent.

What do you get instead?

E-mail is not sent. With enableSwiftMailerLogging enabled, you get something like (sensitive information redacted):

++ Starting Swift_SmtpTransport
<< 220 smtp.gmail.com ESMTP n5-v6sm5287511ljh.84 - gsmtp
>> EHLO [127.0.0.1]
<< 250-smtp.gmail.com at your service, [123.123.123.123]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
>> AUTH LOGIN
<< 334 abcdefghijklm
>> abcdefghijklmabcdefghijklm==
<< 334 noprstuvz
>> noprstuvznoprstuvz=
<< 235 2.7.0 Accepted
++ Swift_SmtpTransport started
!! Cannot send message without a sender address (code: 0)

Additional info

As gmail is one of the biggest e-mail servers, Yii should consider supporting it and I have couple solutions to this:

  1. From field should be equal to username by default
  2. We should have an option to provide default headers from mailer component config array
  3. We need to create custom Mailer component that replaces, for example, yii\swiftmailer\Mailer that explicitly sets setFrom() to be equal to that of a transport username during calling of compose() method
Q A
Yii version 2.0.15.1.

Swift mailer exception

I don't know exactly why, but I'm getting from time to time an exception from the swiftmailer extension. My php script is running in the background from the console (with the extension async-worker + redis) , and if he get some triggers the php script send mail to users. Most of time, it works, but at other time, I get the following exception :

PHP Warning 'yii\base\ErrorException' with message 'fwrite(): SSL: An established connection was aborted by the software in your host machine.'

in E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php:232

Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleError(2, 'fwrite(): SSL: ...', 'E:\ProgramData...', 232, Array)
#1 E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php(232): fwrite(Resource id #463, 'MAIL FROM:<MTE@...')
#2 E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\ByteStream\AbstractFilterableInputStream.php(171): Swift_Transport_StreamBuffer->_commit('MAIL FROM:<MTE@...')
#3 E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\ByteStream\AbstractFilterableInputStream.php(90): Swift_ByteStream_AbstractFilterableInputStream->_doWrite('MAIL FROM:<MTE@...')
#4 E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\AbstractSmtpTransport.php(276): Swift_ByteStream_AbstractFilterableInputStream->write('MAIL FROM:<MTE@...')
#5 E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\EsmtpTransport.php(243): Swift_Transport_AbstractSmtpTransport->executeCommand('MAIL FROM:<MTE@...', Array, Array)
#6 E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\EsmtpTransport.php(322): Swift_Transport_EsmtpTransport->executeCommand('MAIL FROM:<MTE@...', Array)
#7 E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\AbstractSmtpTransport.php(416): Swift_Transport_EsmtpTransport->_doMailFromCommand('MTE@meditech-ph...')
#8 E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\AbstractSmtpTransport.php(444): Swift_Transport_AbstractSmtpTransport->_doMailTransaction(Object(Swift_Message), 'MTE@meditech-ph...', Array, Array)
#9 E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\AbstractSmtpTransport.php(176): Swift_Transport_AbstractSmtpTransport->_sendTo(Object(Swift_Message), 'MTE@meditech-ph...', Array, Array)
#10 E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Mailer.php(85): Swift_Transport_AbstractSmtpTransport->send(Object(Swift_Message), Array)
#11 E:\ProgramData\htdocs\Yii2_KB\vendor\yiisoft\yii2-swiftmailer\Mailer.php(146): Swift_Mailer->send(Object(Swift_Message))
#12 E:\ProgramData\htdocs\Yii2_KB\vendor\yiisoft\yii2\mail\BaseMailer.php(260): yii\swiftmailer\Mailer->sendMessage(Object(yii\swiftmailer\Message))
#13 E:\ProgramData\htdocs\Yii2_KB\vendor\yiisoft\yii2\mail\BaseMessage.php(48): yii\mail\BaseMailer->send(Object(yii\swiftmailer\Message))
#14 E:\ProgramData\htdocs\Yii2_KB\controllers\BackgroundTask.php(141): yii\mail\BaseMessage->send()
#15 E:\ProgramData\htdocs\Yii2_KB\vendor\bazilio\yii2-async\commands\AsyncWorkerCommand.php(29): app\controllers\BackgroundTask->execute()
#16 [internal function]: bazilio\async\commands\AsyncWorkerCommand->actionDaemon('background')
#17 E:\ProgramData\htdocs\Yii2_KB\vendor\yiisoft\yii2\base\InlineAction.php(55): call_user_func_array(Array, Array)
#18 E:\ProgramData\htdocs\Yii2_KB\vendor\yiisoft\yii2\base\Controller.php(151): yii\base\InlineAction->runWithParams(Array)
#19 E:\ProgramData\htdocs\Yii2_KB\vendor\yiisoft\yii2\console\Controller.php(91): yii\base\Controller->runAction('daemon', Array)
#20 E:\ProgramData\htdocs\Yii2_KB\vendor\yiisoft\yii2\base\Module.php(455): yii\console\Controller->runAction('daemon', Array)
#21 E:\ProgramData\htdocs\Yii2_KB\vendor\yiisoft\yii2\console\Application.php(167): yii\base\Module->runAction('async-worker/da...', Array)
#22 E:\ProgramData\htdocs\Yii2_KB\vendor\yiisoft\yii2\console\Application.php(143): yii\console\Application->runAction('async-worker/da...', Array)
#23 E:\ProgramData\htdocs\Yii2_KB\vendor\yiisoft\yii2\base\Application.php(375): yii\console\Application->handleRequest(Object(yii\console\Request))
#24 E:\ProgramData\htdocs\Yii2_KB\yii(23): yii\base\Application->run()
#25 {main}

PHP Warning: fwrite(): SSL operation failed with code 1. OpenSSL Error messages:
error:1409F07F:SSL routines:SSL3_WRITE_PENDING:bad write retry in E:\ProgramData\htdocs\Yii2_KB\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php on line 232

System information :
Yii : 2.0.6
PHP Version 5.5.9
Apache Version Apache/2.4.10 (Win64) PHP/5.5.9
System : Windows NT SERVERMT 6.2 build 9200 (Windows Server 2012 Standard Edition) AMD64

Getting error messages or logging errors in the Swiftmailer extension.

Swiftmailer send function returns false. But there are no error messages in any logs or object properties I can find. Swiftmailer docs say there is a logger plugin to do logging for Swiftmailer but I have no idea how to configure it with Yii configs. How do I get any status info or error messages out of swiftmailer in Yii? The guide and the docs say nothing regarding the error handling at all.

Migrated from yiisoft/yii2#7524

How can i set display sender name ?

create a message

$msg = \Yii::$app->mailer->compose()
->setFrom()
->setSender("abc<[email protected]>"); // error :  no method named setSender

as #6 mentioned I use

$msg->getSwiftMessage()->getHeaders()->addTextHeader('Sender', 'abc<[email protected]>'); //reset() expects parameter 1 to be array, string given at  AbstractSmtpTransport.php line 347
$msg->getSwiftMessage()->getHeaders()->addTextHeader('Sender', ['[email protected]']); //error:Cannot send message without a sender address

how can i set the display sender name ? I suppose Message Class should have setSender method because http://swiftmailer.org/docs/messages.html provided.

Catched swift exception still messes up page output

What steps will reproduce the problem?

Render a faulty mail message that throws a Swift exception. For example attach a file that does not exist.

What's expected?

If you catch the exception, no extra output should be generated on the web page.

What do you get instead?

When rendering the mail body, PHP output buffering is used. When the exception is thrown, the buffer is obviously not cleared correctly. So the parts of the mail that rendered successful before the exception happened now appear in the web output, even when you catch the exception.

Additional info

Q A
Yii version 2.0.10
PHP version 7.0.8
Operating system Ubuntu 14.04 LTS

Does yii/swiftmailer able to add custom mail header?

I have use mandrill as my smtp server.
And they work great.
One feature that i want to use in my site is the mail tagging feature.
It will help me to read the report easier.

However, to tag mail, they need to add custom header while sending mail.

I was wondering, is yii/swiftmail is able to do this?

Please kindly advise.

Thank you.

swiftmailer breaks support for php5

This is not a direct problem, though swiftmailer broke php 5 support in 6.0.2 by using the $x = $y ?? 0; syntax
forcing the project to use version 6.0.1 fixes the problem.

Mail logger: Call to undefined method setplugin

Just enabled logs 'enableSwiftMailerLogging' => true and got the error below

PHP User Error – yii\base\ErrorException

Call to undefined method setplugin
1. in /vagrant/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php at line 291
282283284285286287288289290291292293294295296297298299300                $return = call_user_func_array(array($handler, $method), $args);
                // Allow fluid method calls
                if (is_null($return) && substr($method, 0, 3) == 'set') {
                    return $this;
                } else {
                    return $return;
                }
            }
        }
        trigger_error('Call to undefined method '.$method, E_USER_ERROR);
    }
 
    /** Get the params to initialize the buffer */
    protected function _getBufferParams()
    {
        return $this->_params;
    }
 
    /** Overridden to perform EHLO instead */
2. in /vagrant/vendor/yiisoft/yii2-swiftmailer/Mailer.php at line 239 – Swift_Transport_EsmtpTransport::__call('method' => '???', 'args' => '???')
233234235236237238239240241242243244245            foreach ($config as $name => $value) {
                if ($reflection->hasProperty($name) && $reflection->getProperty($name)->isPublic()) {
                    $object->$name = $value;
                } else {
                    $setter = 'set' . $name;
                    if ($reflection->hasMethod($setter) || $reflection->hasMethod('__call')) {
                        $object->$setter($value);
                    } else {
                        throw new InvalidConfigException('Setting unknown property: ' . $className . '::' . $name);
                    }
                }
            }
        }
3. in /vagrant/vendor/yiisoft/yii2-swiftmailer/Mailer.php at line 239 –
An Error occurred while handling another error:
ReflectionException: Method Swift_Transport_EsmtpTransport::setplugin() does not exist in /vagrant/vendor/yiisoft/yii2/web/ErrorHandler.php:199
Stack trace:
#0 /vagrant/vendor/yiisoft/yii2/web/ErrorHandler.php(199): ReflectionMethod->__construct('Swift_Transport...', 'setplugin')
#1 /vagrant/vendor/yiisoft/yii2/views/errorHandler/callStackItem.php(26): yii\web\ErrorHandler->addTypeLinks('Swift_Transport...')
#2 /vagrant/vendor/yiisoft/yii2/web/ErrorHandler.php(249): require('/vagrant/vendor...')
#3 /vagrant/vendor/yiisoft/yii2/web/ErrorHandler.php(307): yii\web\ErrorHandler->renderFile('@yii/views/erro...', Array)
#4 /vagrant/vendor/yiisoft/yii2/views/errorHandler/exception.php(385): yii\web\ErrorHandler->renderCallStackItem('/vagrant/vendor...', 238, 'Swift_Transport...', 'setplugin', Array, 3)
#5 /vagrant/vendor/yiisoft/yii2/web/ErrorHandler.php(249): require('/vagrant/vendor...')
#6 /vagrant/vendor/yiisoft/yii2/web/ErrorHandler.php(113): yii\web\ErrorHandler->renderFile('@yii/views/erro...', Array)
#7 /vagrant/vendor/yiisoft/yii2/base/ErrorHandler.php(111): yii\web\ErrorHandler->renderException(Object(yii\base\ErrorException))
#8 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\base\ErrorException))
#9 {main}
Previous exception:
yii\base\ErrorException: Call to undefined method setplugin in /vagrant/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php:291
Stack trace:
#0 /vagrant/vendor/yiisoft/yii2-swiftmailer/Mailer.php(239): Swift_Transport_EsmtpTransport->__call('???', '???')
#1 /vagrant/vendor/yiisoft/yii2-swiftmailer/Mailer.php(239): Swift_Transport_EsmtpTransport->setplugin('???')
#2 /vagrant/vendor/yiisoft/yii2-swiftmailer/Mailer.php(188): yii\swiftmailer\Mailer->createSwiftObject('???')
#3 /vagrant/vendor/yiisoft/yii2-swiftmailer/Mailer.php(129): yii\swiftmailer\Mailer->createTransport('???')
#4 /vagrant/vendor/yiisoft/yii2-swiftmailer/Mailer.php(155): yii\swiftmailer\Mailer->getTransport()
#5 /vagrant/vendor/yiisoft/yii2-swiftmailer/Mailer.php(105): yii\swiftmailer\Mailer->createSwiftMailer()
#6 /vagrant/vendor/yiisoft/yii2-swiftmailer/Mailer.php(146): yii\swiftmailer\Mailer->getSwiftMailer()
#7 /vagrant/vendor/yiisoft/yii2/mail/BaseMailer.php(262): yii\swiftmailer\Mailer->sendMessage('???')
#8 /vagrant/vendor/yiisoft/yii2/mail/BaseMessage.php(48): yii\mail\BaseMailer->send('???')
#9 /vagrant/src/components/Mailer.php(60): yii\mail\BaseMessage->send('???')
#10 /vagrant/src/modules/backend/controllers/DefaultController.php(77): app\components\Mailer->sendMailTo('???', '???', '???', '???')
#11 /vagrant/vendor/yiisoft/yii2/base/InlineAction.php(57): app\modules\backend\controllers\DefaultController->actionSendEmail()
#12 /vagrant/vendor/yiisoft/yii2/base/InlineAction.php(57): ::call_user_func_array:{/vagrant/vendor/yiisoft/yii2/base/InlineAction.php:57}('???', '???')
#13 /vagrant/vendor/yiisoft/yii2/base/Controller.php(156): yii\base\InlineAction->runWithParams('???')
#14 /vagrant/vendor/yiisoft/yii2/base/Module.php(523): yii\base\Controller->runAction('???', '???')
#15 /vagrant/vendor/yiisoft/yii2/web/Application.php(102): yii\base\Module->runAction('???', '???')
#16 /vagrant/vendor/yiisoft/yii2/base/Application.php(380): yii\web\Application->handleRequest('???')
#17 /vagrant/web/index.php(14): yii\base\Application->run()
#18 {main}
Q A
Yii version 2.0.11.1
PHP version 7.1.1
Operating system CentOs 7

Email Content

how can i set the content from yii2 DetailView widget

Don't validate email from 2 level domain

return [
'adminEmail' => '[email protected]',

cause:

Address in mailbox given [] does not comply with RFC 2822, 3.6.2.

  1. in /home/kira/lampstack-7.0.4-0/apache2/mafia-yii/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php at line 348

Not send mail with cyrillic domain

Not send mail with cyrillic domain
'test@тест.kz Address in mailbox given [test@тест.kz] does not comply with RFC 2822, 3.6.2.'

This bug fixed in swiftmailer swiftmailer/swiftmailer#1044
Plz, update composer.json

Q A
Yii version 2.0.15.1
Yii SwiftMailer version 2.0.7
SwiftMailer version 5.4.9
PHP version 7.2.5
Operating system Ubuntu 16.04.4 LTS

yii2 SwiftMailer|: useFileTransport ignored, always processed as true

This issue has originally been reported by @ynzejan at yiisoft/yii2#12333.
Moved here by @SilverFire.


What steps will reproduce the problem?

Submitting actionCreate with composing, setting and sending message using Yii->mailer

What is the expected result?

Email messages actually sent.

What do you get instead?

Email messages saved to file.

Additional info

I have setup all necessary configuration for the mailer in common/parms.php.
Added code in controller to send message.
The issue is that whatever I have as useFileTransport setting it always results in saving the message rather than sending the message.
I have tried to set useFileTransport to false, set to 0. even remove useFileTransport, since the default setting BaseMailer is false. The result is always the same: the message is saved.
Only if I tweak BaseMailer and set $this->useFileTransport = false; then the email is sent.

I used vardump of the mailer object in the controller and noticed that useFileTransport is already set to true, although set to false in the configuration.
Here is my create action in the controller:

$post = Yii::$app->request->post();
        if (!empty($post))
        {
            $model->load($post);

            $attachment = UploadedFile::getInstance($model, 'attachment');
            if ($attachment)
            {
                $model->bijlageNaam = $attachment->name;
                // the path to save file, you can set an uploadPath
                // in Yii::$app->params (as used in below)
                $path = Yii::$app->params['uploadPath'];
                // generate a unique file name
                $model->bijlage = $path . 
                    Yii::$app->security->generateRandomString() . 
                    '.' . 
                    $attachment->extension;
                $attachment->saveAs($model->bijlage);
            }
            if ($model->bijlage)
            {
                //$cat = 'yii\swiftmailer\Logger::add';
                //Yii::info('begin verwerken bijlage bij e-mail', $cat);
                $model->verzenderEmail = Yii::$app->params['receptieEmail']; 

                $aantalVerstuurd = 0;
                if (is_array($model->chauffeurId))
                {
                    $cIds = $model->chauffeurId;
                    foreach($cIds as $cId)
                    {
                        $adres = $this->getChauffeurEmail($cId);
                        $naam = $this->getChauffeurNaam($cId);
                        //$email = Yii::$app->mailer;
                        $email = Yii::$app->mailer->compose()
                        ->setFrom($model->verzenderEmail)
                        ->setSubject($model->onderwerp . ' bijlage: ' . $model->bijlageNaam)
                        ->setHtmlBody($model->emailInhoud)
                        ->attach($model->bijlage)
                        ->setTo(array($adres => $naam))
                        ->send();
                                             etc.

And here the configuration in the components section of common/parms:

'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            'enableSwiftMailerLogging' => true,
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',               
                'plugins' => 
                [
                    [
                        'class' => 'Swift_Plugins_LoggerPlugin',
                        'constructArgs' => [new Swift_Plugins_Loggers_ArrayLogger],
                    ],
                ],
                'host' => 'smtp.gmail.com',
                'authMode' => 'login',
                'username' => '[email protected]',
                'password' => 'PaSsW0Rd',
                'port' => '465',
                'encryption' => 'ssl',
                'streamOptions' => [ 'ssl' =>
                    [
                        'allow_self_signed' => true,
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                    ],
                ],
            ],
Q A
Yii version 2.0.9

Advanced template
| PHP version | 5.6.8
| Operating system | Windows 10
| XAMPP 5.6.8

Send email by console

I want send email by console with Swift_SmtpTransport and I think that is a issue.

The same transport settings work in common/config/main-local.php and don't work in console/config/main-local.php.

In console/config/main-local.php I have (is a copy of
common/config/main-local.php):

<?php
return [
    'components' => [        
        'mail' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            'htmlLayout' => '@common/mail/layouts/html',
            'textLayout' => '@common/mail/layouts/text',  // custome layout        
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'gator.hostgator.com',
                'username' => '[email protected]',
                'password' => '*******',
                'port' => '465',
                'encryption' => 'ssl',
            ],
        ],
    ],    
];

With this configuration (and in common the settings are the same and work) I load the script by command and no email send and no error.

With below (I delete the transport settings) I run the same script by command and the email send ok:

<?php
return [
    'components' => [        
        'mail' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            'htmlLayout' => '@common/mail/layouts/html',
            'textLayout' => '@common/mail/layouts/text',  // custome layout        
        ],
    ],    
];

In console/controllers/CronController I have this:

<?php

namespace console\controllers;

use yii\console\Controller;
use backend\models\Definicoes;
use common\models\Acordo;
use Yii;

/**
 * Cron controller
 */
class CronController extends Controller {

    public function actionIndex() {
        $data_hoje = date('Y-m-d');
        $model_definicoes = Definicoes::find()->one();

        Yii::$app->mail->compose('@common/mail/cron_acordo', ['model_definicoes' => $model_definicoes])
           ->setFrom([Yii::$app->params['adminEmail'] => Yii::$app->params['nome']])
           ->setSubject('Alert')
           ->setTo('[email protected]')     
           ->send();        
    }
}

Why this happen? I can´t use transport in console?
I verify in Cpanel the host, user and pass and is ok. This settings work fine in common where I send email without problems.
In the log I don't have any error.
How can I verify where is the problem?

Thanks!

| Yii vesion: 2.0.7 |
| PHP version: 5.4 |
| Operating system: Linux |

Error HTML code

Yii2 2.0.13 send html email.
In the HTLM code extra characters are added =
error_mail

Send mails on PHP 5.6 without correct OpenSSL certificate

Hi,
PHP 5.6 sets SSL flag verify_peer to true, so without proper SSL config sending e-mails cause error:

PHP Warning – yii\base\ErrorException
stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

It'll be great to set this flag in Yii2 main config file -> components -> mailer

Doesn't appear to work with Gmail

What steps will reproduce the problem?

http://stackoverflow.com/questions/37290204/cannot-send-email-from-yii-swiftmail-to-gmail-expected-response-code-250-but-go/37290443

    'smtp.host' => 'smtp.gmail.com',
    'smtp.username' => '[email protected]',
    'smtp.password.encrypted' => 'xxxxxxxxxxx',
    'smtp.port' => '587',
    'smtp.encryption' => 'tls',

What's expected?

Expect the email to send.

What do you get instead?

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 https://support.google.com/mail/answer/14257

Additional info

Q A
Yii vesion 2.0.7
PHP version PHP 5.6.19
Operating system Windows 8.1

Not valid html tag

I try yii2 advanced template, but for email (example reset password) give not valid html tag like =3D" etc, please check

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.=
org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns=3D"http://www.w3.org=
/1999/xhtml">
<head>
    <meta http-equiv=3D"Content-Type" con=
tent=3D"text/html; charset=3DUTF-8" />
    <title></title>
    <=
/head>
<body>
        <div class=3D"password-reset">
    <=
p>Hello user,</p>

    <p>Follow the link below to r=
eset your password:</p>

    <p><a href=3D"http://domain.com/admin/=
reset-password?token=3DRkyjyDtRrLqcwnmgYYFwqEL5389vI2yB_1440474633">http:/=
/domain.com/admin/reset-password?token=3DRkyjyDtRrLqcwnmgYYFwqEL5389vI2yB_144=
0474633</a></p>
</div>
    </body>
</html>

Improve logging

What steps will reproduce the problem?

  • try to send a mail to a non-resolvable host.

What's expected?

  • logs should show an error or warning
2016-11-18 05:06:04 [-][-][-][info][yii\mail\BaseMailer::send] Sending email „Willkommen auf My Application" to "[email protected]"
2016-11-18 05:06:04 [-][-][-][info][yii\swiftmailer\Logger::add] ++ Starting Swift_SmtpTransport
2016-11-18 05:06:04 [-][-][-][warning][yii\swiftmailer\Logger::add] !! Connection could not be established with host mailcatcher [php_network_getaddresses: getaddrinfo failed: Name or service not known #0] (code: 0)

What do you get instead?

  • all log messages from mailer in info
2016-11-18 05:06:04 [-][-][-][info][yii\mail\BaseMailer::send] Sending email „Willkommen auf My Application" to "[email protected]"
2016-11-18 05:06:04 [-][-][-][info][yii\swiftmailer\Logger::add] ++ Starting Swift_SmtpTransport
2016-11-18 05:06:04 [-][-][-][info][yii\swiftmailer\Logger::add] !! Connection could not be established with host mailcatcher [php_network_getaddresses: getaddrinfo failed: Name or service not known #0] (code: 0)

Additional info

Q A
Yii version 2.0.10 (extension: 2.0.6)
PHP version 7.0.12
Operating system Docker PHP (Debian)

Can't update to Yii version 2.0.11 due to swiftmailer dependencies

When trying to upgrade from Yii version 2.0.10 to 2.0.11 using composer require "yiisoft/yii2:~2.0.11" I get the following errors from composer

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package yiisoft/yii2 ~2.0.11 is satisfiable by yiisoft/yii2[2.0.x-dev] but these conflict with your requirements or minimum-stability.
  Problem 2
    - yiisoft/yii2-swiftmailer 2.0.6 requires yiisoft/yii2 ~2.0.4 -> satisfiable by yiisoft/yii2[2.0.10, 2.0.4, 2.0.5, 2.0.6, 2.0.7, 2.0.8, 2.0.9, 2.0.x-dev] but these conflict with your requirements or minimum-stability.
    - yiisoft/yii2-swiftmailer 2.0.6 requires yiisoft/yii2 ~2.0.4 -> satisfiable by yiisoft/yii2[2.0.10, 2.0.4, 2.0.5, 2.0.6, 2.0.7, 2.0.8, 2.0.9, 2.0.x-dev] but these conflict with your requirements or minimum-stability.
    - yiisoft/yii2-swiftmailer 2.0.6 requires yiisoft/yii2 ~2.0.4 -> satisfiable by yiisoft/yii2[2.0.10, 2.0.4, 2.0.5, 2.0.6, 2.0.7, 2.0.8, 2.0.9, 2.0.x-dev] but these conflict with your requirements or minimum-stability.
    - Installation request for yiisoft/yii2-swiftmailer (locked at 2.0.6, required as ~2.0.0) -> satisfiable by yiisoft/yii2-swiftmailer[2.0.6].

Is this something that has to do with this extension or is it something in my composer.json?
My composer.json

  "require": {
    "php": ">=5.5.0",
    "ext-intl": "*",
    "yiisoft/yii2": "~2.0.10",
    "yiisoft/yii2-bootstrap": "^2.0.0",
    "yiisoft/yii2-swiftmailer": "~2.0.0",
    "yiisoft/yii2-authclient": "^2.0.0",
    "yiisoft/yii2-jui": "^2.0.0",
    "mihaildev/yii2-elfinder": "^1.0",
    "trntv/yii2-aceeditor": "^2.0",
    "trntv/probe": "^0.2",
    "trntv/yii2-file-kit": "^1.0.0",
    "trntv/yii2-glide": "^1.0.0",
    "trntv/yii2-datetime-widget": "^1.0.0",
    "trntv/cheatsheet": "^0.1@dev",
    "trntv/yii2-command-bus": "^2.0",
    "intervention/image": "^2.1",
    "vlucas/phpdotenv": "^2.0",
    "bower-asset/admin-lte": "^2.0",
    "bower-asset/font-awesome": "^4.0",
    "bower-asset/html5shiv": "^3.0",
    "bower-asset/jquery-slimscroll": "^1.3",
    "bower-asset/flot": "^0.8",
    "symfony/process": "^3.0",
    "yiisoft/yii2-mongodb": "^2.1"
  },

Additional info

Q A
Yii version 2.0.10
PHP version 7.0.9
Operating system CENTOS 7

Setting Dynamic content for queued messages

Hello All,
In a multilanguage site context, messages are sent in real time translated into the language in use by the user.
I am trying to send site messages from a queue using a cron job.
The case is that the messages are added to queue only in the sourceLanguage.
What I would like is to populate the queue with already translated messages - in the user language according to the locale set in their profile. So users will get messages in their language.
I can't find a way to do that.
Any tips or hints?

When transport is gone, swiftmailer does not try to restart transport

What steps will reproduce the problem?

Make a queue that sends emails, send email and after some time(about 5-15 minutes) send another email

What's expected?

it sends email, waits 15 minutes (because queue said so) it sends another

What do you get instead?

it sends email, waits 15 minutes (because queue said so) gets error that transport is gone, because it never tries to reconnect

Additional info

4 lines of code fixes this(will make PR myself)

Q A
Yii version 2.0.15.1
Yii SwiftMailer version 2.0.7
SwiftMailer version 5.4.12
PHP version 7.2
Operating system Docker

Add method for reset (restart) transport

I'm using a worker for sending emails which work as a daemon and i noticed that daemon fails with an error when there is a long period between sending emails

Error: fwrite(): send of 6 bytes failed with errno=32 Broken pipe
PHP Notice:  fwrite(): send of 12 bytes failed with errno=32 Broken pipe in .../vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php on line 232

I found the swiftmailer's issue about this problem: swiftmailer/swiftmailer#490

One guy implemented his own extension for laravel that has functional for auto reseting smtp connection.
You can find it here: https://github.com/YOzaz/Laravel-SwiftMailer/blob/master/src/YOzaz/LaravelSwiftmailer/Mailer.php#L128

I think we can implement same functionality for avoid such error

SwiftMailer setReadReceiptTo not exists

This issue has originally been reported by @magefad at yiisoft/yii2#11457.
Moved here by @samdark.


What steps will reproduce the problem?

Yii::$app->mailer->compose()
->setFrom('[email protected]')
->setTo($form->email)
->setSubject($form->subject)
->setTextBody('Plain text content')
->setHtmlBody('HTML content')
->send();

What is the expected result?

Нет обертки для swiftmailer метода setReadReceiptTo как и соответственно самого метода при попытке отправки письма

get message body

After composing a message it would be nice to get its bodies:

$message = Yii::$app->mailer->compose([
    'html' => 'welcome-html',
    'text' => 'welcome-text',
]);

$subject = $message->getSubject(); // works
$html = $message->getHtmlBody();   // missing
$plain = $message->getTextBody();  // missing

// e.g., storing html and plain in a database for later usage, preview, ... here

Does yii2-swiftmailer support sending base64 emails

Dear,
I'm trying to use base64 image in Html body email and send it to gmail. But the email is not display image because all of resource of image is removed in email. So I would like to ask that

How could I use yii2-swiftmailer to send an email with base64 image (embed in-line image) correctly ?

Thank you!

Missing setReturnPath

Hi,

I have noticed that the following is missing from this plugin setReturnPath

http://swiftmailer.org/docs/messages.html#setting-the-return-path-bounce-address

Setting the Return-Path: (Bounce) Address¶

The Return-Path: address specifies where bounce notifications should be sent and is set with the setReturnPath() method of the message.

You can only have one Return-Path: and it must not include a personal name.

To set the Return-Path: address:

Call the setReturnPath() method on the Message.
Bounce notifications will be sent to this address.

1
$message->setReturnPath('[email protected]');

Plugin: Swift_Events_ResponseReceivedListener not working with yii2-swiftmailer

What steps will reproduce the problem?

Installing & configuring Swift_Events_ResponseReceivedListener:

      'mailer' => [
           'class' => 'yii\swiftmailer\Mailer',
           'viewPath' => '@frontend/mail',
           'htmlLayout' => '@frontend/mail/layouts/html',
           'transport' => [
               'class' => 'Swift_SmtpTransport',
               ...
               'plugins' => [
                   [
                       'class' => 'Swift_Events_ResponseReceivedListener',
                       'constructArgs'=>
                       [
                         'callback' => function ($message, $body) {
                                         echo sprintf($body->SendRawEmailResult->MessageId);
                                       }
                        ]
                   ],
               ],
             ],
           ],

What's expected?

The mailer object should return the Message ID provided by the ResponseReceivedListener plugin after the message has been sent.

What do you get instead?

Upon sending the mail I receive the following error:

PHP Fatal Error 'yii\base\ErrorException' with message 'Call to a member function getMessage() on string'
in \vendor\jmhobbs\swiftmailer-transport-aws-ses\classes\Swift\Events\ResponseReceivedListener.php:16

Turns out the $event->getResponse() function in ResponseReceivedListener.php returns response code strings, and no object. i.e:

220 email-smtp.amazonaws.com ESMTP SimpleEmailService-1383awdawd763 7anawddwadwSpawddwa
250-email-smtp.amazonaws.com
250-8BITMIME
250-SIZE 10485760
250-STARTTLS
250-AUTH PLAIN LOGIN
250 Ok
220 Ready to start TLS
250-email-smtp.amazonaws.com
250-8BITMIME
250-SIZE 10485760
250-STARTTLS
250-AUTH PLAIN LOGIN
250 Ok
334 AWDDAadwaU6
334 UAWDWDADmQ6
235 Authentication successful.
250 Ok
250 Ok
354 End data with <CR><LF>.<CR><LF>
250 Ok 01adwadwawd66e8d27-8acawdawddawf1b-4d8bdawadwdawc16f59a0-000000

I'm not 100% sure if this issue lies with yii2-swiftmailer or the plugin being outdated, and which of the 2 should be updated in order to get it working.

Swiftmailer: Connection could not be established

Hi,
after googling around and having seen a lot of messages to that issue I'm lost. Not one solution was applicable.
Sending an email from my Yii2 app results in

[Swift_TransportException] exception 'Swift_TransportException' with message 'Connection could not be established with host w010699b.kasserver.com [Unable to find the socket transport "TLS" - did you forget to enable it when you configured PHP? #0].

Same happens on my local host and on my webspace. On both TLS is enabled by the server and by PHP (says phpinfo()).
This is my config for SwiftMailer:

'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'viewPath' => 'app\mail',
        //'useFileTransport' => false,
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'host address',
            'username' => '[email protected]',
            'password' => '*********',
            'port' => '587',
            'encryption' => 'TLS',
            'plugins' => [
                [
                    'class' => 'Swift_Plugins_ThrottlerPlugin',
                    'constructArgs' => [20],
                ],
            ],
        ],
        'messageConfig' => [
            'charset' => 'UTF-8',
            //'from' => ['' => '[email protected]',],
        ],
        // send all mails to a file by default. You have to set
        // 'useFileTransport' to false and configure a transport
        // for the mailer to send real emails.
        //'useFileTransport' => true,
    ],

Sending emails from other applications on the webspace is possible, the config values are valid and TLS is supported by my hoster.
I tried as encrypton STARTTLS, SSL, tls and none with port 25 all with the same result. Deleting plugins or messageConfig does not help anyway,
Find the model and the view attached.
Here is the action code (SiteController):

public function actionEmaillink() {
    $getInput = Basics::TestInput();
    $model = new EmaillinkForm();
    if ($model->load(Yii::$app->request->post()) && $model->emaillink(Yii::$app->params['adminEmail'])) {
        Yii::$app->session->setFlash('emaillinkFormSubmitted');
        return $this->refresh();
    }
    return $this->render('emaillink', [
        'model' => $model,
        'id' => $getInput['id'],
        'entryId' => $getInput['entryId'],
        'year' => $getInput['year'],
    ]);
}

So what to do?
Regards
Christian

emaillink.php.txt
EmaillinkForm.php.txt

Please configure UrlManager::scriptUrl correctly as you are running a console application.

i have this error in my console for send mail:
Exception 'yii\base\InvalidConfigException' with message 'Please configure UrlManager::scriptUrl correctly as you are running a console application.'

in /home/vox/domains/vox.com/public_html/app/vendor/yiisoft/yii2/web/UrlManager.php:518

Address action in console:
/home/vox/public_html/app/commands/InvoiceController.php

Address Layout:
/home/vox/public_html/app/mail/revial-invoice.php

Undisclosed Recipients

This issue has originally been reported by @ApXaHgheJI at yiisoft/yii2#14371.
Moved here by @samdark.


What steps will reproduce the problem?

setBcc(['"Undisclosed recipients"[email protected]'])

What is the expected result?

Email recipient will see ( To:Undisclosed recipients )

What do you get instead?

Address in mailbox given ["Undisclosed recipients"[email protected]] does not comply with RFC 2822, 3.6.2.

Additional info

Q A
Yii version 2.0.?
PHP version
Operating system

Syntax Errors in files of The SwiftMailer

What steps will reproduce the problem?

If ran the console app on hosting by the cron and ran The Swiftmailer by this code
Yii::$app->mailer->compose()->setFrom(Yii::$app->params['robotEmail'])->setTo('some email')->setSubject('some subject')->send();

What's expected?

Only to get true.

What do you get instead?

Some syntax errors in a lot of swiftmailer files. Like this:

  1. PHP Parse Error 'yii\base\ErrorException' with message 'syntax error, unexpected '?''
    in /var/www/vhosts/kupdam.ru/httpdocs/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php:496

Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleFatalError()
#1 {main}

  1. PHP Parse Error 'yii\base\ErrorException' with message 'syntax error, unexpected '?''
    in /var/www/vhosts/kupdam.ru/httpdocs/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php:296

Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleFatalError()
#1 {main}

Additional info

Q A
Yii version 2.0.15.1
Yii SwiftMailer version 2.1.0.0
SwiftMailer version 6.0.2
PHP version 7.1.1
Operating system CentOS Linux 7.2.1511 (Core)‬

530 5.7.0 Authentication required on self hosted domain

What steps will reproduce the problem?

'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'mail.domain.com',
                'username' => '[email protected]',
                'password' => 'pass',
                'port' => '25', // tried with 465 (ssl) and 587
                'encryption' => 'tls',
            ],
        ],

I have tried sending an email to a self hosted domain, it works on popular domains such as google and yahoo but this error is shown in my casa:

530 5.7.0 Authentication required

Is there any way to on the transport object, something related authentication?

Additional info

Q A
Yii version 2
PHP version 5.6
Operating system Debian 8

Fatal PHP error when configuring a transport class with a protected property

If you try to configure yii\swiftmailer\Mailer with a Transport class that has getter/setter methods that correspond to a protected property, if you try to include that property in your Mailer config, it will result in a fatal PHP error because the property_exists() method on line 231 of Mailer.php will return true.

Here’s a concrete example: I’m trying to connect my Yii application to Mandrill using the MandrillTransport class from the accord/mandrill-swiftmailer library. MandrillTransport has a protected $apiKey property and a public setApiKey() method. So my mailer config is:

'mailer' => [
    'class' => 'yii\swiftmailer\Mailer',
    'transport' => [
        'class' => 'Accord\MandrillSwiftMailer\SwiftMailer\MandrillTransport',
        'constructArgs' => [
            [
                'class' => 'Swift_Events_SimpleEventDispatcher'
            ]
        ],
        'apiKey' => 'XXXXXXXX',
    ]
]

I was expecting that yii\swiftmailer\Mailer would be smart enough to match the apiKey setting with the setApiKey() method, as that’s what the logic suggests it will do, but instead I got that fatal PHP error due to the protected $apiKey property.

send mail error

my php 5.4

when i send mail , error happend:

 PHP Parse Error – yii\base\ErrorException
syntax error, unexpected '?'

    1. in /www/web/develop/fecshop/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php at line 496

 *
     * @return int
     */
    public function getPriority()
    {
        list($priority) = sscanf($this->getHeaderFieldModel('X-Priority'),
            '%[1-5]'
            );
 
        return $priority ?? 3;    // error Here!!!
    }

return $priority ?? 3; php 7.2

The problem with sending mail occurred after updating the PHP version.
Before that, everything was perfect.

PHP Parse Error 'yii\base\ErrorException' with message 'syntax error, unexpected '?''

in /vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php:490

Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleFatalError()
#1 {main}

Here is the problem.
return $priority ?? 3;

My PHP version is

php -v
PHP 7.2.12-1+ubuntu14.04.1+deb.sury.org+1 (cli) (built: Nov 12 2018 10:58:25) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.2.12-1+ubuntu14.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

SwiftMailer delivery status

This issue has originally been reported by @mogilka at yiisoft/yii2#15545.
Moved here by @samdark.


Why Yii2 Mailer uses SwiftMailer but ignores its failed recipients feature?

What steps will reproduce the problem?

Swift_Mailer class method send($message, $failedRecipients = null) has two parameters: message (requires) and failedRecipients (not required)

But yii\swiftmailer\Mailer calls send() method without parameter failedRecipients:

$this->getSwiftMailer()->send($message->getSwiftMessage()) > 0;

So it's impossible to detect if a mail delivery was success. For example, if incorrect email address used

What is the expected result?

I want to use all accessable SwiftMailer features, particularly "failedRecipients" parameter to get a list of email addresses which delivery process failed. So I want to have a posibility to check not only send() method result but also an array of recipients who did not receive the message - via native SwiftMailer variable "failedRecipients"

What do you get instead?

Default mailer settings and simplified send() method works perfect if it's no nessessary to check email delivery. But in most cases it is not enough and misleading that the recipient has received a message. There are no other ways to check this at the program level

Additional info

Q A
Yii version 2.0.8
PHP version 7.0.26
Operating system Ubuntu 16.04

Invalid Configuration – yii\base\InvalidConfigException

Yii Version: 2.1.
Yii SwiftMailer version: 2.2.x-dev
SwiftMailer version: 6.0.2
PHP version: PHP 7.1.17
Operating system: Centos7

src/app/mail
    layouts/html.php
    layouts/text.php
    passwordResetToken-html.php
    passwordResetToken-text.php

src/forms/PasswordResetRequestForm.php:

    return Yii::$app
        ->mailer
        ->compose(
            ['html' => 'passwordResetToken-html', 'text' => 'passwordResetToken-text'],
            ['user' => $user]
            )
        ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])
        ->setTo($this->email)
        ->setSubject('Password reset for ' . Yii::$app->name)
        ->send();

Error:

1. in /home/intracheck.tusoporte.net/public_html/vendor/yiisoft/yii2/BaseYii.php at line 318
309310311312313314315316317318319320321322323324325326327                                    unset($type['class']);
            }
            return static::$container->get($class, $params, $type);
        } elseif (is_callable($type, true)) {
            return static::$container->invoke($type, $params);
        } elseif (is_array($type)) {
            throw new InvalidConfigException('Object configuration must be an array containing a "__class" element.');
        }
 
        throw new InvalidConfigException('Unsupported configuration type: ' . gettype($type));
    }
 
    /**
     * @var LoggerInterface logger instance.
     */
    private static $_logger;
 
    /**
     * @return LoggerInterface message logger
                
2. in /home/intracheck.tusoporte.net/public_html/vendor/yiisoft/yii2/mail/BaseMailer.php at line 100 – yii\BaseYii::createObject(null)
3. in /home/intracheck.tusoporte.net/public_html/vendor/yiisoft/yii2/mail/BaseMailer.php at line 141 – yii\mail\BaseMailer::getComposer()

Can not catch Swiftmailer's exceptions

In my project if the email sending is failed, I have to rollback all my previous tasks (because it is a user registration, I have to delete the created user). I see the Swift_TransportException in the log, but I can not catch it in my try block. Also strange that the request replies HTTP Redirection 302 error code and redirects me to the same controller's view action with an id (which is the id of the previously created user in my action)

My configuration is:

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

the code is:

try {
    ...
    Yii::$app->mailer->compose()
    ->setFrom('[email protected]')
    ->setTo($model->email)
    ->setSubject('Activation email')
    ->setTextBody('Activation url: ' . $activationUrl)
    ->setHtmlBody('Activation url: ' . $activationUrl)
    ->send();
    ...
} catch (Exception $e) {
    //delete user here
}

Cannot work well with Office365's Starttls

What steps will reproduce the problem?

Send email with other mailbox succeeded already. Recently my user want to switch the mail server to office 365, so changed the mailbox and did some test, failed to send mail.

The config file was set as below:

    'mailer'=>[
            'class'=>'yii\swiftmailer\Mailer',
            'viewPath'=>'@common/mail',
            'useFileTransport'=>false,
            'transport'=>[
                'class'=>'Swift_SmtpTransport',
                'host'=>'smtp.office365.com',
                'username'=>'[email protected]',
                'password'=>'mypassword',
                'port'=>'587',
                'encryption'=>'START/TLS',
            ],
        ],

What's expected?

mail send success

What do you get instead?

Connection could not be established with host smtp.office365.com [php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known #0]

Additional info

Q A
Yii version 2.0.11
Yii SwiftMailer version 2.0.7
SwiftMailer version 5.4.8
PHP version 5.6.11
Operating system Mac OS

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.