I want to create a code such that if one configuration fails to send mail the other config will kick in to send the mail, I have created two configurations, One in the provider which is set on page load the other is a helper function which can be set as we need.
if I set the helper function before sending any mail the function kicks in but if I keep it in try-catch block the helper doesn't work
try {
Mail::to($administrator->email)->send(new ResetPassword($data));
} catch (\Exception $e) {
$mailsenderr = true;
}
if ($mailsenderr) {
$newConfig = new SecondaryMailer;
$newConfig->setmailer();
try {
Mail::to($administrator->email)->send(new ResetPassword($data));
} catch (\Exception $e) {
return [
"status" => 0,
"message" => 'Error sending mail.'
// , "error" => $e->getMessage()
];
}
}
return ["status" => 1, "message" => "Mail sent successflly"];
Figured out how to
Just create a provider and set the code like
$mail = DB::table('mail_variables')->where('mailer_type', 'primary')->where('status', 'active')->first();
try {
$transport = new \Swift_SmtpTransport($mail->host, $mail->port, $mail->encryption);
$transport->setUsername($mail->username);
$transport->setPassword($mail->password);
$mailer = new \Swift_Mailer($transport);
$mailer->getTransport()->start();
} catch (\Swift_TransportException $e) {
$mail = DB::table('mail_variables')->where('mailer_type', 'secondary')->where('status', 'active')->first();
}
$config = array(
'driver' => $mail->driver,
'host' => $mail->host,
'port' => $mail->port,
'from' => array(
'address' => $mail->from_address,
'name' => $mail->from_name
),
'encryption' => $mail->encryption,
'username' => $mail->username,
'password' => $mail->password,
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false,
);
Config::set('mail', $config);
Related
I want to send email with some accounts to some targets.But when use this code all emails are delivered to first sender account only.
from() just change name of sender in message and it could not change sender account
while(true)
{
$config = array(
'driver' => 'smtp',
'host' => $smtp,
'from' => array('address' => $senders[$p], 'name' =>
$senderName),
'username' => $senders[$p],
'password' => $senderpasses[$p],
'port' => '587',
'encryption' => 'tls'
);
Config::set('mail', $config);
$data = [
'target' => $email[$m],
'text' => $text,
'title' => $title,
'sender' => $senders[$p],
'senderName' => $senderName
];
try {
Mail::send('emails.mail', ['data' => $data], function
($message) use ($data) {
$message->from($data['sender'], $data['senderName']);
$message->to($data['target'])-
>subject($data['titl']);
});
} catch (\Exception $e) {
echo $e->getMessage();
}
$m++;
$p++;
if ($p >= count($senders)) {
$p = 0;
}
if ($m >= count($email)) {
return ($m);
}
}
it send email just with first sender and other users are not used.
Emails are, by definition, sent from a single sender to multiple addresses, so it is not possible to achieve what you are asking for.
You have to send the mail multiple times, one for each sender. May I ask you what is the purpose of this scenario?
I'm having a hard time trying to figure out how to send mails with sendgrid.
this is the code i currently have:
employees controller:
function _sendEmail($id) {
$email = new Email();
try {
$email->from(['coms#me.co' => 'Me'])
->profile('SendGrid')
->to([$id['email'] => $id['full_name']])
->subject("TEST SUBJECT")
->emailFormat("both")
->template('default')
->send('My message');
$this->Flash->success("Message sent.");
} catch (Exception $ex) {
echo 'Exception : ', $ex->getMessage(), "\n";
}
return $this->redirect(['action' => 'index']);
}
I'm working with this plugin I found a few days ago; https://github.com/Iandenh/cakephp-sendgrid... I configured everything as stated in the docs but when I want to send the mail, nothing happens, the function flashes the success message and makes the redirection, but no email is sent.
This is the email transport in the app.php
'EmailTransport' => [
'SendGridEmail' => [
'className' => 'SendGridEmail.SendGrid',
'api_key' => 'API_KEY'
],
and the delivery profile
'Email' => [
'SendGrid' => [
'transport' => 'SendGridEmail',
'template' => 'default',
'layout' => 'default',
'emailFormat' => 'both',
'from' => ['coms#me.co' => 'Me'],
'sender' => ['coms#me.co' => 'Me'],
]
]
I'd really appreciate if someone can point me out any mistake or a possible solution for my problem.
Hi there this might be too late but in case if anyone facing the same issue.
This is working for me
So the first mistake you did is you are using the Email class, with sendgrid you should be using sendgrid Mail method now
I assume you have already installed this package if not go ahead and add it to the composer.json file and update composer
"sendgrid/sendgrid": "~7",
After that you can use sendgrid class for sending emails like shown in example below
protected function sendEmail($to, $subject, $content)
{
$email = new \SendGrid\Mail\Mail();
$email->setFrom(Configure::consume('App.from_email'), Configure::consume('Theme.title'));
$email->setSubject($subject);
$email->addTo($to);
$email->addContent("text/html", 'Your email body');
$sendgrid = new \SendGrid(Configure::consume('App.sendgrid_api_key'));
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
}
You need to replace sendgrid_api_key with your api key. I am using it from my configuration file.
I've got a problem with sending mail using CakePHP. Everythings giong well, but i didn't receive any single mail , i tired to send to 2 different emails .
//WebsitesController.php
App::uses('AppController','Controller');
App::uses('CakeEmail','Network/Email');
class WebsitesController extends AppController
{
public $helpers = array('Html','Form','Session');
public $components = array('Email','Session');
public function contact()
{
$this->set('dane', $this->Website->findById(4));
}
public function contact_email()
{ /* all data is taken from contact.ctp, I debuged all data below and it's correct */
$useremail = $this->data['Website']['useremail'];
$usertopic = $this->data['Website']['usertopic'];
$usermessage = $this->data['Website']['usermessage'];
$Email = new CakeEmail();
$Email->from(array($useremail => ' My Site'));
$Email->to('wigan#mail.com');
$Email->subject($usertopic); // all data is correct i checked several times
$Email->send($usermessage);
if($Email->send($usermessage))
{
$this->Session->setFlash('Mail sent','default',array('class'=>'alert alert-success'));
return $this->redirect(array('controller'=>'websites','action'=>'contact'));
}
$this->Session->setFlash('Problem during sending email','default',array('class'=>'alert alert-warning'));
}
}
//contact.ctp
<fieldset>
<?php
echo $this->Form->create('Website',array('controller'=>'websites','action'=>'contact_email'));
echo $this->Form->input('useremail',array('class'=>'form-control'));
echo $this->Form->input('usertopic',array('class'=>'form-control'));
echo $this->Form->input('usermessage',array('class'=>'form-control'));
echo $this->Form->submit('Send',array('class'=>'btn btn-default'));
echo $this->Form->end();
?>
</fieldset>
all seems to be fine, even if statement in function contact_email is approved.
configuration ( i'm working on localhost, xampp, netbeans 7.4)
public $smtp = array(
'transport' => 'Smtp',
'from' => array('site#localhost' => 'My Site'),
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
try this, you didn't set the config
public function contact_email()
{ /* all data is taken from contact.ctp, I debuged all data below and it's correct */
$useremail = $this->data['Website']['useremail'];
$usertopic = $this->data['Website']['usertopic'];
$usermessage = $this->data['Website']['usermessage'];
$Email = new CakeEmail();
$Email->config('smtp')
->emailFormat('html')
->from($useremail)
->to('wigan#mail.com')
->subject($usertopic); // all data is correct i checked several times
if($Email->send($usermessage))
{
$this->Session->setFlash('Mail sent','default',array('class'=>'alert alert-success'));
return $this->redirect(array('controller'=>'websites','action'=>'contact'));
} else {
$this->Session->setFlash('Problem during sending email','default',array('class'=>'alert alert-warning'));
}
}
Please follow the steps:
step 1: In this file (app\Config\email.php)
add this:
public $gmail = array(
'transport' => 'Smtp',
'from' => array('site#localhost' => 'Any Text...'),
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'timeout' => 30,
'username' => 'youremail#example.com',
'password' => 'yourPassword',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
step 2: Add an email template (app\View\Emails\html\sample.ctp)
<body>
<h1>Email Testing: <?php echo $first_name?></h1>
</body>
step 3: Change the code in your method as shown below:
public function send_my_email() {
App::uses('CakeEmail', 'Network/Email');
$Email = new CakeEmail();
$Email->config('gmail'); //configuration
$Email->emailFormat('html'); //email format
$Email->to('receiveremail#ex.com');
$Email->subject('Testing the emails');
$Email->template('sample');//created in above step
$Email->viewVars(array('first_name'=>'John Doe' ));//variable will be replaced from template
if ($Email->send('Hi did you receive the mail')) {
$this->Flash->success(__('Email successfully send on receiveremail#ex.com'));
} else {
$this->Flash->error(__('Could not send the mail. Please try again'));
}
}
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
I've been trying to send emails with Pear on xampp through Gmail, and after spending hours setting it all up and figuring out all the errors I was getting, I thought I was so close, until I started getting this error:
controller action
public function automail() {
App::uses('CakeEmail', 'Network/Email');
$ret_msg = null;
try {
$is_call_email = true;
$subject = "case detail";
$comment = "Ready to Review";
$email_to = "exmaple#gmail.com";
if ($is_call_email == true) {
$email_to = str_replace(' ', '', $email_to);
$email_addresses = preg_split('/[;,]/', $email_to);
$this->log($is_call_email,'bool');
$email = new CakeEmail();
$email->from(array($this->Session->read('Auth.User.email') => $this->Session->read('Auth.User.name')))
->to($email_addresses)
->subject($subject)
->send($comment);
$this->log($subject,'subject');
}
} catch (Exception $ex) {
$ret_msg = $ex->getMessage();
$this->log($ex->getLine(), 'emailError');
}
$this->log('Return msg is = ' . $ret_msg, 'shared');
return;
in email.php
<?php
class EmailConfig {
public $default = array(
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'username' => 'example#gmail.com', //example#gmail.com
'password' => 'secret',
'transport' => 'Smtp',
'from' => array('exampe#gmail.com' => 'Nam Email'),
'log' => true
);
}
from and to both are same email addresses because i was send in my account for testing...
please help me or any advice for how to send email using cakephp....
You need to specify $email->config. Like:
$email->config('default')
->from(array($this->Session->read('Auth.User.email') => $this->Session->read('Auth.User.name')))
->to($email_addresses)
->subject($subject)
->send($comment);