Sending mail with attachments - php

How do i send a mail in PHP with attachments?
I want to use pure php and not any libraries...
Here's what I already have tried:
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email';
//define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail.";
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

Try this:
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//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#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Reference: http://webcheatsheet.com/PHP/send_email_text_html_attachment.php

You can try the following, but first you will need to make changes to these:
$name = 'image.jpg';
// The path to the image with the file name:
$fileatt = "images/".$name;
Which is within the code below: (pre-tested)
<?php
// Set who this goes to:
$to = array('Your Name','email#example.com');
// Give the message a subject:
$subject = 'Some subject';
// Set who this message is from:
$from = array("My Company", "email#example.com");
// Create the header information:
$random_hash = md5(date('r', time()));
$mime_boundary = "==Multipart_Boundary_x{$random_hash}x";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-Type: multipart/mixed; boundary="'.$mime_boundary.'"' . "\r\n";
$headers .= 'To: '.$to[0].' <'.$to[1].'>' . "\r\n";
$headers .= 'From: '.$from[0].' <'.$from[1].'>' . "\r\n";
// Build the message (can have HTML in it) message:
$message = 'This is an <b>HTML message</b> it comes with an attachment!'."\n\n".
// Do not edit this part of the message:
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// The image that you would like to send (filename only):
$name = 'image.jpg';
// The path to the image with the file name:
$fileatt = "images/".$name;
$fileatt_type = "application/octet-stream"; // File Type
// Filename that will be used for the file as the attachment
$fileatt_name = $name;
// Read the file attachment:
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
// Create sendable information
$data = chunk_split(base64_encode($data));
// Finalize the message with attachment
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}\n";
unset($data);
unset($file);
unset($fileatt);
unset($fileatt_type);
unset($fileatt_name);
// Send the message:
mail($to[1], $subject, $message, $headers);
echo "Email sent";
?>

You need to make use of base64 encoding inorder to attach a file. So here goes a simpler code.
<?php
$to = "someone#somewhere.com";
$subject = "Email with an Attachment with no Special libraries";
$random_hash = md5(date('r', time()));
$headers = "From: someid#yoursite.com\r\nReply-To: noreply#so.com";
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents("pics.zip")));
$output = "somecontent";
echo mail($to, $subject, $output, $headers);
?>

Related

PHP file attachment in form file input [duplicate]

