How to handle invalide email exception in cakephp? - email

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

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";
}

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

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
}

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.

how do i send an email through joomla

I have a system so folks can register for a class through my Joomla site (I believe it's 3.0). But from there, I would like to send folks an email filling variables from the registration. So something like:
Dear (name), thank you for registering for (class).
This is to remind you your class is tomorrow, (date), at (place).
I believe for the registration, the system uses authorize.net
How can I accomplish this?
Thanks for the help!!
You can use JFactory:getMailer like suggested in the following post. I'm copying here his code example (modified it a bit):
$subject = "Here is the subject of your message.";
$body = "Here is the body of your message.";
$user = JFactory::getUser();
$to = $user->email;
$from = array("me#mydomain.com", "Brian Edgerton");
# Invoke JMail Class
$mailer = JFactory::getMailer();
# Set sender array so that my name will show up neatly in your inbox
$mailer->setSender($from);
# Add a recipient -- this can be a single address (string) or an array of addresses
$mailer->addRecipient($to);
$mailer->setSubject($subject);
$mailer->setBody($body);
# If you would like to send as HTML, include this line; otherwise, leave it out
$mailer->isHTML();
# Send once you have set all of your options
$mailer->send();
That's all there is to it for sending a simple email. If you would like to add carbon copy recipients, include the following before sending the email:
# Add a blind carbon copy
$mailer->addBCC("blindcopy#yourdomain.com");
Another alternative is using JMail::sendMail: http://docs.joomla.org/API17:JMail::sendMail
Fetch the Mail Object:
`$mailer = JFactory::getMailer();`
Set a Sender
$user = JFactory::getUser();
$recipient = $user->email;
$mailer->addRecipient($recipient);
$mailer->setSender($sender);
Recipient
$user = JFactory::getUser();
$recipient = $user->email;
$mailer->addRecipient($recipient);
Create the Mail
$body = 'Body Text';
$mailer->isHtml(true);
$mailer->Encoding = 'base64';
$mailer->setBody($body);
Sending the Mail
$send = $mailer->Send();
if ( $send !== true ) {
echo 'Error sending email: ';
} else {
echo 'Mail sent';
}
https://docs.joomla.org/Sending_email_from_extensions

How do I AddAddress automatically in PHPmailer from form php info?

This has got to be a simple one, but I've been searching all over and nothing seems relevant to my problem: or i'm not able to interpret advice for others adequately.
I'm getting the error "You must provide at least one recipient email address. Message could not be sent."
If I put a specific email address in 'AddAddress' field the message is sent. I want to have an email sent to the user who has submitted their form as an automatic email response thanking user for registering... Thus the ($_POST['email']) in the 'AddAddress' field. This works in Mail() php function. Why not PHP MAiler? What am I missing?
Here is my code with sensitive bits taken out (Relevant bit - I think - in bold):
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$email=$_POST['email'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email,) VALUES('$email',)";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
}
else {
echo "ERROR";
}
?>
<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "localhost"; // specify main and backup server
$mail->SMTPAuth = false; // turn on SMTP authentication
$mail->Username = ""; // SMTP username
$mail->Password = ""; // SMTP password
$mail->From = "";
$mail->FromName = "";
**$mail->AddAddress = ($_POST['email']);**
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "";
$mail->Body = "";
$mail->AltBody = "";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
<?php
// close connection
mysql_close();
?>
Many thanks in advance for your advice. Hopefully this will help others too...
Ed
Simple one... just change this line
$mail->AddAddress = ($_POST['email']);
to this:
$mail->AddAddress($_POST['email']);
as it is a method, as opposed to a variable, on the class! :)
there are some good examples you can use on the PHPMailer GitHub