Emails not being sent via PHPMailer - arrays

I took over the web development for a company and they've got a feedback form on a couple pages (colorado, prescott, flagstaff and wyoming) that submits form info to an email as a spam filter using PHPmailer. However, they're not receiving emails the way they hoped. I can get emails through all addAddress emails except for the one using $recipeint. Searched and tried everything I could think of including explode and foreach other codes. Can't get this to work. A little help would be great.
$colorado = array( "ColoradoSprings", "Denver", "Boulder" );
$colorado = array_map( 'strtolower', $colorado );
$wyoming = array( "Cheyenne", "Buffalo" );
$wyoming = array_map( 'strtolower', $wyoming );
if ( in_array( $_POST[ 'location' ], $colorado ) || in_array( $_POST[ 'location' ], $wyoming ) )
$recipient = "person1#mail.com, person2#mail.com";
switch ( $_POST[ 'location' ] ) {
case "prescott":
$recipient = "person3#mail.com, person4#mail.com";
break;
case "flagstaff":
$recipient = "person3#mail.com, person4#mail.com";
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.mail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "senderemail#mail.com";
$mail->Password = "password";
$mail->setFrom( 'allmail#mail.com', 'Everyone' );
$mail->addReplyTo( $_POST[ "Email" ], $_POST[ "Name" ] );
$mail->addAddress( 'allmail#mail.com', 'Everyone' );
$mail->addAddress( 'random#mail.com', 'John Doe' );
$mail->addAddress( $recipient, 'Others' );

This is strange code, or incomplete. As it stands it will only attempt to send email if location == 'flagstaff', so you probably need to pay some attention to your conditions.
addAddress only accepts a single address; if you want to send more, call it multiple times in a loop. For example:
$recipients = ["person1#mail.com", "person2#mail.com"];
foreach ($recipients as $recipient) {
$mail->addAddress($recipient);
}

Related

issues with saveAssociated cakephp

I'm having some issues trying to save an article that has 4 pictures. The thing is that i need to use the article id in order to name the pictures like article_id."-"$i
Since I have only 4 pictures per article this $i should be from 1 to 4 or from 0 to three.
Now the problem is that in order to achieve this i need to create and save Article model so i can have an id to use, but then after performing all the scripting to make the thumbs and form the names, when I go Article->saveAssociated() i have two times the article record created!! i tried to set the id to "-1" before saving but nothing...
Any suggestion will be very much appreciated !!!
Code:
public function add() {
if ($this->request->is ( 'ajax' )) {
$this->layout = 'ajax';
} else {
$this->layout = 'default';
}
if ($this->request->is ( 'post' )) {
$this->Article->create ();
$this->request->data ['Article'] ['time_stamp'] = date ( 'Y-m-d H:i:s', time () );
if ($this->Article->save($this->request->data) ) {
for ($i=0; $i<4; $i++){
$img_path = "./images/";
$extension[$i] = end(explode('.', $this->request->data['Image'][$i]['image']['name']));
$this->request->data['Image'][$i]['image'] = array('name'=>$this->Article->id."-".$i, 'tmp_name' => $this->request->data['Image'][$i]['image']['tmp_name']);
// $this->request->data['Image'][$i]['name'] = $this->Article->id."-".$i;
$this->request->data['Image'][$i]['ext']= $extension[$i];
$target_path[$i] = $img_path . basename($this->request->data['Image'][$i]['image']['name'].".".$extension[$i]);
if(!move_uploaded_file($this->request->data['Image'][$i]['image']['tmp_name'], $target_path[$i])) {
die(__ ( 'Fatal error, we are all going to die.' ));
}else{
$this->Resize->img($target_path[$i]);
$this->Resize->setNewImage($img_path.basename($this->request->data['Image'][$i]['image']['name']."t.".$extension[$i]));
$this->Resize->setProportionalFlag('H');
$this->Resize->setProportional(1);
$this->Resize->setNewSize(90, 90);
$this->Resize->make();
}
}
$this->Article->id;
pr($this->Article->id);
$this->Article->saveAssociated($this->request->data, array('deep' => true));
//$this->redirect ( array ('action' => 'view', $this->Article->id ) );
pr($this->Article->id);
exit;
$this->Session->setFlash ( __ ( 'Article "' . $this->request->data ["Article"] ["name"] . '" has been saved' ) );
} else {
$this->Session->setFlash ( __ ( 'The article could not be saved. Please, try again.' ) );
}
}
$items = $this->Article->Item->find ( 'list' );
$payments = $this->Article->Payment->find ( 'list' );
$shippings = $this->Article->Shipping->find ( 'list' );
$this->set ( compact ( 'items', 'payments', 'shippings' ) );
}
Instead of
$this->Article->saveAssociated();
which would save the Article AGAIN, just save the images separately using something like this:
foreach($this->request->data['Image'] as &$image) {
$image['name'] = 'whatever_you_want' . $this->Article->id;
$image['article_id'] = $this->Article->id;
}
$this->Article->Image->save($this->request->data['Image']);
Another option (not necessarily better - just another option) would just be to append the newly-created Article's id to the existing Article array, then saveAssociated(). If the Article has an id in it's data, it will update instead of create. I would suggest the first answer above, but - just brainstorming other options in case this helps for someone's scenario:
// 1) save the Article and get it's id
// 2) append the `id` into the Article array
// 3) do your image-name manipulation using the id
// 4) saveAssociated(), which updates the Article and creates the Images

How do I use fixed fields in CakeDC's csvUpload behavior in Util plugin

I am using the csvUpload behavior of the Utils plugin by CakeDC, on a CakePHP 2.2.1 install.
I have it working great it's processing a rather large csv successfully. However there are two fields in my table / Model that would be considered fixed, as they are based on ID's from from associated models that are not consistent. So I need to get these fixed values via variables which is easy enough.
So my question is, how do I use the fixed fields aspect of csvUpload? I have tried that following and many little variation, which obviously didn't work.
public function upload_csv($Id = null) {
$unique_add = 69;
if ( $this->request->is('POST') ) {
$records_count = $this->Model->find( 'count' );
try {
$fixed = array('Model' => array('random_id' => $Id, 'unique_add' => $unique_add));
$this->Model->importCSV($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
} catch (Exception $e) {
$import_errors = $this->Model->getImportErrors();
$this->set( 'import_errors', $import_errors );
$this->Session->setFlash( __('Error Importing') . ' ' . $this->request->data['Model']['CsvFile']['name'] . ', ' . __('column name mismatch.') );
$this->redirect( array('action'=>'import') );
}
$new_records_count = $this->Model->find( 'count' ) - $records_count;
$this->Session->setFlash(__('Successfully imported') . ' ' . $new_records_count . ' records from ' . $this->request->data['Model']['CsvFile']['name'] );
$this->redirect(array('plugin'=>'usermgmt', 'controller'=>'users', 'action'=>'dashboard'));
}
}
Any help would be greatly appreciated as I have only found 1 post concerning this behavior when I searching...
I made my custom method to achieve the same task. Define the following method in app\Plugin\Utils\Model\Behavior
public function getCSVData(Model &$Model, $file, $fixed = array())
{
$settings = array(
'delimiter' => ',',
'enclosure' => '"',
'hasHeader' => true
);
$this->setup($Model, $settings);
$handle = new SplFileObject($file, 'rb');
$header = $this->_getHeader($Model, $handle);
$db = $Model->getDataSource();
$db->begin($Model);
$saved = array();
$data = array();
$i = 0;
while (($row = $this->_getCSVLine($Model, $handle)) !== false)
{
foreach ($header as $k => $col)
{
// get the data field from Model.field
$col = str_replace('.', '-', trim($col));
if (strpos($col, '.') !== false)
{
list($model,$field) = explode('.', $col);
$data[$i][$model][$field] = (isset($row[$k])) ? $row[$k] : '';
}
else
{
$col = str_replace(' ','_', $col);
$data[$i][$Model->alias][$col] = (isset($row[$k])) ? $row[$k] : '';
}
}
$is_valid_row = false;
foreach($data[$i][$Model->alias] as $col => $value )
{
if(!empty($data[$i][$Model->alias][$col]))
{
$is_valid_row = true;
}
}
if($is_valid_row == true)
{
$i++;
$data = Set::merge($data, $fixed);
}
else
{
unset($data[$i]);
}
}
return $data;
}
And you can use it using:
$csv_data = $this->Model->getCSVData($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
Here $csv_data will contain an array of all of those records from the csv file which are not empty and with the fixed field in each record index.
So as I was telling Arun, I answered my own question and figured it out. I was looking to broad instead of really examining what was in front of me. I started running some debugging and figured it out.
First of all, $unique_add = 69 is seen as an int, duh. In order for it to be added to the csv it need to viewed as a string. So it simply becomes, $unique_add = '69'.
I couldn't enter the value of $Id directly into the fixed array. So I just had to perform a simple find to get the value I needed.
$needed_id = $this->Model->find('first', array(
'condition'=>array('Model.id'=>$Id)
)
);
$random_id = $needed_id['Model']['id'];
Hopefully this won't be needed to help anyone because hopefully no one else will make this silly mistake. But one plus... Now there's actually more than one post on the internet documenting the use of fixed fields in the CakeDC Utils plugin.

How do I send an email with an attachment in CakePHP 2.0?

I'm trying to send an email with an attachment using CakePHP 2.0.
The file is submitted by the user via a form.
So far I have:
App::uses('CakeEmail', 'Network/Email');
$email = new CakeEmail();
$email->attachments = array($this->data['Opportunity']['resume_file']['tmp_name']);
$email->viewVars(array('name' => $this->data['Opportunity']['name']));
$email->template('application')
->emailFormat('html')
->to(TEST_CONTACT)
->from(EMAIL_CONTACT)
->subject('New application received')
->send();
The email sends and looks fine, but there is no attachment.
What am I doing wrong?
For some reason CakePHP won't do attachments unless you state the
filePaths first.
I have the same problem and I did not manage to find many answer to
this question. It took me a while to solve the problem, to clarify,
I got it working by
$this->Email->filePaths = array('/home/username/');
$this->Email->attachments =array('article_button.png');
$this->Email->to = 'em...#email.co.uk';
$this->Email->subject = 'Something';
$this->Email->replyTo = $client['Client']['email'];
$this->Email->from = $client['Client']['email'];
$this->Email->sendAs = 'html';
if($this->Email->send('Testing', null, null)){
die('Email Sent!');
}else{
die('Failed to send email');
}
http://groups.google.com/group/cake-php/browse_thread/thread/93a9c9467733fe38?pli=1
Put below script in AppController.php
function sendMailWithAttachment($template = null, $to_email = null, $from_email = null, $subject = null, $contents = array()) {
$from_email = 'noreply#xyz.com';
$email = new CakeEmail();
$result = $email->template($template, 'default')
->emailFormat('html')
->to($to_email)
->from($from_email)
->subject($subject)
->attachments('your-server-path/filename.extenstion')
->viewVars($contents);
if ($email->send('default')) {
return true;
}
return false;
}
After that just call the method sendMailWithAttachment() in any controller like
$this->sendMailWithAttachment('tmpl', 'test#abc.com','noreply#xyz.com', 'Subject', $tmpl_DATA_IN_ARRAY);

Receiving email takes upto 3 hours

This is my code I am facing problem in receiving mail it take up to 3 hours. Please help me.
function sendMail($to, $subject, $template, $from,$params,$attachmentFile=array(),$layout='default') {
foreach($params as $key=>$val) {
$this->set("".$key."",$val);
}
$this->Email->sendAs = 'html';
if (is_array($to))
$this->Email->to = $to;
else
$this->Email->to = "<".$to.">";
//$this->Email->to;
$this->Email->subject = $subject;
$this->Email->layout = $layout;
$this->Email->replyTo = "test#gmail.com";
$this->Email->from = "test#gmail.com";
$this->Email->attachments = $attachmentFile;
$this->Email->template = $template; // note no '.ctp'
//echo "<pre>";print_r($this->Email);
//die();
if(!$this->Email->send()) {
return 0;
}
else {
return 1;
}
}
Email is not instant. Sometimes a normal email will take quite a while. I would check what server (be it an SMTP server or plain old sendmail) you are using though and try to send mail through that normally to see how long it takes to make sure that it's not a cakephp configuration issue.

codeigniter file upload - optional?

I'm sure this is simple but I can't see how to make uploading a file with CI optional.
If you leave the file input box empty, the error "You didn't choose an upload file" appears.
The reason I want it to be optional is that my form edits a directory type listing, and I don't need to upload the image each time I edit the listing.
Is there a way to remove the "required" error handling on the file class
Use the following:
<?php if ( $_FILES AND $_FILES['field_name']['name'] )
{
// Upload the file
}
codeigniter file upload optionally ...works perfect..... :)
---------- controller ---------
function file()
{
$this->load->view('includes/template', $data);
}
function valid_file()
{
$this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');
if ($this->form_validation->run()==FALSE)
{
$this->file();
}
else
{
$config['upload_path'] = './documents/';
$config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile',FALSE))
{
$this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());
if($_FILES['userfile']['error'] != 4)
{
return false;
}
}
else
{
return true;
}
}
i just use this lines which makes it optionally,
if($_FILES['userfile']['error'] != 4)
{
return false;
}
$_FILES['userfile']['error'] != 4 is for file required to upload.
you can u make it unneccessory by using $_FILES['userfile']['error'] != 4 , then it will pass this error for file required and
works great with other types of errors if any by using return false ,
hope it works for u ....
Use this code in the controller before calling do_upload()
if (is_uploaded_file($_FILES['field_name']['tmp_name'])) {
// your code here
}
Use This Code :-
$config['upload_path'] = 'assets/img/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
// Upload the file
if ($this->upload->do_upload('Image')){
$dataimage = $this->upload->data();
$data = array(
'image' => $dataimage['file_name'],
'UserName' => $this->input->post('UserName'),
'Password' => $this->input->post('Password'),
'xid' => $this->input->post('xid')
);
}
else{
/*$out['msg'] = show_err_msg($this->upload->display_errors());
echo json_encode($out);
exit();*/
$data = array(
'image' => NULL,
'UserName' => $this->input->post('UserName'),
'Password' => $this->input->post('Password'),
'xid' => $this->input->post('xid')
);
}

Resources