This question already has answers here:
Send attachments with PHP Mail()?
(16 answers)
Closed 4 years ago.
My form did send all info except of file/ How it is possible to fix it?
This is input file:
<input type="file" name="file" placeholder="ЗАГРУЗИТЬ ЧЕК" id="file_kd" required>
<br></p>
This is code php mail:
<?php
header('Refresh: 0; URL=http://yougotit.agency/kodabra/thank-you.php'); //
переадресация на страницу спасибо
$to = "stanislav.mandrik#gmail.com"; // емайл получателя данных из формы
$tema = "Kodabra - заявка успешно отправлена!"; // тема полученного емайла
$from = "Kodabra <no-reply#kodabra.com>";
$photo = $_FILES['file']['name'];
$message = "Ваше имя: ".$_POST['kdname']."<br>";
$message .= "E-mail: ".$_POST['kdemail']."<br>";
$message .= "Номер телефона: ".$_POST['kdphone']."<br>";
$message .= "Артикул модели (указан на упаковке): ".$_POST['kdartic']."<br>";
$message .= "Номер чека: ".$_POST['kdbill']."<br>";
$message .= "Комментарий: ".$_POST['kdcomment']."<br>";
$message .= "Согласился на обработку персональных данных. ".$_POST['kdagree']."<br>";
$message .= "Фото чека: ".($photo)."\n";
$headers = "MIME-Version: 1.0"."\r\n".
"Content-type: text/html; charset=\"utf-8\""."\r\n".
"From: $from"."\r\n";
mail($to, $tema, $message, $headers);
?>
from the answer that i marked duplicate please don't upvote this
To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email.Have a look at the example:
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//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#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64, split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.
Taken from here.
In order to send email with file attachments you have to split the message into multiple parts with different encoding - here's how I do it. Note that there is a section for plain text information, and then it changes content encoding and adds any attachments by reading in the byte stream and re-encoding to base64 format and adding that to the message body, specifing content type, its file name, etc.
Of course, this all assumes that you have a working mail set up and a mail() of a plain text message works fine...
<?php
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: $from_name <$from_address>\r\n";
$headers .= "Date: " . date("Ymd H:i:s") . "\r\n";
$headers .= "Reply-To: $from_name <$from_address>\r\n";
$headers .= "X-Priority: 1\r\n";
$headers .= "X-MSMail-Priority: High\r\n";
$headers .= "X-Mailer: ".$_SERVER['PHP_SELF']. "?id=". $_SERVER['UNIQUE_ID']. "\r\n";
$separator=md5(time());
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n";
$headers .= "This is a MIME encoded message.\r\n";
// text message as normal for f2m
$messageBody="--".$separator."\r\n";
$messageBody.="Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$messageBody.="Content-Transfer-Encoding: 8bit\r\n";
$messageBody.="\r\n".$message_body."\r\n\r\n";
// add attachments
// $attachments is basically the $_FILES array
for($i=0;$i<count($attachments);$i++){
$attachcontent=chunk_split(base64_encode(file_get_contents($attachments[$i]['tmp_name'])));
$messageBody.="--".$separator."\r\n";
$messageBody.="Content-Type: application/octet-stream; name=\"".$attachments[$i]['name']."\"\r\n";
$messageBody.="Content-Transfer-Encoding: base64\r\n";
$messageBody.="Content-Disposition: attachment; filename=\"".$attachments[$i]['name']."\"\r\n";
$messageBody.="\r\n".$attachcontent."\r\n";
}
$messageBody.="--" . $separator . "--";
mail($to_address, $subject, $messageBody, $headers);
?>

How to email attachment from PHP?

I am trying to email a text file as an attachment from a PHP script using the code from here: http://webcheatsheet.com/php/send_email_text_html_attachment.php#attachment
<?
$subject = 'Requested File';
$random_hash = md5(date('r', time()));
$headers = "From: email#email.com\r\nReply-To: email#email.com";
$headers .= "\r\nContent-Type: myltipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents('path/test.txt')));
ob_start();
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="test.txt"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
I'm not a PHP developer and have very limited experience using it, I am not getting any errors when this script is executed but I am also not receiving the email...any ideas why? Or what I should be looking at specifically?
Thank you for any tips!
EDIT:
As per the comments, I tried using SwiftMailer but I cannot get it to work using this code:
$message = Swift_Message::newInstance();
// Give the message a subject
$message->setSubject('Your subject');
// Set the From address with an associative array
$message->setFrom(array('email#email.com' => 'From Name'));
// Set the To addresses with an associative array
$message->setTo(array('email#email.com', 'email#email.com' => 'Name'));
// Give it a body
$message->setBody('Here is the message itself');
// And optionally an alternative body
$message->addPart('<q>Here is the message itself</q>', 'text/html');
// Optionally add any attachments
$message->attach(Swift_Attachment::fromPath('path/test.csv'));
Again, this code executes without any errors but no email is sent...what am I missing?
That tutorial has errors for its file attachment, I remember it now and I never could modify it to work. (In the past)
Here is a working copy from my own library that you're welcome to use.
Just change all instances of test.txt to the file you wish to attach.
<html>
<head>
<title>Send file attachments using PHP</title>
</head>
<body>
<?php
$to = "email#example.com";
$subject = "This is the subject";
$message = "This is the test message.";
# Open a file
$file = fopen( "test.txt", "r" );
if( $file == false )
{
echo "Error in opening file";
exit();
}
# Read the file into a variable
$size = filesize("test.txt");
$content = fread( $file, $size);
# encode the data for safe transit
# and insert \r\n after every 76 chars.
$encoded_content = chunk_split( base64_encode($content));
# Get a random 32 bit number using time() as seed.
$num = md5( time() );
# Define the main headers.
$header = "From:email#example.com\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; ";
$header .= "boundary=$num\r\n";
$header .= "--$num\r\n";
# Define the message section
$header .= "Content-Type: text/plain\r\n";
$header .= "Content-Transfer-Encoding:8bit\r\n\n";
$header .= "$message\r\n";
$header .= "--$num\r\n";
# Define the attachment section
$header .= "Content-Type: multipart/mixed; ";
$header .= "name=\"test.txt\"\r\n";
$header .= "Content-Transfer-Encoding:base64\r\n";
$header .= "Content-Disposition:attachment; ";
$header .= "filename=\"test.txt\"\r\n\n";
$header .= "$encoded_content\r\n";
$header .= "--$num--";
# Send email now
$retval = mail ( $to, $subject, "", $header );
if( $retval == true )
{
echo "Message sent successfully...";
}
else
{
echo "Message could not be sent...";
}
?>
</body>
</html>

