Code Igniter -> attach email - php

How do you use the email->attach function?
I can't figure what is happen, cos when i put the code for email->attach the mesage came in blank(the mail body) and there is no attach.
If i remove that code line, everything come back to normal..
thank you
my controller (sendmail.php)
<?php
class Sendmail extends Controller {
function __construct() {
parent::Controller();
$this->load->library('email');
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('validation');
}
function index() {
$info = array (
'nome' => $this->input->post('nome'),
'mail' => $this->input->post('email'),
'motivo' => $this->input->post('motivo'),
'mensagem' => $this->input->post('mensagem'),
'anexo' => $this->input->post('upload'),
);
$this->load->library('email');
$this->email->set_newline('\r\n');
$this->email->clear();
$this->email->from($info['mail'], $info['nome']);
$this->email->to('example#mai.com');
/* $this->email->cc(''); # não é preciso */
$this->email->subject($info['motivo']);
$this->email->message($info['mensagem']);
$this->email->attach($info['anexo']);
if ($this->email->send() ) {
echo 'sent';
}
else {
$this->load->view('formulario');
# show_error( $this->email->print_debugger() );
}
}
}
?>
my view (formulario.php)
<?php
echo form_open_multipart('davidslv/index.php/sendmail');
?>
<label for="nome">nome</label>
<input type="text" name="nome" id="nome" required />
<label for="email">email</label>
<input type="text" name="email" id="email" required />
<label for="assunto">assunto</label>
<select name="motivo">
<option value="motivo1">motivo1</option>
<option value="motivo2">motivo2</option>
<option value="motivo3">motivo3</option>
</select>
<p> <label for="mensagem">mensagem</label>
<textarea name="mensagem" id="mensagem" rows="8" cols="30" required></textarea>
</p>
<label for="upload">documento</label>
<input type="file" id="upload" name="upload" size="18"/>
<input type="submit" id="enviar" name="enviar" value="Enviar!" />
</form>

You can not directly attach a file from the upload field of your form to an email. You can only attach files to your email from your server, so you need to upload the file from the form with CIs upload library: $this->upload->do_upload() to your server into some directory. the upload library needs to be configured, which file types are allowed etc. if the upload was successful, the do_upload function returns extensive data about where the file is stored. you can use the 'full_path' index from the array to attach this file to the email. then send the mail. after that you may delete the file from your server. Here are some code fragments that might help.
$this->load->library('upload');
if($_FILES['upload']['size'] > 0) { // upload is the name of the file field in the form
$aConfig['upload_path'] = '/someUploadDir/';
$aConfig['allowed_types'] = 'doc|docx|pdf|jpg|png';
$aConfig['max_size'] = '3000';
$aConfig['max_width'] = '1280';
$aConfig['max_height'] = '1024';
$this->upload->initialize($aConfig);
if($this->upload->do_upload('upload'))
{
$ret = $this->upload->data();
} else {
...
}
$pathToUploadedFile = $ret['full_path'];
$this->email->attach($pathToUploadedFile);
...
$this->email->send();
...
}
...
Hope this helped...

$this->email->attach()
Enables you to send an attachment. Put
the file path/name in the first
parameter. Note: Use a file path, not
a URL. For multiple attachments use
the function multiple times. For
example:
$this->email->attach('/path/to/photo1.jpg');
$this->email->attach('/path/to/photo2.jpg');
$this->email->attach('/path/to/photo3.jpg');
$this->email->send();
Codeigniter Email Class

This is Absolutely right code Please Try
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|jpeg|png|txt|php|pdf';
$config['max_size'] = '9000';
$config['encrypt_name'] = true;
$image_data = $this->upload->data();
$fname=$image_data[file_name];
$fpath=$image_data[file_path].$fname;
$this->email->attach($fpath);

step 1:You can not directly attach a file from the upload field of your form to an email. You can only attach files to your email from your server, so you need to upload the file from the form with CIs upload library:
$this->upload->do_upload() to your server into some directory.
step 2:
$file=upload file;
$file_path='uploaded directory on your server(eg:uploads/career)'.$file;
step 3:just include
$this->email->attach($file_path);
$this->email->send();

