PHPMail sending attachment but they are empty - php

Basically, I am trying to send a PDF via PHPMail.
the email is sent and I receive it in outlook perfectly. the problem is that the attachment is broken and it doesnt open. I even tried sending a HTML and is also empty.
I tried researching in the forum, tried several "working codes" and other people got it working with this code... I have no clue why is not working for me.
I am using the lastest version of PHPMail 5.2.2
$mail = new PHPMailer();
$staffEmail = "staffemail";
$mail->From = $staffEmail;
$mail->FromName = "name";
$mail->AddAddress('my#email.com');
$mail->AddReplyTo($staffEmail, "name");
$mail->AddAttachment('test.pdf');
$mail->Subject = "PDF file attachment";
$mail->Body = "message!";
$mail->Send();

This custom PHP function will show the (beginning) PHP developer how-to build an e-mail script with attachment function. Please note that inside the mail function is no validation functionality available.
<?php
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
echo "mail send ... OK"; // or use booleans here
} else {
echo "mail send ... ERROR!";
}
}
?>
Next we show an example on how-to use this function to send an e-mail message with one attached zip file:
<?php $my_file = "somefile.zip";
$my_path = $_SERVER['DOCUMENT_ROOT']."/your_path_here/";
$my_name = "Olaf Lederer";
$my_mail = "my#mail.com";
$my_replyto = "my_reply_to#mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo you like this script? I hope it will help.\r\n\r\ngr. Olaf";
mail_attachment($my_file, $my_path, "recipient#mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
?>
Are you looking for a script to send multiple attachments? Try our mail attachment class script.
If you like to send your websites mail messages via SMTP and Gmail, check our PHPMailer tutorial, too.

I suggest you to upload the file to the server and then attach it to the email. For example, you can use the following steps :
Upload the file
Attach it to the email
Send the email
Delete this temporary file from the server
Try this because I think thats the reason of your poblem.
Just in case: http://php.net/manual/en/features.file-upload.php
Good luck

There can be two problems either path is not correct for attachment or php dont have permission on that folder

this one is working for me trying to send a resume has attachmnet in zend
$mail = new Zend_Mail ();
$mail->setBodyHTML ( stripslashes ($message) );
// add attachment
$fileContents = file_get_contents($attachemnet);
$resume = $mail->createAttachment($fileContents);
$resume->filename = $EmployeeDeatils['resume'];
//$mail->createAttachment($attachemnet);
$mail->setFrom ( $mail_template ['from_email'], $mail_template ['from_caption'] );
$mail->addTo ( $clientemail, $employee_name );
$mail->setSubject ($subject );
try {
$mail->send ();
} catch ( Exception $e ) {
$this->_helper->errorlog ( " Send mail to member with activation link : " . $e->getMessage () );
}

You can try use this function which uses simple mail function of PHP:
function mail_attachment ($from , $to, $subject, $message, $attachment){
$fileatt = $attachment; // Path to the file
$fileatt_type = 'application/octet-stream'; // File Type
$start= strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1;
$fileatt_name = substr($attachment, $start, strlen($attachment)); // Filename that will be used for the file as the attachment
$email_from = $from; // Who the email is from
$email_subject = $subject; // The Subject of the email
$email_txt = $message; // Message that the email has in it
$email_to = $to; // Who the email is to
$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$msg_txt=""; //\n\nMail created from websiteaddress systems : http://websiteaddress.com
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nwebsiteaddress-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_txt .= $msg_txt;
$email_message = "This is a multi-part message in websiteaddress format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n".$email_txt. "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
$ok = #mail($email_to, $email_subject, $email_message, $headers);
if($ok) {
//echo "Attachment has been mailed !";
//header("Location: index.php");
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
}
Hope this will help you.

Related

How to send email with attachment in PHP using jspdf & Html2PDF [duplicate]

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";

Unable to attach pdf to email in php

I've tried to follow the examples given in this forum, like the example given by freestate here - Error with PHP mail(): .
Below is my code copied from his revised example. It emails fine. And an attachment is shown in the email when received. However it cannot be opened and is always 125k in size.
I have verified that a file size is returned with "$file_size = filesize($file);". Also that the "fopen" does open the stream. In fact before I added the Multipart to the header, I could see the content in the body of the text (albeit not readable).
I'm only trying to attach a basic pdf file, on a window's platform (windows 10), Apache 2.4, PHP 5.6.16.0.
What would cause the attachment to fail to attach properly?
emailer('//serverName/path/', 'documentName.pdf');
function eMailer($path, $filename)
{
$eol = PHP_EOL;
$to = "xxxx#yyyyyyyy.com";
$subject = "File Name: ".$filename;
$body = "The this the written content of the body";
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$header = "From: NameOfPerson <their#emailAddress.com>".$eol.
"MIME-Version: 1.0\r\n".
"Content-Type: multipart/mixed; boundary=\"".$uid."\"";
$message = "--".$uid.$eol.
"Content-Type: text/html; charset=ISO-8859-1".$eol.
"Content-Transfer-Encoding: 8bit".$eol.$eol.
$body.$eol.
"--".$uid.$eol.
"Content-Type: application/pdf; name=\"".$filename."\"".$eol.
"Content-Transfer-Encoding: base64".$eol.
"Content-Disposition: attachment; filename=\"".$filename."\"".$eol.
$content.$eol.
"--".$uid."--";
echo (mail($to, $subject, $message, $header))?'success':'failure';
}
So after spending considerable time trying to solve the attachment problem by myself, I decided to use one of the two common packages out there PHPMailer and Swiftmailer. Both seemed pretty good. I work on just one enterprise project and I do not have Composer installed. So I wanted something easy to download and plug into my project manually. After reading the installation instructions for swiftmailer, I decided this would be easy for me to install and use.
These are the steps I took
I downloaded the Swiftmailer zip file from Github
From the unzipped file I copied the "lib" folder right into my project "C:\myproject\lib"
Then I read the usage instructions in the online manual
To use it in my project all I needed to do was include it in my code like this:
function eMailer($path, $filename, $mailto, $subject, $message, $user)
{
$file = $path.$filename;
require_once 'C:\myProject\lib\swift_required.php';
// Create the SMTP configuration
$transport = Swift_SmtpTransport::newInstance("mymail_server_address ie: 192.111.22.33", 25);
$transport->setUsername($user['email']);
$transport->setPassword($user['password']);
// Create the mail transport configuration
$transport = Swift_MailTransport::newInstance();
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
$mailto['email']=> $mailto['name']
));
$message->setSubject($subject);
$message->setBody($message);
$message->setFrom($user['email'], $user['name']);
$message->attach(Swift_Attachment::fromPath($file));
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
}
This obviously has much more capabilities than I need right now, but if in the future I need a mailer function in another part of my project it's there ready for me to use.
Try below code:
$name = "Name";
$email = "Email Address";
$to = "$name <$email>";
$from = "XYZ";
$subject = "TEST SUBJECT";
$mainMessage = "Hi, here's the file.";
$fileatt = "./test.pdf";
$fileatttype = "application/pdf";
$fileattname = "newname.pdf";
$headers = "From: $from";
// File
$file = fopen ( $fileatt, 'rb' );
$data = fread ( $file, filesize ( $fileatt ) );
fclose ( $file );
// Attach 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 Email
if (mail ( $to, $subject, $message, $headers )) {
echo "The email was sent.";
} else {
echo "There was an error sending the mail.";
}