PHP Email with attachement

Am facing a problem to sent a PHP email with an excel attachment. I can see the mail sent message, Mail is coming, but there is no attachment. I dint know the real problem. this is my code. I have put the User.xlsx file in my root directory. Please help me to solve this issue. Thanks
$to = "dibeesh#amt.in";
$subject="attachement";
$mail_msg="message with attach";
$filename="User.xlsx"; // Attachement file in root directory
$contentType="application/zip"; // Not sure about what to put here
$pathToFilename="./";
$random_hash = md5(date('r', time()));
$headers = "From: webmaster#mysite.com\r\nReply-To: ".$to;
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents($pathToFilename)));
ob_start();
echo "
--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary=\"PHP-alt-$random_hash\"
--PHP-alt-$random_hash
Content-Type: text/plain; charset=\"utf-8\"
Content-Transfer-Encoding: 7bit
$mail_msg
--PHP-alt-$random_hash--
--PHP-mixed-$random_hash
Content-Type: $contentType; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--
";
$message = ob_get_clean();
// $fh=fopen('log.txt','w');
// fwrite($fh,$message);
$mail_sent = #mail( $to, $subject, $message, $headers );
echo $mail_sent ? "Mail sent" : "Mail failed";
I have managed to debug my code, sorry for duplicate posting. It may help someone thanks
// Email to Client with attachement
//define the receiver of the email
$to = 'dibeesh#amt.in';
//define the subject of the email
$subject = 'Bayern3 Notification';
$filename = "User.xlsx";
//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: lal#amt.in\r\nReply-To: dibeesh#amt.in";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents($filename)));
//define the body of the message.
ob_start(); //Turn on output buffering
echo "--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary=\"PHP-alt-$random_hash\"
--PHP-alt-$random_hash
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
--PHP-alt-$random_hash
Content-Type: text/html; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
<h4>Hi,</h4>
<p><b>$userfullname</b> and his 10 friends qualified for <b>$venuename</b>. Please find the Excel sheet attached. You can download the detailed report form Bayern3 Admin Panel</p>
<h4>Regards,</h4>
<h4>Bayern3 Team</h4>
--PHP-alt-$random_hash--
--PHP-mixed-$random_hash
Content-Type: application/zip; name=$filename
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--";
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
//echo $mail_sent ? "Mail sent" : "Mail failed";
if($mail_sent === True)
{
//echo "Mail Sent";
}
else{
//echo "Mail Failed";
}

how to attach multiple files to email and send it to multiple emailid dynamically php

