cakephp 3.x how to check if mail send or not - email

i am sending mail using cakephp 3.0 this is my code
$email = new Email();
$siteEmail = "test#example.com";
$subject = "Message subject";
$email = new Email();
$email->from($siteEmail)
->to($userEmail)
->subject($subject);
$response = $email->send($message);
if($response) {
$this->Flash->success(__('mail send'));
} else {
$this->Flash->error(__('mail send fail'));
}
but how to check if mail is send or not if i print the $response variable than its print the array of all mail related data like to from message and subject no response like message is send or not how to check so that print the success or failure flash message when i use if else as shown above its always return true either mail sent or not
thanks

Send failures are causing exceptions, \Cake\Network\Exception\SocketException to be exact, so wrap your send() call in a try block, and evaluate possible catched exceptions.
use Cake\Network\Exception\SocketException;
// ...
try {
$email->send($message);
// success
} catch (SocketException $exception) {
// failure
}

Related

sendgrid getting error : The from address does not match a verified Sender Identity

when i try to send email with From Name : xxx#gmail.com it is not working, i am getting this error : The from address does not match a verified Sender Identity , can anyone please help me how to verify gmail domain ? so i can send email from gmail also, here is my code for it
$email = new \SendGrid\Mail\Mail();
$email->setFrom("xxxx#gmail.com", "test");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("xxxx#gmail.com", "Example User");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
"text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);
$apiKey = 'xxxxxxx';
$sendgrid = new \SendGrid($apiKey);
try {
$response = $sendgrid->send($email);
echo '<pre>';
print_r($response);
exit;
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}

recipient receives same mail twice while sending mail in yii 1.1

I am trying to send mail to recipient one at a time.My code is like this:
$message = new YiiMailMessage;
$message->view = "mail";
$params = array('sendEmail'=>$values);
$message->subject = $values['subject'];
$message->setBody($params, 'text/html');
$message->from =$values['email_from'] ;
$message->addTo($values['email_to']);
if(Yii::app()->mail->send($message)){
Yii::app()->user->setFlash('success','Success sending email. ');
$this->redirect(array('mail/admin'));
}else{
Yii::app()->user->setFlash('error','Error while sending email. ');
}
Mail is received by recipient but same mail is received twice.
Maybe you are using a create action to notify the user each time a new record is created. Verify Yii::app()->mail->send($message) appears one time in your action, for example:
public function actionCreate()
{
$model= new MyModel;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['SomeForm']))
{
$model->attributes=$_POST['SomeForm'];
if($model->validate()){
if($model->save()){
$message = new YiiMailMessage;
$message->setBody('<h1>mets-blog.com</h1>','text/html');
$message->subject = 'Service';
$message->addTo('mets#blog.com');
$message->from = 'your#email.com' you want
Yii::app()->mail->send($message);
$this->redirect(array('view','id'=>$model->id));
}
}
}
$this->render('create',array(
'model'=>$model,
));
}
maybe you are calling your action twice in your controller by render your view.

How to handle invalide email exception in cakephp?

I have a list of array. There are some invalid emails inside an array. i.e:
$to = array('sattar.kuet#gmail.com','sas dsad .com');
Here sattar.kuet#gmail.com is an valid mail but sas dsad .com is not a valid email. So if I want to send email with this recipients ($to) there will be occurred a fatal error for sas dsad .com. So How can I ignore these invalid email?
N.B: I am using cakephp 2.6.7
CakeEmail throws SocketException if the email address is not well constructed. Just catch the exception and ignore it.
Option 1: Send multiple emails
$email = new CakeEmail();
$to = array('sattar.kuet#gmail.com','sas dsad .com');
foreach ($to as $emailAddress) {
try {
$email->to($emailAddress);
$email->send();
} catch(SocketException $e) {
//Do nothing
}
$email->reset();
}
Option 2: Send a single email
$email = new CakeEmail();
$to = array('sattar.kuet#gmail.com','sas dsad .com');
foreach ($to as $emailAddress) {
try {
$email->addTo($emailAddress);
} catch(SocketException $e) {
//Do nothing
}
}
$email->send();
See CakeEmail::addTo().
You can remove all invalid email with following code :
<?php
$len=count($array);
for ($i=0;$i<$len;$i++)
if (preg_match('^[a-z0-9!#$%&*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+(?:[a-z]{2,4}|museum|travel)$/i',$array[$i]))
echo $array[$i];
?>
Remove invalid email format in PHP

Cakephp mail sending error

