I am trying to send email on codeigniter with attach file.
I always receive email successfully. However , I never receive with attach file. Below is code and highly appreciate for all comments.
$ci = get_instance();
$ci->load->library('email');
$config['protocol'] = "smtp";
$config['smtp_host'] = "ssl://smtp.gmail.com";
$config['smtp_port'] = "465";
$config['smtp_user'] = "test#gmail.com";
$config['smtp_pass'] = "test";
$config['charset'] = "utf-8";
$config['mailtype'] = "html";
$config['newline'] = "\r\n";
$ci->email->initialize($config);
$ci->email->from('test#test.com', 'Test Email');
$list = array('test2#gmail.com');
$ci->email->to($list);
$this->email->reply_to('my-email#gmail.com', 'Explendid Videos');
$ci->email->subject('This is an email test');
$ci->email->message('It is working. Great!');
$ci->email->attach( '/test/myfile.pdf');
$ci->email->send();
$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:
public function setemail()
{
$email="xyz#gmail.com";
$subject="some text";
$message="some text";
$this->sendEmail($email,$subject,$message);
}
public function sendEmail($email,$subject,$message)
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'abc#gmail.com',
'smtp_pass' => 'passwrd',
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('abc#gmail.com');
$this->email->to($email);
$this->email->subject($subject);
$this->email->message($message);
$this->email->attach('C:\Users\xyz\Desktop\images\abc.png');
if($this->email->send())
{
echo 'Email send.';
}
else
{
show_error($this->email->print_debugger());
}
}
i have this problem before , the problem with the path file , so i change the path file to
$attched_file= $_SERVER["DOCUMENT_ROOT"]."/uploads/".$file_name;
$this->email->attach($attched_file);
And it works fine with me
With Codeigniter 3.1.0 I had same problem. Seems that there is missing a "\r\n":
Content-Type: application/pdf; name="test.pdf"<br>
Content-Disposition: attachment;<br>
Content-Transfer-Encoding: base64<br>
JVBERi0xLjYNJeLjz9MNCjQzNyAwIG9iag08PC9MaW5lYXJpemVkIDEvTCA3OTUyMTYvTyA0Mzkv<br>
RSA2ODEwODcvTiA0L1QgNzk0ODA3L0ggWyA1NjQgMjYxXT4+DWVuZG9iag0gICAgICAgICAgICAg<br>
should be:
Content-Type: application/pdf; name="test.pdf"<br>
Content-Disposition: attachment;<br>
Content-Transfer-Encoding: base64<br>
<br>
JVBERi0xLjYNJeLjz9MNCjQzNyAwIG9iag08PC9MaW5lYXJpemVkIDEvTCA3OTUyMTYvTyA0Mzkv<br>
RSA2ODEwODcvTiA0L1QgNzk0ODA3L0ggWyA1NjQgMjYxXT4+DWVuZG9iag0gICAgICAgICAgICAg<br>
I changed line 725 in system/libraries/Email from
'content' => chunk_split(base64_encode($file_content)),<br>
to
'content' => "\r\n" . chunk_split(base64_encode($file_content)),<br>
It works for me, but not the perfect fix.
Try putting the full path in $ci->email->attach();
On windows this would like something like
$ci->email->attach('d:/www/website/test/myfile.pdf');
This method has worked well for me in the past.
If you want to send attachment in email Without uploading file on server, please refer below.
HTML View file
echo form_input(array('type'=>'file','name'=>'attach_file','id'=>'attach_file','accept'=>'.pdf,.jpg,.jpeg,.png'));
Controller file
echo '<pre>'; print_r($_FILES); shows below uploaded data.
[attach_file] => Array
(
[name] => my_attachment_file.png
[type] => image/png
[tmp_name] => C:\wamp64\tmp\php3NOM.tmp
[error] => 0
[size] => 120853
)
We will use temporary upload path [tmp_name] where attachment is uploaded, because we DO NOT want to upload attachment file on server.
$this->email->clear(TRUE); //any attachments in loop will be cleared.
$this->email->from('your#example.com', 'Your Name');
$this->email->to('someone#example.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
//Check if there is an attachment
if ( $_FILES['attach_file']['name']!='' && $_FILES['attach_file']['size'] > 0 )
{
$attach_path = $_FILES['attach_file']['tmp_name'];
$attach_name = $_FILES['attach_file']['name'];
$this->email->attach($attach_path,'attachment',$attach_name);
}
$this->email->send();
use path helper
$this->load->helper('path');
$path = set_realpath('./images/');
on email line
$this->email->attach($path . $your_file);
here i am using phpmailer to send mail
here full code is mention below
$this->load->library('My_phpmailer');
$mail = new PHPMailer();
$mailBody = "test mail comes here2";
$body = $mailBody;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "ssl://smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 1;// enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true;// enable SMTP authentication
$mail->Host = "ssl://smtp.gmail.com"; // sets the SMTP server
$mail->Port = 465;// set the SMTP port for the GMAIL server
$mail->Username = "YourAccountIdComesHere#gmail.com"; // SMTP account username
$mail->Password = "PasswordComesHere";// SMTP account password
$mail->SetFrom('SetFromId#gmail.com', 'From Name Here');
$mail->AddReplyTo("SetReplyTo#gmail.com", "Reply To Name Here");
$mail->Subject = "Mail send by php mailer";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment($cdnStorage . '/' . $fileName);
$address ='WhomeToSendMailId#gmail.com';
$mail->AddAddress($address, "John Doe");
if (!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
Here Is Full Source Code
$validation_rules = array(
array('field' => 'name', 'rules' => COMMON_RULES),
array('field' => 'email', 'rules' => COMMON_RULES),
array('field' => 'message', 'rules' => COMMON_RULES),
);
$this->validation_errors($validation_rules);
$name = $this->input->post('name');
$email = $this->input->post('email');
$message = $this->input->post('message');
$this->load->library('email');
//upload file
$attachment_file = "";
if (!empty($_FILES) && isset($_FILES["attachment_file"])) {
$image_name = $_FILES["attachment_file"]['name'];
$ext = pathinfo($image_name, PATHINFO_EXTENSION);
$new_name = time() . '_' . $this->get_random_string();
$config['file_name'] = $new_name . $ext;
$config['upload_path'] = "uploads/email/";
$config['allowed_types'] = "*";
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('attachment_file')) {
$finfo = $this->upload->data();
$attachment_file = base_url() . 'uploads/email/' . $finfo['file_name'];
} else {
$error = $this->upload->display_errors();
$this->msg = $error;
$this->_sendResponse(5);
}
}
$this->email->from($email, "$name")
->to("example#gmail.com")
->subject("FeedBack From $name")
->message($message)
->attach($attachment_file);
if ($this->email->send()) {
// temp pass updated.
$this->msg = "Email send successfully.";
$this->_sendResponse(1);
} else {
$this->msg = "Internal server error/Something went wrong.";
$this->_sendResponse(0);
}
$this->load->library('email'); // Loading the email library.
$this->email->clear(TRUE);
$this->email->from($user_email, $name);
$this->email->to('email#gmail.com');
$this->email->subject("Some subject");
$this->email->message("Some message");
if($_FILES['userfile']['name']!='' && $_FILES['userfile'['size'] > 0){
$attach_path = $_FILES['userfile']['tmp_name'];
$attach_name = $_FILES['userfile']['name'];
$this->email->attach($attach_path,'attachment',$attach_name);
}
$this->email->send();
Related
I'm new to the zend framework.
I have a code to send a mail and it's working, but the message is not received by the customer side, but it returns that the mail was sent successfully. Can you teach me how to work with zend_email?
public function sendMailStatements($qid,$emails=array()) {
require_once 'Zend/Mail.php';
require_once 'Zend/Mail/Transport/Smtp.php';
try {
$config = array('ssl' => 'ssl',
'port' => 465,
'auth' => 'login',
'host' => '127.0.0.1',
'username' => 'username#gmail.com',
'password' => 'password');
$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
Zend_Mail::setDefaultTransport($transport);
$mail = new Zend_Mail();
$mail->setSubject("Quotation LL Sports Exim");
$body="Dear Sir/Madam<br>Kindly find the attached Quotation and give us your Feed BAck";
$mail->setBodyHtml($body);
foreach ($emails as $email):
$mail->addTo($email);
endforeach;
var_dump($emails);
if($qid!=""):
$fullBaseUrl = getcwd();
$full_path = $fullBaseUrl . "\\pdfs\\" .$qid.".pdf";
$content = file_get_contents($full_path); // e.g. ("attachment/abc.pdf")
$attachment = new Zend_Mime_Part($content);
$attachment->type = 'application/pdf';
$attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$attachment->encoding = Zend_Mime::ENCODING_BASE64;
$attachment->filename ="quotation.pdf"; // name of file
$mail->addAttachment($attachment);
endif;
$mail->send($transport);
return true;
} catch (Zend_Exception $e) {
echo "Caught exception: " . get_class($e) . "\n";
echo "Message: " . $e->getMessage() . "\n";
exit;
// Other code to recover from the error
}
}
Please let me know where I did wrong?
Thanks in advance.
My website using webform in drupal 7 application.
I have two queries
I can added a list for To email recipients one message. Email will receiving all the recipients but mails sending individual. I cant see in the to list group.
How to set multiple CC email recipients one message ? Here am using 'CC' => 'xx#yyyy.com, xx1#yyyy1.com, xx2#yyyy2.com' in theme_mail_headers under "$headers.
function MODULENAME_mail($key, &$message, $params) {
if($key === 'MODULEcase') {
$header = array(
'MIME-Version' => '1.0',
'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
'Content-Transfer-Encoding' => '8Bit',
'X-Mailer' => 'Drupal',
'Cc' => implode(',', $params['Cc']),
);
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
foreach ($headers as $key => $value) {
$message['headers'][$key] = $value;
}
break;
}
}
Then prepare data and pass to drupal_mail function
$mail_content = "Hello There!";
$params = array('body' => $mail_content);
$params['cc'] = array(
'cc_user1#example.com',
'cc_user2#example.com',
'cc_user3#example.com',
);
$to = 'touser#example.com';
$from = 'no-reply#example.com';
$mail = drupal_mail('MODULENAME', 'MODULEcase', $to, language_default(), $params, $from);
This is it. Enjoy :-)
I wish to send HTML emails. I tried using mime.php but could not get it working. Below is my working text email code:
<?php
$subject="hello-test";
$body="<html><body><h1>message body</h1></body></html>";
$em_arr=array("email#example.com");
foreach ($em_arr as $to_address)
{
require_once '/usr/local/share/pear/Mail.php';
$headers = array (
'Content-Type:text/html;charset=UTF-8',
'From' => 'Test <test#example.com>',
'To' => $to_address,
'Subject' => $subject);
$smtpParams = array (
'host' => '<smtp host address>',
'port' => 587,
'auth' => true,
'username' => '<uname>',
'password' => '<password>'
);
// Create an SMTP client.
$mail = Mail::factory('smtp', $smtpParams);
// Send the email.
$result = $mail->send($to_address, $headers, $body);
if (PEAR::isError($result)) {
echo("Email not sent. " .$result->getMessage() ."\n");
} else {
echo("Email sent to ".$to_address."\n");
}
}
?>
Please let me know how can I send HTML emails.
I had to replace the Content header line to:
'Content-Type' => "text/html; charset=UTF-8",
That was the mistake above. It is working fine now.
i run a cloud app (using CakePHP) on Rackspace and i wanna send emails using cakephp.
I used this: https://github.com/kochb/cakephp-mailgun
but it returns me an
"Could not send email.
Error: An Internal Error Has Occurred."
error.
The way i try to send an email is with the following code:
$Email = new CakeEmail();
$from = $this->request->data['Mail']['from'];
$to = ($this->request->data['Mail']['to']);
$subject = $this->request->data['Mail']['subject'];
$message = $this->request->data['Mail']['message'];
$Email->sender($from, 'TestName');
$Email->from($from)
->bcc($to)
->replyTo($from)
->subject($subject)
->send($message);
$this->Session->setFlash('On the way to recipient');
$this->redirect(array('action' => 'index'));
I have edited the Config/Email.php file inserting the MailGun API credentials etc.
What's possibly going on? Can you find out why this happens?
Thanks in advance!
(I was having the same errors you were)
The BasicTransport didn't have the right "pre-processing" nor the appropriate response handling.
I copied over the functionality from CurlTransport and it works for me now.
Specifically, we needed:
$post = array();
$post_preprocess = array_merge(
$email->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject')),
array(
'text' => $email->message(CakeEmail::MESSAGE_TEXT),
'html' => $email->message(CakeEmail::MESSAGE_HTML)
)
);
foreach ($post_preprocess as $k => $v) {
if (! empty($v)) {
$post[strtolower($k)] = $v;
}
}
and then:
$response = $http->post($url, $post, $request);
if ($response === false) {
throw new SocketException("Mailgun BasicTransport error, no response", 500);
}
$http_status = $response->code;
if ($http_status != 200) {
throw new SocketException("Mailgun request failed. Status: $http_status, Response: {$response->body}", 500);
}
Is it possible to send an email with an dynamically generated attachment?
I tried it this way:
$this->Email->attachments = array(
'reservation.ics' => array(
'controller' => 'reservations',
'action' => 'ical',
'ext' => 'ics',
$this->data['Reservation']['id']
)
);
But it didn't work.
attachments only takes paths to local files on the server, not URLs. You need to render your attachment to a temporary file, then attach it.
In your controller, this could roughly look like this:
$this->autoRender = false;
$content = $this->render();
file_put_contents(
TMP . 'reservation' . $id . '.ics',
$content
);
$this->Email->attachments = array(
'reservation.ics' => TMP . 'reservation' . $id . '.ics'
);
There are another method to send attachment. firstly store this file on the server then use the server path to send. In the below example I skip the code to store attachment file. There is code for attachment only.
Class EmailController extends AppController {
var $name="Email";
var $components = array ('Email');
var $uses = NULL;
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array(*));
}
function EmailSend(){
$Path = WWW_ROOT."img";
$fileName = 'test.jpg';
$this->Email->from = 'Amit Jha<amit#mail.com>';
$this->Email->to = 'Test<test#test.com>';
$this->Email->subject = 'Test Email Send With Attacment';
$this->Email->attachments = array($Path.$fileName);
$this->Email->template = 'simple_message';
$this->Email->sendAs = 'html';
if($this->Email->send()){
$this->session->setFlash("Email Send Successfully");
$this->redirect('somecontroller/someaction');
}
}