I am currently not receiving emails using the below configuration and was wondering if's it something to do with my set up maybe missing something or it doesnt work on MAMP localhost?
main-local.php in common config directory
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
// 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,
],
And then to send the email (which does display a success message)
public function submitreview($email)
{
//return Yii::$app->mailer->compose(['html' => '#app/mail-templates/submitreview'])
return Yii::$app->mailer->compose()
->setTo($email)
->setFrom([$this->email => $this->name])
->setSubject($this->title)
->setTextBody($this->description)
->attachContent($this->file)
->send();
}
You can send mail through localhost in Yii2 with following config.
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'ENTER_EMAIL_ADDRESS_HERE',
'password' => 'ENTER_PASSWORD',
'port' => '587',
'encryption' => 'tls',
],
]
and in your controller
\Yii::$app->mail->compose('your_view', ['params' => $params])
->setFrom([\Yii::$app->params['supportEmail'] => 'Test Mail'])
->setTo('to_email#xx.com')
->setSubject('This is a test mail ' )
->send();
I simply m using gmail for testing, used this php file to send mail from local host.
When you're going for production, replace the transport file with your original credentials.
the $result will echo 1, if the mail is successfully sent
<?php
$subject="Testing Mail";
$body="<h2>This is the body</h2>";
$to="*******#gmail.com"; //this is the to email address
require_once 'swiftmailer/swift_required.php';
// Create the mail transport configuration
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')->setUsername('######')->setPassword('######');
//$transport = Swift_MailTransport::newInstance();
$message = Swift_Message::newInstance()
->setSubject($subject)
->setFrom(array('#######gmail.com'))
->setTo(array($to))
->setBody($body,'text/html');
//send the message
$mailer = Swift_Mailer::newInstance($transport);
$result=$mailer->send($message);
?>
When useFileTransport is set to true (Default in development environment) then mails are saved as files in the 'runtime' folder.
For example, if you are using the advanced starter template and signup as a user when in the backend of the site (And using an extension that sends user registration emails), the registration email will be saved in /backend/runtime/mail
Related
I'm trying to dynamically change the sender of the email through config but it doesn't work, it always sends from the email configured in the .env.
$config = array(
'driver' => 'smtp',
'host' => 'smtp.googlemail.com',
'port' => '465',
'from' => array('address' => optional($model->account)->email,
'name' => optional($model->account)->from),
'encryption' =>'ssl',
'username' => optional($model->account)->email,
'password' => optional($model->account)->password,
);
Config::set('mail', $config);
Mail::to($customer_email)->send(new DinamicMail());
How can I achieve to send the mail of an account dynamically.
This was the code I had used for multiple emails
// Backup your default mailer
$backup = Mail::getSwiftMailer();
// Setup your gmail or other mailer
$transport = (new \Swift_SmtpTransport(env('MAIL_HOST'), env('MAIL_PORT'), env('MAIL_ENCRYPTION')))
->setUsername(env('MAIL2_USERNAME'))
->setPassword(env('MAIL2_PASSWORD'));
// Any other mailer configuration stuff needed...
$custom_mail = new \Swift_Mailer($transport);
// Set the mailer
Mail::setSwiftMailer($custom_mail);
// Send your message
Mail::to('test#test.com')->send(new InsuranceMail( (object)$mail_data) );
// Mail::to(config('mail.insurance'))->send(new InsuranceMail( (object)$mail_data) );
// Restore your original mailer
Mail::setSwiftMailer($backup);
Note: MAIL2_USERNAME or MAIL_HOST are also added in .env, the rest I think you get the idea
I write a game for football fans. So, I have to send similar mails to a group of people (not completely duplicated e-mail copies).
When I send the mails in a cycle - Yii framework sends the mails twice.
I suppose - it is because of the static variable Yii::$app.
Can someone give me a hint, please.
A code for example.
foreach ($oRace->user as $currUser) {
$htmlContent = $this->renderPartial('start_race', ['oRace' => $oRace]);
Yii::$app->mailer->compose()
->setFrom('info#example.com')
->setTo($currUser->mail)
->setSubject('Race "' . $raceName . '" has Started')
->setHtmlBody($htmlContent)
->send();
}
Thanks all in advance!
My Mailer config.
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'mail.example.eu',
'username' => 'support#example.com',
'password' => 'password',
'port' => '587',
'encryption' => 'TLS',
]
],
One more thing. The last mail in the cycle is never duplicated (only the last).
Another failed option.
Yii::$app->mailer->sendMultiple($allMails);
I recommend you to use CC or BCC option in the email instead of using foreach loop to send emails. I hope this will help someone.
$email = [];
foreach ($oRace->user as $currUser) {
$email[] = $currUser->mail;
}
$htmlContent = $this->renderPartial('start_race', ['oRace' => $oRace]);
Yii::$app->mailer->compose()
->setFrom('info#example.com')
->setCc($email) // If you're using Bcc use "setBcc()"
->setSubject('Race "' . $raceName . '" has Started')
->setHtmlBody($htmlContent)
->send();
From the provided code snippets, there are 3 possible reasons for that. Either:
$oRace->user contains every user twice
$currUser->mail contains the email twice like `email#example.com;email#example.com"
something is wrong inside the send function of SwiftMailer
After all - I have found that the issue was not with my Yii2 framework, but with my hosting mail server.
I have used https://github.com/ChangemakerStudios/Papercut for listening what my framework sends. It receives mails on port 25, while it listens for events on port 37804. It's a little bit confusing. Yii2 web.php simple configuration for local mail server is:
$config = [
'components' =>
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'localhost', // '127.0.0.1'
'port' => '25',
]
],
],
];
Thank of all, who have read my post!
Is there an easy way to "override" the destination of an email using CakeEmail?
I have a model method that send an email using this piece of code:
$Email = new CakeEmail();
$Email->config('default');
$sent = $Email->template('new-notification')
->subject('A new notification for you')
->viewVars([
'name' => $foo['User']['name'],
'text' => $foo['Notification']['text'],
)
->emailFormat('html')
->to($foo['User']['email'])
->send();
And this configuration:
class EmailConfig
{
public $default = array(
'host' => 'smtp.server.com',
'port' => 587,
'username' => 'user#domain.com',
'password' => 'pwdAsYouKnow',
'from' => array('noreply#domain.com' => 'Company'),
'transport' => 'Smtp'
);
}
As you can see, I send the email for a dynamically defined user's email.
My objective is when I'm developing locally on my machine, to force every call to ->send() to force a destination like developer#domain.com.
I can easily detect if I'm on development, but I don't know how to force in a "master" way to CakeEmail only send to a defined account overriding the one set on the call.
I already tried to set an
'to' => array('developer#domain.com' => 'Dev'),
inside $default but, no success.
I appreciate any help, thanks!
i'm assuming when you are on local machine you run in debug mode, so you can check if debug mode is on then use that to send to different email
if(Configure::read('debug')){
$emailTo = 'developer#domain.com'
}
else{
$emailTo = $foo['User']['email'];
}
then you just use variable for email address:
$sent = $Email->template('new-notification')
->subject('A new notification for you')
->viewVars([
'name' => $foo['User']['name'],
'text' => $foo['Notification']['text'],
)
->emailFormat('html')
->to($emailTo)
->send();
I have a Silex app with Swift Mailer, but it seems like the configuration was not loaded from $app['swiftmailer.options'].
I registered the service in my bootstrap file
$app->register(new SwiftmailerServiceProvider());
And in my configuration file
$app['swiftmailer.options'] = array(
'host' => 'smtp.mandrillapp.com',
'port' => '587',
'username' => 'MY_USERNAME',
'password' => 'MY_PASSWORD',
'encryption' => null,
'auth_mode' => null
);
And then I send my email with
$message = \Swift_Message::newInstance()
->setSubject($this->app['forum_name'] . ' Account Verification')
->setFrom(array('no-reply#domain.com'))
->setTo(array('recipient#example.com'))
->setBody('My email content')
->setContentType("text/html");
$this->app['mailer']->send($message);
The send function returns 1 but the email was never sent. But, when I try manually creating an instance of Swift_SmtpTransport, the email would send.
$transport = \Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587)
->setUsername('MY_USERNAME')
->setPassword('MY_PASSWORD');
...
$mailer = \Swift_Mailer::newInstance($transport);
$mailer->send($message);
So the problem is the $app['swiftmailer.options'] is not read or loaded. Am I missing something here?
I'm following the instructions from here.
By default the SwiftmailerServiceProvider uses a spooled transport to queue up emails and sends them all during the TERMINATE stage (after a response is sent back to the client). If you don't call Application->run(), you are bypassing this process. Your mail will stay in the spool and never get sent.
If you want to sent mail outside of the normal Silex flow, you can flush the spool manually with
if ($app['mailer.initialized']) {
$app['swiftmailer.spooltransport']
->getSpool()
->flushQueue($app['swiftmailer.transport']);
}
That's taken directly from the SwiftmailerServiceProvider.
Or you can simply turn off spooling with
$app['swiftmailer.use_spool'] = false;
Try this:
$app->register(new \Silex\Provider\SwiftmailerServiceProvider(), array(
'swiftmailer.options' => array(
'sender' => 'sender',
'host' => 'host',
'port' => 'port',
'username' => 'username',
'password' => 'password'
)
));
It is not in the documentation.
I recently uploaded a CakePHP 2.3.8 app to a Ubuntu 12.04 EC2 instance and now I cannot send emails when using $Email->send() but I can do it with the "fast" method of CakeEmail::deliver('to#gmail.com', 'Subject', 'Content');, however I have a layout that I want to use.
When I try to send an email I get an error stating "Could not send email.
Error: An Internal Error Has Occurred."
Here is my code for sending the email.
App::uses('CakeEmail', 'Network/Email');
$Email = new CakeEmail();
$Email->from(array('myemailaddress#gmail.com' => 'Me'));
$Email->to('person#gmail.com');
$Email->subject('Test Email');
$Email->template('layout_1');
$Email->emailFormat('html');
$testvalues = array('item1' => 'test1', 'item2' => 'test2');
$Email->viewVars(array('tesvalues'=> $testvalues));
$Email->send();
$this->Session->setFlash('Email has been sent');
$this->redirect($this->referer(), null, true);
In /App/Config/email.php here is what I have for smtp
public $smtp = array(
'transport' => 'Smtp',
'from' => array('me#gmail.com' => 'Me'),
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'timeout' => 30,
'username' => 'me#gmail.com',
'password' => '****',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
The exact line that the stack trace flags is in CORE/Cake/Network/Email/MailTransport.php
$this->_mail($to, $email->subject(), $message, $headers, $params);
I checked the error log and it says
Error: [SocketException] Could not send email.
I am going to shoot in the dark here.
It seems to me that you are not setting the layout correctly, according to the documentation you need to tell cake the layout and the view you want to use, for example:
$Email = new CakeEmail();
$Email->template('welcome', 'fancy')
->emailFormat('html')
->to('bob#example.com')
->from('app#domain.com')
->send();
The above would use app/View/Emails/html/welcome.ctp for the view, and app/View/Layouts/Emails/html/fancy.ctp for the layout.
Anyways, I recommend taking a look at Cake logs (app/tmp/logs) and see the cause of your error