send attachment in php mail

I want to send a file in a link which want to get download.I linked the path of the file in anchor tag.But I doesn't get downloaded.That file gets open in next page without downloading.I want to download a file in anchor tag.I want to download in from a link instead of attachment.
move_uploaded_file($_FILES['resume'] ['tmp_name'],'resume/'.$_FILES['resume'][name]);
$url='resume/'.$_FILES['resume']['name'];
$from = $email;
$to="websoftbms#gmail.com";
$headers1 = "From: $from\n";
$headers = "From: $email\r\n";
$headers .= "Reply-To: websoftbms#gmail.com\r\n";
$headers .= "Return-Path: sathurka.mca#gmail.com\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$body = "
Hello,<br>
This mail is sent via blumounts.com<br>
Name:$user<br>
Email:$email<br>
Subject:$subject<br>
message:$message<br>
resume :<a href='//domain.com/website/$url' download>Download</a> <br>
";
$body.="<br>
Thank you,<br>
$user<br>";
if( $sentmail = mail( $to,"Sent via career form.", $body, $headers ))
{
echo '<script>
window.alert("Email sent");
window.reload();
</script>';
}
Try this...
The mail() function doesn’t support attachment or HTML mail by default. You need to use different headers and MIME mail parts to make this possible. Many shared hosting providers doesn’t allow the usage of this function and it might be disabled.
Normally you will pass three values to the mail() function plus some headers. In the example below I skip the value for the message value, because the message is defined as a MIME part together with the attachment.
<?php
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
echo "mail send ... OK"; // or use booleans here
} else {
echo "mail send ... ERROR!";
}
}
$my_file = "file.extension";
$my_path = "/your_path/to_the_attachment/";
$my_name = "Olaf Lederer";
$my_mail = "my#mail.com";
$my_replyto = "my_reply_to#mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo you like this script? I hope it will help.\r\n\r\ngr. Olaf";
mail_attachment($my_file, $my_path, "recipient#mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
Download PHPMailer from here
Create a PHP test file :
<?php
include_once("phpmailer/class.phpmailer.php");
$mail = new PHPMailer () ;
$mail->IsSMTP () ;
// UPDATED CODE -->>
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = // your gmail address "user3386779#gmail.com"
$mail->Password = // your gmail password "passwordUser3386779!"
// <<-- UPDATED CODE
// if you want to format your message body wih HTML Tags
$mail->IsHTML ( true ) ;
$mail->From = $sender_s ;
$mail->Subject = $subject_s ;
$mail->Body = $mail_body_lt ;
// -- Rc : you can loop to add multiple receivers ....
$mail->AddAddress (trim($rc_s));
// -- Cc : you can loop to add multiple receivers ....
$mail->AddCC (trim($cc_s));
// -- Attach file
if (file_exists($attached_files_s) !== TRUE) {
sprintf("file: %s doesn't exist.", $attached_files_s);
}
else {
// Attachement: you can loop to attach multiple files ....
$mail->AddAttachment($attached_files_s);
}
// -- sending mail and catch errors
if ( ! $mail->send () ) {
return $mail->ErrorInfo ;
}
Instead of linking to the real file, make a link to a PHP page with the filename as an argument, and add this header :
// $mimetype is the mimetype of your file.
// You may force it, or use finfo functions to get it :
// http://php.net/manual/fr/function.finfo-file.php
header('Content-type: '.$mimetype);
header('Content-Disposition: attachment; filename="'.$file.'"');
You may of course have to adapt the paths.

php send e-mail with PDF attachment

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";

Attaching a file to an email with PHP

I have a function that is supposed to be attaching a file to an outgoing email. For some reason it is only sending blank files.
Can someone help? I have verified that the files themselves are being uploaded correctly, and are at the exact location needed for this function to work. Only .pdf, .doc, and .docx are allowed
Also, this is on a Windows Server... (I know, I know...YUCK!)
Here is the function:
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = str_replace('/','\\',$path.$filename);
$file_size = filesize($file);
$handle = fopen($file, "rb");
$contenta = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($contenta));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
return true; // or use booleans here
} else {
return false;
}
}
And here is the code using this:
//resume
$errors="";
$dbDir="/candidate-resources/files/temp/";
$baseDir=$_SERVER['DOCUMENT_ROOT'].$dbDir;
$validTypes=array(".doc",".pdf",".docx");
$filesToAdd=array();
$atLeastOne=false;
$valid=false;
$qs="";
if(count($_FILES)>0){
foreach($_FILES as $k=>$v){
if($v['size']>0){
$ext=substr($v['name'],strrpos($v['name'],"."));
if(!in_array($ext,$validTypes)){
$errors='Only ".doc", ".docx", and ".pdf" files can be uploaded. "'.$ext.'" is not a valid file type.';
}
}
}
}
$requireds=array("name","email","message");
foreach($_POST as $k=>$v){//check for injection and spammers
if(preg_match("/(%0A|%0D|\\n+|\\r+)(content-type:|to:|cc:|bcc:)/i",$v) || strpos($v,"http://")!==false || strpos($v,"www.")!==false){
$errors="HTML, website addresses, and scripting code are not allowed in any field. Please check your entries and try again.";
}
$post[$k]=strip_tags(trim(htmlentities($v)));
}
unset($_POST);
foreach($requireds as $r){
if(!strlen(trim($post[$r]))){
$errors.="<li>".ucwords($r)."</li>";
}
}
if(strlen(trim($errors))){
$errors="These fields were left blank. Please fix and resubmit.<ul>".$errors."</ul>";
}
else{
if(ereg("([[:alnum:]\.\-]+)(\#[[:alnum:]\.\-]+\.+)",$post['email'])!=true){
$errors="<p>You must enter a valid email address.</p>";
}
else{
$filename = '';
$ext = '';
// upload the file, then attach it to the email, then delete it
foreach($_FILES as $k=>$v){
if($v['size']!=0){
$atLeastOne=true;
$ext=substr($v['name'],strrpos($v['name'],"."));
move_uploaded_file($v['tmp_name'], $baseDir . "/" . $v['name']);
$filename = $v['name'];
}
}
$to = 'avalid#emailaddress';
$subject="Contact Form";
$headers="From: ".$post["name"]." <".$post["email"].">\r\nReply-To: ".$post["email"]."\r\n";
$message=$subject."\r\n=================================================\r\n\r\n";
foreach($post as $k=>$v) {
if(strlen(trim($v))){
$message.=ucwords(str_replace("_"," ",$k)).": {$v}\r\n";
}
}
if(strlen($filename) > 0) {
mail_attachment($filename, $baseDir, $to, $post["email"], $post["name"], $post["email"], $subject, $message);
//now delete the temp file
if (file_exists(str_replace('/','\\',$baseDir.$filename))) {
unlink(str_replace('/','\\',$baseDir.$filename)); // delete it here only if it exists
}
}else{
mail($to,$subject,$message,$headers);
}
$errors="true";
}
}
please forgive... I just inherited this code (that is: #1 7 years old, #2 now they wanted the ability to attach a file to this email)
Start using Swiftmailer (documentation) or PhpMailer, your life will be easier...
Swiftmailer example:
require_once 'lib/swift_required.php';
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john#doe.com' => 'John Doe'))
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
->setBody('Here is the message itself')
->attach(Swift_Attachment::fromPath('my-document.pdf'));
$mailer->send($message);
PhpMailer example :
$mail = new PHPMailer(); // defaults to using php "mail()"
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->AddAddress("whoto#otherdomain.com", "John Doe");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
I prefer Swiftmailer, but you select you best choice ;-)
I changed my function around some, and this works:
function mail_attachment($from, $fromname, $to, $subj, $text, $filename){
$f = fopen($filename,"rb");
$un = strtoupper(uniqid(time()));
$head = "From: $fromname <$from>\n";
$head .= "To: $to\n";
$head .= "Subject: $subj\n";
$head .= "X-Mailer: PHPMail Tool\n";
$head .= "Reply-To: $from\n";
$head .= "Mime-Version: 1.0\n";
$head .= "Content-Type:multipart/mixed;";
$head .= "boundary=\"----------".$un."\"\n\n";
$zag = "------------".$un."\nContent-Type:text/html;\n";
$zag .= "Content-Transfer-Encoding: 8bit\n\n$text\n\n";
$zag .= "------------".$un."\n";
$zag .= "Content-Type: application/octet-stream;";
$zag .= "name=\"".basename($filename)."\"\n";
$zag .= "Content-Transfer-Encoding:base64\n";
$zag .= "Content-Disposition:attachment;";
$zag .= "filename=\"".basename($filename)."\"\n\n";
$zag .= chunk_split(base64_encode(fread($f, filesize($filename))))."\n";
return #mail("$to", "$subj", $zag, $head);
}
(without the need for a 3rd party include)

Categories