This is a late update, but it might be useful.
It was said twice
"You can not directly attach a file from the upload field of your form
to an email"
. However, this works fine in Codeigniter 3.0
foreach ($_FILES as $key => $file)
{
if ($file['error'] == 0)
{
$this->email->attach($file['tmp_name'], '', $file['name']);
}
}
(Though, the email is not sent and no errors are shown, if there are two files with the same name)

Related

Codeigniter file upload from a form without ajax/jquery/javascript

Context : I am updating user_profile data after user registration using form #updateprofileform ,
i am able to process all other form fields using standard validations and insert/update using user_model.
issue is with resume field which should accept a file as input type and upload to server and store its path on server (say http://domain/uploads/$filename) to a column in database.
Expectation A logged in user , able to view his details(if already in database),update details if incomplete profile.
Question : I found methods how we can upload a file to server using CI framework or how we can upload a file in this context using jquery/ajax/java-script. But i am looking for simple solution for above problem which can do the job with out dependency on technologies.
user_profile.php (view)
<table>
<form class="row" name="updateprofile" action = "<?php echo base_url()?>user/user_profile" method="POST">
<tr>
<td><label for="email">Email ID</label></td><td><input class="form-control" name="email" placeholder="Email-ID" type="text" value="<?php if (isset($email)) echo $email;?>" /> <span style="color:red"><?php echo form_error('email'); ?></span></td>
</tr>
<tr>
<td><label for="resume">Resume</label></td>
<td>
<input name="resume" placeholder="Upload resume" type="file" value="<?php if (isset($resume)) echo $resume;?>" />
<span style="color:red"><?php echo form_error('resume'); ?>
</span>
</td>
</tr>
<tr>
<td></td>
<td><div class="col-md-6 col-lg-3"> <button type="submit" class="btn btn--primary type--uppercase" name="updateprofile" value="updateprofile" formaction = "<?php echo base_url()?>user/user_profile">Update Profile</button> </div></td>
</tr>
</form>
</table>
user_controller
class User extends CI_Controller {
public function __construct()
{
parent::__construct();
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "doc|docx|pdf",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
//'max_height' => "768",
//'max_width' => "1024"
);
$this->load->library('upload', $config);
}
public function user_profile()
{
$resume = $this->input->post('resume');
if ($this->user_model->set_user_profile($id,FALSE) )
{ if($this->do_upload($resume)){
$this->session->set_flashdata('msg_success','Updation Successful!');
echo validation_errors();}
}
else
{
$this->session->set_flashdata('msg_error','Error! Please try again later.');
redirect('user/user_profile');
}
public function do_upload($resume){
if($this->upload->do_upload($resume))
{
$data = array('upload_data' => $this->upload->data($resume));
$this->load->view('user_profile',$data);
}
else
{
$error = array('error' => $this->upload->display_errors($resume));
$this->load->view('user_profile', $error);
}
}
currently always error.... Error! Please try again later . so appreciate some pointers here to upload both file and form data together and save file location in database without ajax/jquery.
Thanks
Change the form definition to the following:
<form class="row" action = "<?php echo base_url('user/user_profile'); ?>" method="post" enctype="multipart/form-data" name="updateprofile" >
Resolved !
4 important steps needed and some missing in most Q&A in all other posts to make this complete.will share samplecode in github when i get sometime.
form encryption type must be enctype="multipart/form-data" (thanks
to #Javier Larroulet and #dexter )
do_upload method by default look for file field with name=userfile
(Thanks to #Alex ! for referencing this), so, if you have your
form's file field name different than userfile, then only it is
required to mention as do_upload('filefieldname') otherwise
optional
loading of upload library configuration is tricky.. if you
autoupload the upload library , then load->library upload config will fail!, you
just =>initialize it.$this->upload->initialize($config); if you
are not using autoload for upload library, then yes, you can load it
from controller. $this->load->library('upload', $config);
when ever, you are using upload, you have to catch the form validation errors
and data errors separately (again thanks to #Alex for pointing this)
a nice documentation is given from codeigniter at this link (https://www.codeigniter.com/userguide3/libraries/file_uploading.html#the-controller ) but doesn't highlight routine mistakes.
hope this post help someone not to waste another 24 hours to debug.

How to attach file(s) in php mailer within same php page?

I am using php mailer to send emails with attachments. I want files to be attached within the same page. my form,
<form method="POST" action="#" enctype="multipart/form-data">
<label>Files to upload:</label>
<input type="file" name="files[]" multiple/>
<button type="submit" name="btnSend" value="Send">Send</button>
</form>
And my php code snippet is,
if (isset($_POST['btnSend'])) {
$mail = new mymailer();
include DOC_ROOT . 'include/contact-email-template.php';
$mailArray = array("my-email-address");
$subject = "Contact Form";
$from = $email;
$mail->sendMail($from, $mailArray, $subject, $admin_template);
$emailsent = 1;
$mod_email = "Success";
/* redirect to home after success */
if ($emailsent == 1) {
unset($_POST['firstname']);
unset($_POST['lastname']);
unset($_POST['email']);
unset($_POST['phone']);
unset($_POST['message']);
$mod_email = "Show";
}
}
How can I attach the file(s) I chose from input type="file"
Please help.
PS: Emails are sending fine with this code even when I set the action to external file and save chosen image in the disk and attach them. I just want to know how to attach files within the same page.
You can you $_FILES and attach the chosen file into mail body on the same page
if(!empty($_FILES)){
$i = 0;
foreach($_FILES['files']['tmp_name'] as $file){
echo $mail->AddAttachment($_FILES['files']['tmp_name'][$i], $_FILES['files']['name'][$i]);
$i++;
}
}

Send files with phpmailer before uploading them?

I have a problem with sending emails with attachment by the phpmailer script. I have a working code if I want to add a single file to the mail. But when it comes to multiple files, it looks like they are not even uploaded.
My code for a single file:
if (isset($_FILES['file']) &&
$_FILES['file']['error'] == UPLOAD_ERR_OK)
{
$mail->AddAttachment($_FILES['file']['tmp_name'],
$_FILES['file']['name']);
if(!$mail->Send())
{
header("Location: " . $returnErrorPage);
}
else
{
header("Location: " . $returnHomePage);
}
}
I tried a few codes that should loop through all files in $_FILES without success. Then I tested the following code:
$count = count($_FILES['file']['tmp_name']);
echo $count;
it returns 0. I know that $_FILES is empty, but I dont know the reason for that. Do I need to buffer the files or something like that?
EDIT:
here is my html code which sent the files and other data to the script:
<form id="form_907007" class="appnitro" method="post" action="server/phpmailer.php"
enctype="multipart/form-data">
<p>Choose data (txt, html etc.):<br>
<input name="file" type="file" size="50" maxlength="100000" multiple>
</p>
</form>
The solution of my problem is based on the idea from Synchro, upload the files first and then send the email.
In my html code I had to change this line:
<input name="file" type="file" size="50" maxlength="100000" multiple>
<input name="file[]" type="file" size="50" maxlength="100000" multiple>
it is important to do this little step to reach each file you want to upload later in php.
The second step is to loop through all files an store them on your server. This is the way I did that:
foreach ($_FILES["file"]["error"] as $key => $error){
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"][$key];
$name = $_FILES["file"]["name"][$key];
move_uploaded_file($tmp_name," server/data/$name"}
In the next step I check if the files are uploaded successful, if return = TRUE I add them as attachement to the mail:
if(move_uploaded_file($tmp_name,"server/data/$name" ))
{
$mail->AddAttachment("server/data/$name");
}
If everything went well I can delete the files after I have send the mail:
if($mail->Send()){
foreach ($_FILES["file"]["error"] as $key => $error)
{
$name = $_FILES["file"]["name"][$key];
unlink("$name");
}
header("Location: " . $returnPage);
exit;}
Thank you for all your help!

store the $_POST form data if page fail to submit

I am using codeigniter. I am currently having a very simple form (nothing but input fields) that submits to the controller for processing.
That all doesn't matter, but what I am asking about is that I have an upload file in the form also. so the upload function will check for file size and type and so on and gives error if not complying. when that happens and I choose another file that matches the requirement, I submit but nothing goes to next page but the uploaded file and its details while the other fields are not posted or are blank.
It is as if the post is not cached and when I select new file to upload and its okay, it checks $_POST of those fields and they are empty. How can I check for that so that to make sure all fields contain values?
Thank you and more than happy to help elaborating.
To repopulate the fields you can use the set_value function.
set_value()
Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The second (optional) parameter allows you to set a default value for the form.
First you check if the form validation and upload was successful.
If both are successful we redirect the user to a new page.
If one of these is unsuccessful we add the error message to your data array which we can access in our view and display our form.
Controller
public function signup()
{
// Data array
$data = array();
// Load form validation libary
$this->load->library('form_validation');
// Load upload library and set configuration
$config['upload_path'] = './uploads/';
$this->load->library('upload', $config);
// Set the required fields
$this->form_validation->set_rules('first_name', 'First name', 'required');
if ($this->form_validation->run() == TRUE)
{
// If upload was succesfull
if ($this->upload->do_upload())
{
$upload_data = $this->upload->data();
// Build array to store in database
$save_data = array(
'first_name' => $this->input->post('first_name'),
'image' => $upload_data['file_name']
);
// Send data to your model to process
$this->your_model->save($save_data);
// Redirect to success page
redirect('registration_succes');
}
else
{
// Upload failed, set error
$data['error'] = $this->upload->display_errors();
}
}
else
{
// Form validation failed, set error
$data['error'] = validation_errors();
}
// Display the form by default or on error
$this->load->view('myform', $data);
}
In our view we repopulate the fields with the submitted values using the set_value function.
View ( myform )
<?php echo form_open_multipart('signup');?>
<fieldset>
<?php if( isset($error) && ! empty($error) ): ?>
<div class="error"><?php echo $error; ?></div>
<?php endif; ?>
<p>
<label>First name</label>
<input type="text" name="first_name" value="<?php echo set_value('first_name'); ?>" />
</p>
<p>
<label>File</label>
<input type="file" name="userfile" size="20" />
</p>
<p>
<input type="submit" />
</p>
</fieldset>
</form>

Codeigniter validating file upload and text input in one form

I have a form with text inputs and a file input. What is a proper way validate both input types using Codeigniter's validation library? I found some solutions but they don't work properly or seem like an overkill (creating new libraries or modifying CI system files).
In my view I'm using 1 multipart form and displaying both text validation error and upload errors.
Here is what I have so far in my Controller...
function create() //create new post
{
$this->form_validation->set_rules('content', 'Entry', 'trim|required|xss_clean');
$this->form_validation->set_rules('category_id', 'Category', 'trim|required|xss_clean|integer');
//Text input fields
if ($this->form_validation->run() == FALSE)
{
$this->load->view('new_post');
}
else
{
$config['upload_path'] = './uploads/posts/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '800'; //in KB
$this->load->library('upload', $config);
//File Upload
if (! $this->upload->do_upload())
{
$upload_error['upload_error'] = array('error' => $this->upload->display_errors());
$this->load->view('my_view', $upload_error);
return FALSE;
}
//Add to database
$data = array (
'user_id' => $this->tank_auth->get_user_id(),
'category_id' => $this->input->post('category_id'),
'content' => $this->input->post('content')
);
$this->Posts_model->create_post($data);
$this->session->set_flashdata('success', 'Post_added!');
redirect('posts');
}
}
I keep getting You did not select a file to upload. in my view.
What is the name of your file input? do_upload() is expecting it by default to be 'userfile', however if you have something like <input type="file" name="image"... you will need to call $this->upload->do_upload('image')
You also need to make sure the form is set to multipart - http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
You're using CodeIgniter's helpers correctly, this could be running more into a PHP problem then a CodeIgniter problem.
It looks like your file may be too big for your PHP configuration? PHP doesn't seem to be passing the file along to you. Create a php_info() file and see what UPLOAD_MAX_FILESIZE is set to?
Also, make sure you have the extension and mime type pair set in application/config/mimes.php.
default codeigneter upload class is $this->upload->do_upload('field_name = userfile') , so you can set the name of field file you make or you use default codeigneter name field of file , if you want to change the name field for file type in your form , please check how codeigneter made setting for that class, actually is simple class and easy to use.., because that class need parameter name of file
Form field validation with file upload using codeigniter
Controller: Upload.php
Note: create folder uploads at base level
Upload folder store file..
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
//$this->load->view('upload_form', array('error' => ' ' ));
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
//Text input fields
if ($this->form_validation->run() == FALSE)
{
$this->load->view('upload_form');
}
else
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
}
?>
Form:(upload.form.php)
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open_multipart();?>
Title: <input type="text" name="title" size="30" /><br/>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
**upload_success.php**
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open_multipart();?>
Title: <input type="text" name="title" size="30" /><br/>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>

Categories