cakephp2 validate emails in controller before send multiple message - email

In Cakephp2, i would like to verify emails which stocked from a mysql database before sending an emailing to many participants.
the problem is if the application meet a bad email => it crash.
I've implemented a validate fonction in the Controller but the bad emails are not filtered and the application crash.
How will i do to separate the bad email to the rest to let the application continue and send all the goods emails without crashing?
eventually , i would keep all emails bad in $erreurs.
Heu....Before posting here, i've read, search and try......
Thanks
Controller
/* $trouve=result of find (all)*/
$envoyes= 0;
$non_envoyes = 0;
foreach ($trouve as $k => $v)
{
if($this>VueAppliMouv>validates(array('fieldList'=>array('email'))))
{
/*i do my emailing=> it's working */
$send++;
}
else
{
$erreurs= $this->VueAppliMouv->validationErrors;
no_send++;
}
}
Model
public $validate = array(
'email'=> array(
'rule'=>'email' ,
'required'=>false ,
'allowEmpty'=>false,
'message'=>"Indiquez un email valide"
)
); //fin validate
View
<h1> il y a eu <?=$envoyes ;?> mails envoyés</h1> <br>
<h1> il y a eu <?=$non_envoyes ;?> mails NON envoyés</h1> <br>
<?php
if (is_array($erreurs))
{
foreach ($erreurs as $key => $valeur)
{
echo "erreur" . $key . "" . $valeur."\n";
}
}
else
{
echo "$erreurs \n";
}
i've send 2 mails:
the first with bad adress,
and the second with a good adress.
even the good one didn't arrive...
Result
Invalid email: "rvagui#gmail"
Error: An Internal Error Has Occurred.
Stack Trace

Related

PHPmailer: Exclude input field from foreach loop

I am happily running a contact form using https://github.com/PHPMailer/PHPMailer and recently added https://friendlycaptcha.com to minimize the amount of spam sent by bots through that form. I love the sleek implementation with no user interaction. The captcha is activated once you click the first input field in the form and auto-solves.
Unfortunately the captcha's solution (hidden input field) adds an enormous string to the e-mail that I would like to exclude.
How do I tell the foreach loop not to include the frc-captcha-solution in the mail that's composed?
private function compose_mail($post)
{
$content = "The following message has been received via contact form:\n\n";
foreach($post as $name=>$value)
{
$content .= ucwords($name).": \t";
$content .= "$value\n\n";
}
$this->mailer->Body = $content;
}
This is the input field in the form that is generated and yields the long string.
<input name="frc-captcha-solution" class="frc-captcha-solution" type="hidden" value=".UNSTARTED">
An example of what I get is:
name: Joe
e-mail: joe#miller.com
address: 100 street
ZIP: 10100
place: City
phone: 0123456789
msg: This is a test message
Frc-captcha-solution: f5e6874becd6758f456b78f6f1726e1d.YadsJVSp+/j0pyBNAQwtjQAAAAAAAAAA+eFoDacaj3c=.AAAAAJZoAQABAAAAQ5YAAAIAAADCJAUAAwAAAF9IAQAEAAAAj5cEAAUAAACwkQMABgAAAFcaAAAHAAAAfvIEAAgAAADvUwIACQAAAK/MAQAKAAAAm+MBAAsAAACU6AAADAAAAJZUAAANAAAA/dAEAA4AAABrSwEADwAAAC7mAAAQAAAAXFoDABEAAAD4UAEAEgAAACMEAAATAAAA3xcCABQAAABBHwMAFQAAAE6LAQAWAAAA1mwAABcAAAAmwwAAGAAAACIZBwAZAAAA6p4AABoAAADovwIAGwAAAFE/AAAcAAAA+d8BAB0AAACQ8gAAHgAAAO1fAgAfAAAAbtwCACAAAAA7EgEAIQAAABmWAQAiAAAA/ysAACMAAAAx0wIAJAAAAJsyBAAlAAAA6acBACYAAACATwAAJwAAAM/wBQAoAAAATLYJACkAAABT1AIAKgAAAMWWAwArAAAAzIAGACwAAAA3fwAA.AgAA
There are many ways to do that, but one is to skip that name when it appears in your loop:
private function compose_mail($post)
{
$content = "The following message has been received via contact form:\n\n";
foreach($post as $name => $value) {
if ($name !== 'frc-captcha-solution') {
$content .= ucwords($name).": \t";
$content .= "$value\n\n";
}
}
$this->mailer->Body = $content;
}

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