I am getting the following error while sending mail from on localhost through my application:
Strict (2048): Only variables should be passed by reference
[CORE\Cake\Network\Email\SmtpTransport.php, line 217]
The mail gets sent but an error is thrown and the screen does not redirect. I just want to get rid of this error.
I am posting the code from line 217 onwards.
$response = end(explode("\r\n", rtrim($response, "\r\n")));
if (preg_match('/^(' . $checkCode . ')(.)/', $response, $code)) {
if ($code[2] === '-') {
continue;
}
return $code[1];
}
throw new SocketException(__d('cake_dev', 'SMTP Error: %s', $response));
The email code is below.
$email = new CakeEmail();
$email->config('gmail');
$email->viewVars(array('userfname'=>$data['User']['username']));
$email->viewVars(array('userlname'=>$data['User']['username']));
$email->viewVars(array('username'=>$data['User']['username']));
$email->template('welcome')
->emailFormat('html')
->sender('amitagarwal_dce#rediffmail.com', 'MyApp emailer')
->from(array('me#example.com' => 'CC'))
->to($data['User']['username'])
->bcc(array('atkral11#gmail.com'))
->subject('Thankyou for applying with us')
->send();
Any help is appreciated.

CodeIgniter: Cannot redirect after $this->email->send()

i have the following code which sends an email from a posted form:
$this->load->library('email');
$config['charset'] = 'iso-8859-1';
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from('info#mysite.com', 'Scarabee');
$this->email->to('info#mysite.com');
$this->email->subject('Message via website');
$data['msg'] = nl2br($this->input->post('msg'));
$data['msg'] .= '<br><br><b>Verstuurd door:</b><br>';
if($this->input->post('bedrijf')){
$data['msg'] .= $this->input->post('bedrijf').'<br>';
}
$data['msg'] .= $this->input->post('naam').'<br>';
$data['msg'] .= $this->input->post('adres').' - '.$this->input->post('postcode').', '.$this->input->post('gemeente').'<br>';
$data['msg'] .= $this->input->post('tel').'<br>';
$data['msg'] .= $this->input->post('email');
$message = $this->load->view('email', $data, TRUE);
$this->email->message($message);
if($this->email->send()){
$success = 'Message has been sent';
$this->session->set_flashdata('msg', $success);
redirect('contact/'.$this->input->post('lang'));
}
else{
show_error('Email could not be sent.');
}
Problem: the email gets sent with proper formatting (from the email view template), but the page then goes blank. For instance, if I try to echo out $message just below the $this->email->send() call, nothing shows up. Redirecting, as I’m attempting above, obviously doesn’t work either. Am I missing something? Thanks for any help…
Update
Traced the problem down to a function inside /system/libraries/Email.php (CI's default email library). Commenting out the code inside this function allows the mail to get sent, as well as a proper redirect:
protected function _set_error_message($msg, $val = '')
{
$CI =& get_instance();
$CI->lang->load('email');
if (substr($msg, 0, 5) != 'lang:' || FALSE === ($line = $CI->lang->line(substr($msg, 5))))
{
$this->_debug_msg[] = str_replace('%s', $val, $msg)."<br />";
}
else
{
$this->_debug_msg[] = str_replace('%s', $val, $line)."<br />";
}
}
The line that caused the error is: $CI->lang->load('email');
Go figure...
UPDATE 2: SOLVED
I had this in my controller's construct:
function __construct() {
parent::__construct();
$this->lang = $this->uri->segment(2, 'nl');
}
I guess there was a conflict between $this->lang and the _set_error_message function which also returns a "lang" variable (see var_dump further down).
Solution: changed $this->lang to $this->language, and everything's hunky dory!
Thought I'd post the answer here in case anyone else is ever losing hair with a similar problem :-)
It's likely that an error is occurring when you attempt to send an e-mail which is then killing your script during execution. Check your apache and PHP error logs ( /var/log/apache/ ) and enable full error reporting.
You could, for debugging purposes, try doing this:
...
$this->email->message($message);
$this->email->send();
redirect('contact/'.$this->input->post('lang'));
This should redirect you, regardless of your mail being sent or not (if you still recieve it, you can assume that the redirect would be the next thing that happens).
My own solution looks like this:
...
if ( $this->email->send() )
{
log_message('debug', 'mail library sent mail');
redirect('contact/thankyou');
exit;
}
log_message('error', 'mail library failed to send');
show_error('E-mail could not be send');
$ref2 = $this->input->server('HTTP_REFERER', TRUE);
redirect($ref);
By using the above code you can redirect to the current page itself
and you can set your flash message above the redirect function.