I am using mPDF class and am successfully able to generate an email with the following code. However, my email comes out blank. I am assuming but am not sure if this has something to do with my headers. It's hard for me to tell because I am getting my emails but am not able open the pdf it generates.
include("./mpdf.php");
$mpdf->debug = true;
$html2 = '
<div style="margin-left:3%;">Attach additional photos:
<input type="file" name="file" id="file" /></div><hr />';
echo $html2;
if ( isset( $_POST['submit'] ) ) {
$file_path = "webform.php";
$file_path_type = "application/pdf";
$mpdf=new mPDF('iso-8859-2');
$mpdf->WriteHTML($html);
$file_path_name = "eval.pdf";
$headers .= 'Content-type: text/html; charset=utf-8' . "\n";
$from = "info#myemail.com";
$to = $_POST['email'];
$ccto = $_POST['youremail'];
$subject = "New Form Submitted";
$message = "*** This is an automatically generated email,
please do not reply *** Someone in your association
has completed a survey.
$headers = "From: ".$from;
$headers.= "cc: " . $ccto . " <" . $ccto . ">" . "\n" ;
$file = fopen($file_path,'rb');
$data = fread($file,$file_path);
fclose($file);
$rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message .= "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$file_path_type};\n" .
" name=\"{$file_path_name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$file_path_name}\"\n" .
"Content-Transfer-Encoding: base64\n" .
$data .= "\n\n" .
"--{$mime_boundary}--\n";
if(#mail($to, $subject, $message, $headers)) {
echo '<script language="javascript">';
echo 'alert("Document sent successfully!")';
echo '</script>';
echo "Sent!";
} else {
echo 'Failed';
}
}
exit;
PHP mail and mpdf users any help would be appreciated.
You're learning the hard way - Don't call mail() yourself because you will do it wrong; constructing and sending email messages is horribly complicated and full of pitfalls, as you're finding. Use a library, whether PHPMailer, SwiftMailer Zend_Mail etc, to do it and it will save you a great deal of hassle. You also need to check your two operations separately - first create a PDF, write it to a file and make sure it works correctly; Then write some code that sends a message and check that works; Then get it to send the PDF. Otherwise if you find it's not working, you won't be able to tell which part is broken.
Here is how I did it with MPDF and PHPMAILER.
I also have it so you can attach another file within my form that I made. Hope this helps you along the way.
include("mpdf/mpdf.php");
if ( isset( $_POST['submit'] ) ) {
$mpdf=new mPDF('c','Letter','','','10','10','10','10','','');
$mpdf->allow_charset_conversion=true;
$mpdf->charset_in='ISO-8859-2';
$mpdf->SetDisplayMode('fullpage');
$mpdf->WriteHTML(utf8_encode($html));
$emailAttachment = $mpdf->Output('serviceagreement.pdf', 'S');
//$emailAttachment = chunk_split(base64_encode($emailAttachment));
require("php_mailer/class.phpmailer.php");
$mail = new PHPMailer(true);
try {
$mail = new PHPMailer;
$mail->AddAddress('send email');
$mail->SetFrom('support#myorganization.com');
$mail->AddReplyTo($_POST['email1']);
$mail->Subject = 'Evaluation';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML("*** Form attached! Please see the attached form (.pdf).");
$mail->AddStringAttachment($emailAttachment, $filename = 'serviceagreement.pdf',
$encoding = 'base64',
$type = 'application/pdf'); // attachment
if (isset($_FILES['attached']) &&
$_FILES['attached']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['attached']['tmp_name'],
$_FILES['attached']['name']);
}
$mail->Send();
echo "<div style='margin-left:4%;'>Message Sent OK</div>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}}
?>'
Related
I am creating pdf using FPDF . Pdf is generating perfectly and also pdf is available with email. But i want to send body message also. I have tried with body message. Example Fine text message This is text message from shohag But only pdf attachment is available and body is empty. Here is my code.
function send_pdf_to_user(){
if($_REQUEST['action'] == 'pdf_invoice' ){
require('html2pdf.php');
$pdf=new PDF_HTML();
$pdf->SetFont('Arial','',11);
$pdf->AddPage();
$text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
if(ini_get('magic_quotes_gpc')=='1')
$text=stripslashes($text);
$pdf->WriteHTML($text);
//documentation for Output method here: http://www.fpdf.org/en/doc/output.htm
$attach_pdf_multipart = chunk_split( base64_encode( $pdf->Output( '', 'S' ) ) );
//define the receiver of the email
$to = 'monirulmask#gmail.com';
//define the subject of the email
$subject = 'Test Invoice';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#test.ch\r\nReply-To: webmaster#test.ch";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$msg .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
$msg .= "Content-Transfer-Encoding: base64\r\n";
$msg .= "Content-Disposition: attachment\r\n";
$msg .= $attach_pdf_multipart . "\r\n";
$msg .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n";
$msg .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$msg .= "<p>This is text message from shohag</p>\r\n\r\n";
global $message;
$message = '';
$mail_sent = #mail( $to, $subject, $msg, $headers );
//#mail( $to1, $subject, $msg, $headers );
if(!empty($mail_sent)):
$message = "Invoice sent succuessfully";
else:
$message = "Error occured. Please try again.";
endif;
}
}
Please check my code and let me know further possibility. Thanks in advance.
You can use PHPMailer with FPDF . It works properly without any hassle. You need to change parameter for $pdf->Output . Download and copy class.phpmailer.php and PHPMailerAutoload.php to your work folder. Attach class.phpmailer.php below or above require('html2pdf.php'); . I have done this before so this will work. According to your code this should work.
function send_pdf_to_user(){
if($_REQUEST['action'] == 'pdf_invoice' ){
require('html2pdf.php');
require_once('class.phpmailer.php');
$pdf=new PDF_HTML();
$pdf->SetFont('Arial','',11);
$pdf->AddPage();
$text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
if(ini_get('magic_quotes_gpc')=='1')
$text=stripslashes($text);
$pdf->WriteHTML($text);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = "This is test mail by monirul";
$mail->AddReplyTo("webmaster#test.ch","Test Lernt");
$mail->SetFrom('webmaster#test.ch', 'Test Lernt');
$address = "monirulmask#gmail.com";
$mail->AddAddress($address, "Abdul Kuddos");
$mail->Subject = "Test Invoice";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
//documentation for Output method here: http://www.fpdf.org/en/doc/output.htm
$pdf->Output("Test Invoice.pdf","F");
$path = "Walter Lernt Invoice.pdf";
$mail->AddAttachment($path, '', $encoding = 'base64', $type = 'application/pdf');
global $message;
if(!$mail->Send()) {
$message = "Invoice could not be send. Mailer Error: " . $mail->ErrorInfo;
} else {
$message = "Invoice sent!";
}
}
}
Use this simple code to send email with pdf attachment. Hope this help you. Thanks.
// Settings
$name = "Name goes here";
$email = "someome#anadress.com";
$to = "$name <$email>";
$from = "Gyan-Shah ";
$subject = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$fileatt = "./test.pdf"; //file location
$fileatttype = "application/pdf";
$fileattname = "newname.pdf"; //name that you want to use to send or you can use the same name
$headers = "From: $from";
// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);
// This attaches the file
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$mainMessage . "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
No external libraries are necessary really. Follow this format:
$to = "email1#domain.com, email2#domain.com"; // addresses to email pdf to
$from = "sent_from#domain.com"; // address message is sent from
$subject = "Your PDF email subject"; // email subject
$body = "<p>The PDF is attached.</p>"; // email body
$pdfLocation = "./your-pdf.pdf"; // file location
$pdfName = "pdf-file.pdf"; // pdf file name recipient will get
$filetype = "application/pdf"; // type
// create headers and mime boundry
$eol = PHP_EOL;
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers = "From: $from$eol" .
"MIME-Version: 1.0$eol" .
"Content-Type: multipart/mixed;$eol" .
" boundary=\"$mime_boundary\"";
// add html message body
$message = "--$mime_boundary$eol" .
"Content-Type: text/html; charset=\"iso-8859-1\"$eol" .
"Content-Transfer-Encoding: 7bit$eol$eol" .
$body . $eol;
// fetch pdf
$file = fopen($pdfLocation, 'rb');
$data = fread($file, filesize($pdfLocation));
fclose($file);
$pdf = chunk_split(base64_encode($data));
// attach pdf to email
$message .= "--$mime_boundary$eol" .
"Content-Type: $filetype;$eol" .
" name=\"$pdfName\"$eol" .
"Content-Disposition: attachment;$eol" .
" filename=\"$pdfName\"$eol" .
"Content-Transfer-Encoding: base64$eol$eol" .
$pdf . $eol .
"--$mime_boundary--";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
change this:
$msg .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
To this:
$msg = "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
I'm trying to send emails with attachment from a HTML form using PHP mail().
I have found a script online that works - but with one problem:
If a file is attached to the email, the script works fine. However, if there is no attachment, the email is sent but doesn't contain any text content (blank email body).
I want the ability to add an attachment to be optional.
My question is, how can an email be sent successfully, with or without an attachment?
Thanks!
The PHP script I'm using is as follows:
<?php
$email = trim($_POST['email']);
$email_san = filter_var($email, FILTER_SANITIZE_EMAIL);
$fname = $_POST['first_name'];
$fname_san = filter_var($fname,FILTER_SANITIZE_STRING);
$lname = $_POST['last_name'];
$lname_san = filter_var($lname,FILTER_SANITIZE_STRING);
$org = trim($_POST['organisation']);
$org_san = filter_var($org,FILTER_SANITIZE_STRING);
$user_phone = $_POST['phone'];
$trim_phone = trim($user_phone);
$replace_phone = preg_replace('/[^0-9+-]/', '', $trim_phone);
$phone_san = filter_var($replace_phone,FILTER_SANITIZE_NUMBER_INT);
$message = $_POST['message'];
$fromemail = $email_san;
$subject="Inquiry";
$email_message = '<p><b>First Name:</b> '.$fname_san.'</p>
<p><b>Organisation:</b> '.$org_san.'</p>
<p><b>Email:</b> '.$email_san.'</p>
<p><b>Phone:</b> '.$phone_san.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
$semi_rand = md5(uniqid(time()));
$headers = "From: ".$fromemail;
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
if($_FILES["file"]["name"]!= ""){
$strFilesName = $_FILES["file"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_message .= "\n\n";
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: application/octet-stream;\n" .
" name=\"{$strFilesName}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$strContent .= "\n\n" .
"--{$mime_boundary}--\n";
}
$toemail="email#somedomain.com";
if(mail($toemail, $subject, $email_message, $headers)){
echo "Email sent.";
}else{
echo "Email NOT sent.";
}
?>
/*** UPDATE ***/
OK, taking advice that PHPMailer is a better method of sending emails, I have made another attempt to setup PHPMailer.
I don't have Composer so I downloaded and installed PHPMailer manually. I don't have Composer so I downloaded and installed PHPMailer manually. My server folder hierarchy is shown in this image.
I found a PHPMailer tutorial online which provided a simple script which I saved as 'mailer-test.php', uploaded and linked to my PHPMailer install:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once "php-mailer/src/Exception.php";
//PHPMailer Object
$mail = new PHPMailer(true); //Argument 'true' in enables exceptions
//From email address and name
$mail->From = "me#mydomain.com";
$mail->FromName = "Full Name";
//To address and name
//$mail->addAddress("recipient#somedomain.com", "Recepient Name");
$mail->addAddress("recipient#somedomain.com"); //Recipient name is optional
//Address to which recipient will reply
$mail->addReplyTo("me#mydomain.com", "Reply");
//Send HTML or Plain Text email
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
?>
However, when I view 'mailer-test.php' in a browser, I get the follwing server error:
This page isn't working.
yourdomain.com is currently unable to handle this request.
HTTP ERROR
What is causing this?
Something look strange with your strcontent (he miss the $ on line 39)
But to get more simple, use PhpMailer class
It makes your life easy by sending mails
Make sure you add enctype='multipart/form-data' to your form tag:
<form action='index.php' method='POST' enctype='multipart/form-data'>
...
</form>
How come this piece of php code doesn't work with multiple recipient ?
It only works if $to has only one adress, like:
$to = 'aa#bb.com';
Edit
It works if email adresses are on the same domain.. For instance, if the website is www.example.com, emails such as xxx#example.com will work but yyy#other.com won't.
Solution
PHPMailer. It gives an easy way to configure SMTP.
Here is the initial code
<?php
//define the receiver of the email
$to = 'aa#bb.com, cc#dd.com, ee#ff.com';
// array with filenames to be sent as attachment
$files = array("a.zip","b.c","a.html");
// email fields: to, from, subject, and so on
$from = "mail#mail.com";
$subject ="My subject";
$message = "My message";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers = "From: $from";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
?>
Here is the final code
// PHPMailer
$mail = new PHPMailer;
// setting up PHPMailer
$mail->isSMTP();
$mail->Host = 'host.com';
$mail->SMTPAuth = false;
$mail->Port = xx;
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->Subject = $_POST['subject'];
$mail->msgHTML($_POST['message']);
foreach($contacts as $contact)
$mail->addAddress($contact['email']);
// If the user has attached some files
foreach ($_FILES as $file)
$mail->addAttachment($file['tmp_name'], basename($file['name']));
$response = array("status" => $mail->send() ? "sent" : "error");
echo json_encode($response);
You need use proper RFC 2822 formating.
Don't use # because you don't know what is the error. If you format mails in format "user#example.com, anotheruser#example.com" it's correct and you need search problem elsewhere.
You can also see example #4 on http://php.net/manual/en/function.mail.php#example-3493 page.
although this is not a direct response to your issue, you could potentially save yourself trouble by using a pre-existing email sending library like either:
phpmailer
https://github.com/PHPMailer/PHPMailer
or simplesmtp
https://bitbucket.org/ghorwood/simplesmtp/
I am creating pdf using FPDF . Pdf is generating perfectly and also pdf is available with email. But i want to send body message also. I have tried with body message. Example Fine text message This is text message from shohag But only pdf attachment is available and body is empty. Here is my code.
function send_pdf_to_user(){
if($_REQUEST['action'] == 'pdf_invoice' ){
require('html2pdf.php');
$pdf=new PDF_HTML();
$pdf->SetFont('Arial','',11);
$pdf->AddPage();
$text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
if(ini_get('magic_quotes_gpc')=='1')
$text=stripslashes($text);
$pdf->WriteHTML($text);
//documentation for Output method here: http://www.fpdf.org/en/doc/output.htm
$attach_pdf_multipart = chunk_split( base64_encode( $pdf->Output( '', 'S' ) ) );
//define the receiver of the email
$to = 'monirulmask#gmail.com';
//define the subject of the email
$subject = 'Test Invoice';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#test.ch\r\nReply-To: webmaster#test.ch";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$msg .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
$msg .= "Content-Transfer-Encoding: base64\r\n";
$msg .= "Content-Disposition: attachment\r\n";
$msg .= $attach_pdf_multipart . "\r\n";
$msg .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n";
$msg .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$msg .= "<p>This is text message from shohag</p>\r\n\r\n";
global $message;
$message = '';
$mail_sent = #mail( $to, $subject, $msg, $headers );
//#mail( $to1, $subject, $msg, $headers );
if(!empty($mail_sent)):
$message = "Invoice sent succuessfully";
else:
$message = "Error occured. Please try again.";
endif;
}
}
Please check my code and let me know further possibility. Thanks in advance.
You can use PHPMailer with FPDF . It works properly without any hassle. You need to change parameter for $pdf->Output . Download and copy class.phpmailer.php and PHPMailerAutoload.php to your work folder. Attach class.phpmailer.php below or above require('html2pdf.php'); . I have done this before so this will work. According to your code this should work.
function send_pdf_to_user(){
if($_REQUEST['action'] == 'pdf_invoice' ){
require('html2pdf.php');
require_once('class.phpmailer.php');
$pdf=new PDF_HTML();
$pdf->SetFont('Arial','',11);
$pdf->AddPage();
$text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
if(ini_get('magic_quotes_gpc')=='1')
$text=stripslashes($text);
$pdf->WriteHTML($text);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = "This is test mail by monirul";
$mail->AddReplyTo("webmaster#test.ch","Test Lernt");
$mail->SetFrom('webmaster#test.ch', 'Test Lernt');
$address = "monirulmask#gmail.com";
$mail->AddAddress($address, "Abdul Kuddos");
$mail->Subject = "Test Invoice";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
//documentation for Output method here: http://www.fpdf.org/en/doc/output.htm
$pdf->Output("Test Invoice.pdf","F");
$path = "Walter Lernt Invoice.pdf";
$mail->AddAttachment($path, '', $encoding = 'base64', $type = 'application/pdf');
global $message;
if(!$mail->Send()) {
$message = "Invoice could not be send. Mailer Error: " . $mail->ErrorInfo;
} else {
$message = "Invoice sent!";
}
}
}
Use this simple code to send email with pdf attachment. Hope this help you. Thanks.
// Settings
$name = "Name goes here";
$email = "someome#anadress.com";
$to = "$name <$email>";
$from = "Gyan-Shah ";
$subject = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$fileatt = "./test.pdf"; //file location
$fileatttype = "application/pdf";
$fileattname = "newname.pdf"; //name that you want to use to send or you can use the same name
$headers = "From: $from";
// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);
// This attaches the file
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$mainMessage . "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
No external libraries are necessary really. Follow this format:
$to = "email1#domain.com, email2#domain.com"; // addresses to email pdf to
$from = "sent_from#domain.com"; // address message is sent from
$subject = "Your PDF email subject"; // email subject
$body = "<p>The PDF is attached.</p>"; // email body
$pdfLocation = "./your-pdf.pdf"; // file location
$pdfName = "pdf-file.pdf"; // pdf file name recipient will get
$filetype = "application/pdf"; // type
// create headers and mime boundry
$eol = PHP_EOL;
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers = "From: $from$eol" .
"MIME-Version: 1.0$eol" .
"Content-Type: multipart/mixed;$eol" .
" boundary=\"$mime_boundary\"";
// add html message body
$message = "--$mime_boundary$eol" .
"Content-Type: text/html; charset=\"iso-8859-1\"$eol" .
"Content-Transfer-Encoding: 7bit$eol$eol" .
$body . $eol;
// fetch pdf
$file = fopen($pdfLocation, 'rb');
$data = fread($file, filesize($pdfLocation));
fclose($file);
$pdf = chunk_split(base64_encode($data));
// attach pdf to email
$message .= "--$mime_boundary$eol" .
"Content-Type: $filetype;$eol" .
" name=\"$pdfName\"$eol" .
"Content-Disposition: attachment;$eol" .
" filename=\"$pdfName\"$eol" .
"Content-Transfer-Encoding: base64$eol$eol" .
$pdf . $eol .
"--$mime_boundary--";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
change this:
$msg .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
To this:
$msg = "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
I want to use php mailer for sending multiple attachment in mail.
But the problem is, how to use it. Where to download it, how to install it,. I have searched for 3 days, but have got confused, two or three tutorials that i used, doesn't work and make me more confused.
I want a single file tag, that uploads multiple attachments , and send them in email.
I have done with the Email sending with one attachment successfully..
Please guide me. And please give those links that really work for the purpose.
PHPMailer can be downloaded from its SourceForge page.
Now to the code, which is mostly taken from the examples provided in the ZIPball:
<?php
require_once 'class.phpmailer.php';
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try {
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->AddAddress('whoto#otherdomain.com', 'John Doe');
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML(file_get_contents('contents.html'));
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
This is a combination of multiple scripts and a bit of reading. I haven't added any form processing or the like, but it allows for the use of the option to attach multiple files through one input button. Hope its helpful to someone. I'm sure it breaks all kinds of standards. I do know it works in Chrome 31 and IE10.
Edit: Working with this little script, I added HTML formatting for the message and the thank you message replacement.
<?php
if(isset($_POST['Submit'])) {
$email_to = "";
$email_subject = "";
$thankyou = "thanks.html";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
function died($error) {
echo "Sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
$requester_name = $_POST['requester_name']; // required
$requester_email = $_POST['requester_email']; // required
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message = "<html><body> \r\n";
$email_message .= "<table style=\"border: 1px #777 solid; font-family: Arial; font-size: 13px;\" cellpadding=\"7\"> \r\n";
$email_message .= "<tr><td style=\"background: #444; color:#fff;\"><strong>New Hire Form</strong></td><td style=\"background: #444; color:#fff;\">Requirements</td></tr>" . "\n";
$email_message .= "<tr><td style=\"background: #ccc;\"><strong>Requester Name: </strong></td><td style=\"background: #ddd;\">" .clean_string($requester_name). "</td></tr>" . "\n";
$email_message .= "<tr><td style=\"background: #ccc;\"><strong>Requester Email: </strong></td><td style=\"background: #ddd;\">".clean_string($requester_email). "</td></tr>" . "\n";
$email_message .= "</table> \r\n";
$email_message .= "</body></html>";
// multipart boundary
$email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message . "\n\n";
for($i=0;$i<count($_FILES['attachfile']['name']);$i++)
{
if($_FILES['attachfile']['name'][$i] != "")
{
//here you will get all files selected by user.
$name = ($_FILES['attachfile']['name'][$i]);
$tmp_name = ($_FILES['attachfile']['tmp_name'][$i]);
$type = ($_FILES['attachfile']['type'][$i]);
$size = ($_FILES['attachfile']['size'][$i]);
echo count($_Files['attachfile']) ;
echo $_FILES['attachfile']['name'][$i] ;
echo $_FILES['attachfile']['tmp_name'][$i] ;
echo $_FILES['attachfile']['type'][$i] ;
// Read the file content into a variable
$file = fopen($tmp_name,'rb');
$data = fread($file,filesize($tmp_name));
// Close the file
fclose($file);
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
$headers .= 'From: '.$email_sender."\r\n". // Mail will be sent from your Admin ID
'Reply-To: '.$Email."\r\n" . // Reply to Sender Email
'X-Mailer: PHP/' . phpversion();
// headers for attachment
$headers .= "MIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\"";
#mail($email_to, $email_subject, $email_message, $headers);
?>
<script>location.replace('<?php echo $thankyou;?>')</script>
<?php
}
die();
?>