how to attach multiple files to email and send it to multiple emailid dynamically php
i have one form and i want to send multiple files dynamically to multiple email id on button click.i have tried this code but it only takes zip files. i want all kind of files seperatelly attached.
<?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/mixed; 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 = "1.rar";
$my_path = $_SERVER['DOCUMENT_ROOT']."schedulemgt/upload/";
$my_name = "tech";
$my_mail = "my#mail.com";
$my_replyto = "my_reply_to#mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,Your report is here";
mail_attachment($my_file, $my_path, "recipient#mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
?>
<?php
$to = 'youraddress#example.com';
$subject = 'Test email with attachment';
//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#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

Email PDF Attachment with PHP Using FPDF

I want to email a PDF as an attachment that was created using FPDF. My code looks like this, but the attachment never comes through.
<?php
require('lib/fpdf/fpdf.php');
$pdf = new FPDF('P', 'pt', array(500,233));
$pdf->AddFont('Georgiai','','georgiai.php');
$pdf->AddPage();
$pdf->Image('lib/fpdf/giftcertificate.jpg',0,0,500);
$pdf->SetFont('georgiai','',16);
$pdf->Cell(40,10,'Hello World!');
$doc = $pdf->Output('test.pdf', 'S');
//define the receiver of the email
$to = 'myemail#example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//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: reply#test.com\r\nReply-To: reply#test.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents($doc)));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Anyone familiar with doing this? I'm hoping to use the PHP mail() function.
This ended up working for me:
<?php
require('lib/fpdf/fpdf.php');
$pdf = new FPDF('P', 'pt', array(500,233));
$pdf->AddFont('Georgiai','','georgiai.php');
$pdf->AddPage();
$pdf->Image('lib/fpdf/image.jpg',0,0,500);
$pdf->SetFont('georgiai','',16);
$pdf->Cell(40,10,'Hello World!');
// email stuff (change data below)
$to = "myemail#example.com";
$from = "me#example.com";
$subject = "send email with pdf attachment";
$message = "<p>Please see the attachment.</p>";
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
$filename = "test.pdf";
// encode data (puts attachment in proper format)
$pdfdoc = $pdf->Output("", "S");
$attachment = chunk_split(base64_encode($pdfdoc));
// main header
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
// no more headers after this, we start the body! //
$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$eol;
// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;
// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";
// send message
mail($to, $subject, $body, $headers);
?>
if you use PHPMailer
$attachment= $pdf->Output('attachment.pdf', 'S');
$mailer->AddStringAttachment($attachment, 'attachment.pdf');
Enjoy
I think you have a superfluous command there. You are using the string variant of the Output() command:
$doc = $pdf->Output('test.pdf', 'S');
Then you are performing a file_get_contents() on it:
$attachment = chunk_split(base64_encode(file_get_contents($doc)));
It is not a file, it is a file in a string, as file_get_contents() would return if $doc was a filename.
Just reduce that down to:
$attachment = chunk_split(base64_encode($doc));
Then see if any more errors occur.
Create one pdf file name as testing.pdf
<?php
//define the receiver of the email
$to = 'elangovan2me#gmail.com';
//define the subject of the email
$subject = 'Test email with attachment';
//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: elangovan2me#gmail.com\r\nReply-To: meeetcity#gmail.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('testing.pdf')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Email Pdf File Attachements</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/pdf; name="attachment.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
None of these worked for me...but were close. This is what worked for me and within a WordPress Plugin
function mmd_CreatePDFTest()
{
require(plugin_dir_path( __FILE__ ).'pdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont("Arial","B",14);
$pdf->Cell(40,10, "this is a pdf example");
$pdfdoc = $pdf->Output("", "S");
$content = chunk_split(base64_encode($pdfdoc));
$filename = "test.pdf";
$file_name = "test.pdf";
$uid = md5(uniqid(time()));
$mailto = "recipient#gmail.com";
$from_mail = "office#yourdomain.com";
$replyto = $from_mail = "office#yourdomain.com";
$from_name = "YOUR COMPANY NAME | PDF Test";
$subject = "send email with pdf attachment";
$message = "<Please see the attachment.";
// header
$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";
// message & attachment
$nmessage = "--".$uid."\r\n";
$nmessage .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$nmessage .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$nmessage .= $message."\r\n\r\n";
$nmessage .= "--".$uid."\r\n";
$nmessage .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
$nmessage .= $content."\r\n\r\n";
$nmessage .= "--".$uid."--";
$returnpath = "-f" . $from_mail;
if (mail($mailto, $subject, $nmessage, $header, $returnpath))
return true;
else
return false;
} // function mmd_CreatePDFTest()

Categories