Laravel - How to send email to all users

Im struggling to make a code that sends email to my subscribed users. I want to pass body to view according to users default language, can anyone help me ?
My code:
if($newsletter->save())
{
//get users to send to
$users = User::where('newsletter', '=', '1')->Where('activated', '=', '1')->get();
//Send to all users subscribed
foreach($users as $user)
{
//set info according to user default lang
if($user->default_lang == 'pt')
{
$body = $newsletter_pt;
$subject = Input::get('subject_PT');
}
elseif($user->default_lang == 'de')
{
$body = $newsletter_de;
Input::get('subject_DE');
}
$data = array(
'body' => $body,
'subject' => $subject
);
$from_name = Input::get('from_name');
$from_email = Input::get('from_email');
//QUEUE The Newsletters to send
Mail::queue('admin.newsletters.template1', $data, function($message) use ($user, $subject, $from_name, $from_email)
{
$message->from($from_email, $from_name);
$message->bcc($user->email, $user->name);
$message->subject($subject);
});
} //end foreach
return Redirect::To('admin/newsletters')->with('message', array("1" => "Newsletter enviada com sucesso !"));
}
Thanks a lot ;)
Ensure that the $data array has the information you expect to pass into the view before you call Mail::queue(). It should pass both a $body and $subject variable to your view.
You might also try using Mail::send() instead of Mail::queue() and see if it makes a difference (if you're not using a queueing system). Sometimes the queue() method can trip up when serializing Eloquent models, so if $newsletter_pt or $newsletter_de are Eloquent models they might not make it to the view intact.

Is there a way to remove the return-path that kohana is setting in emails?

Our site uses Kohana and php and we are using sendgrid to send transactional emails. With gmail we're having a ton of spam issues and we only send opt-in emails and have a high open rate. One of the potential issues is that our emails seem to have TWO return-paths in the header:
Is being set by us in Kohana
is being inserted by sendgrid.
Sendgrid says that when they send a message, they take over that 'envelope from' for the sake of handling Bounce management. But we can't figure out a way to have Kohana not insert this. Any suggestions? CODE EXAMPLE:
Kohana uses Swift to send mails. How we send them now is below. We've tried removing reply-to via
$message->headers->set('reply-to', '');
but it doesn't appear to work. Funny enough, setting it to a non-empty value alters it, but there doesn't seem to be a way to get rid of it altogether.
Full code for this function:
/**
* Send an email message.
*
* #param string|array recipient email (and name), or an array of To, Cc, Bcc names
* #param string|array sender email (and name)
* #param string message subject
* #param string message body
* #param boolean send email as HTML
* #param string Reply To address. Optional, default null, which defaults to From address
* #return integer number of emails sent
*/
public static function send($category, $to, $from, $subject, $message, $html = FALSE, $replyto = null)
{
// Connect to SwiftMailer
(email::$mail === NULL) and email::connect();
// Determine the message type
$html = ($html === TRUE) ? 'text/html' : 'text/plain';
// Append mixpanel tracking pixel to html emails
if ($html) {
$mixpanel_token = FD_DEV_MODE ? "08c59f4e26aa718a1038459af75aa559" : "d863dc1a3a6242dceee1435c0a50e5b7";
$json_array = '{ "event": "e-mail opened", "properties": { "distinct_id": "' . $to . '", "token": "' . $mixpanel_token . '", "time": ' . time() . ', "campaign": "' . $category . '"}}';
$message .= '<img src="http://api.mixpanel.com/track/?data=' . base64_encode($json_array) . '&ip=1&img=1"></img>';
}
// Create the message
$message = new Swift_Message($subject, $message, $html, '8bit', 'utf-8');
// Adding header for SendGrid, added by David Murray
$message->headers->set('X-SMTPAPI', '{"category" : "' . $category . '"}');
if (is_string($to))
{
// Single recipient
$recipients = new Swift_Address($to);
}
elseif (is_array($to))
{
if (isset($to[0]) AND isset($to[1]))
{
// Create To: address set
$to = array('to' => $to);
}
// Create a list of recipients
$recipients = new Swift_RecipientList;
foreach ($to as $method => $set)
{
if ( ! in_array($method, array('to', 'cc', 'bcc')))
{
// Use To: by default
$method = 'to';
}
// Create method name
$method = 'add'.ucfirst($method);
if (is_array($set))
{
// Add a recipient with name
$recipients->$method($set[0], $set[1]);
}
else
{
// Add a recipient without name
$recipients->$method($set);
}
}
}
if (is_string($from))
{
// From without a name
$from = new Swift_Address($from);
}
elseif (is_array($from))
{
// From with a name
$from = new Swift_Address($from[0], $from[1]);
}
// Reply To support, not standard in Swift, added by Soham
if (!$replyto) $replyto = $from;
$message->setReplyTo($replyto);
return email::$mail->send($message, $recipients, $from);
}
This is not really a Kohana question but more of a Swiftmailer question, since Swiftmailer comes not standard with the Kohana Framework. According to the Swiftmailer docs you can set/get the Return-Path explicitly:
$message->setReturnPath('bounces#address.tld');
Hopes this helps!
i just wanna say thank you for providing this solution for me, indirectly..
// Adding header for SendGrid, added by David Murray
$message->headers->set('X-SMTPAPI', '{"category" : "INSERT CATEGORY HERE"}');
X-SMTPAPI usage documentation from Sendgrid's Website is sucks..

cakephp pre-fill email form with address

I have a list of email addresses on a page and I would like to add the functionality so that when an email address is clicked it opens up an email form with that email address already pre-filled in the recipient field. How can I do this?
This is the form I have already;
<?php echo $this->Form->create('Email', array('action'=>'email_send.php'));
echo $this->Form->input('email',array('label'=>'To: ')); //i want the email address i clicked on to be automatically placed here.
echo $this->Form->input('message',array('type'=>'textarea','label'=>'Message: '));
echo $this->Form->end('Send'); ?>
Also if anyone has any tips on how I'll structure the email_send.php file and the best way to pass variables and perform validation I could use a hand with that too.
In cake, you could achieve it a little like this.. obviously improvements can be made but it's an example:
EmailsController.php (controller)
function list_emails() {
$this->set('emails', $this->EmailModel->find('all', array('fields' =>
array('id', 'email'))));
}
list_emails.ctp (view)
echo '<ul>';
foreach($emails as $email) {
echo '<li>' . $this->Html->link('Email: ' . $email['EmailModel']['email'],
array('action'=>'process', $email['EmailModel']['id'])) . '</li>'; ?>
}
// generates a list of emails in the format:
// Email: foo#foo.com
echo '</ul>';
EmailsController.php (controller)
function process($email_id = null) {
if(!$email_id) {
$this->redirect(array('action'=>'show_emails')); // no id specified
}
// check if the form has been submit, otherwise, get the info for the view..
$this->EmailModel->id = $email_id;
$email = $this->EmailModel->read();
$this->set('email', $email);
}
and the information is now available to you in your process view.
// echo $this->Form->input('email',array('label'=>'To: ','value'=>$email['EmailModel']['email']));
but it's a lot of work really. And don't forget the value can be always be changed; making this a bit pointless
Try this code:
in controller
$this->set('email',$email); //$email is the mail address from database
in view
echo $this->Form->input('email',array('label'=>'To: ','value'=>$email));
or
you can put email in '$this->request->data' array it will automatically populate in view like this:
you should add this in your controller
$this->request->data['Email']['email'] = 'YOUR_EMAIL_FROM_DATABASE';