Send attachments with PHP Mail()?











up vote
195
down vote

favorite
101












I need to send a pdf with mail, is it possible?



$to = "xxx";
$subject = "Subject" ;
$message = 'Example message with <b>html</b>';
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From: xxx <xxx>' . "rn";
mail($to,$subject,$message,$headers);


What am I missing?










share|improve this question




















  • 15




    To send an attachment with mail() function is way harder than you expect, for the sake of your time, try to use PHPMailer
    – Mihai Iorga
    Sep 6 '12 at 13:38












  • Or you could just link to it?
    – user849137
    Sep 6 '12 at 13:39












  • @mihai lorga Doesn't that require server side install? If it's possibible without any extensions or plugins, I need to know how.
    – user1537415
    Sep 6 '12 at 13:39












  • Quick Google search - webcheatsheet.com/php/send_email_text_html_attachment.php
    – Mark
    Sep 6 '12 at 13:40






  • 2




    @ChristianNikkanen it's just an well set script, It also has a lot of features that are hard to accomplish. Why to reinvent the wheel? It does not use any additional plugins.
    – Mihai Iorga
    Sep 6 '12 at 13:42















up vote
195
down vote

favorite
101












I need to send a pdf with mail, is it possible?



$to = "xxx";
$subject = "Subject" ;
$message = 'Example message with <b>html</b>';
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From: xxx <xxx>' . "rn";
mail($to,$subject,$message,$headers);


What am I missing?










share|improve this question




















  • 15




    To send an attachment with mail() function is way harder than you expect, for the sake of your time, try to use PHPMailer
    – Mihai Iorga
    Sep 6 '12 at 13:38












  • Or you could just link to it?
    – user849137
    Sep 6 '12 at 13:39












  • @mihai lorga Doesn't that require server side install? If it's possibible without any extensions or plugins, I need to know how.
    – user1537415
    Sep 6 '12 at 13:39












  • Quick Google search - webcheatsheet.com/php/send_email_text_html_attachment.php
    – Mark
    Sep 6 '12 at 13:40






  • 2




    @ChristianNikkanen it's just an well set script, It also has a lot of features that are hard to accomplish. Why to reinvent the wheel? It does not use any additional plugins.
    – Mihai Iorga
    Sep 6 '12 at 13:42













up vote
195
down vote

favorite
101









up vote
195
down vote

favorite
101






101





I need to send a pdf with mail, is it possible?



$to = "xxx";
$subject = "Subject" ;
$message = 'Example message with <b>html</b>';
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From: xxx <xxx>' . "rn";
mail($to,$subject,$message,$headers);


What am I missing?










share|improve this question















I need to send a pdf with mail, is it possible?



$to = "xxx";
$subject = "Subject" ;
$message = 'Example message with <b>html</b>';
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From: xxx <xxx>' . "rn";
mail($to,$subject,$message,$headers);


What am I missing?







php






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 17 '14 at 22:24

























asked Sep 6 '12 at 13:36







user1537415















  • 15




    To send an attachment with mail() function is way harder than you expect, for the sake of your time, try to use PHPMailer
    – Mihai Iorga
    Sep 6 '12 at 13:38












  • Or you could just link to it?
    – user849137
    Sep 6 '12 at 13:39












  • @mihai lorga Doesn't that require server side install? If it's possibible without any extensions or plugins, I need to know how.
    – user1537415
    Sep 6 '12 at 13:39












  • Quick Google search - webcheatsheet.com/php/send_email_text_html_attachment.php
    – Mark
    Sep 6 '12 at 13:40






  • 2




    @ChristianNikkanen it's just an well set script, It also has a lot of features that are hard to accomplish. Why to reinvent the wheel? It does not use any additional plugins.
    – Mihai Iorga
    Sep 6 '12 at 13:42














  • 15




    To send an attachment with mail() function is way harder than you expect, for the sake of your time, try to use PHPMailer
    – Mihai Iorga
    Sep 6 '12 at 13:38












  • Or you could just link to it?
    – user849137
    Sep 6 '12 at 13:39












  • @mihai lorga Doesn't that require server side install? If it's possibible without any extensions or plugins, I need to know how.
    – user1537415
    Sep 6 '12 at 13:39












  • Quick Google search - webcheatsheet.com/php/send_email_text_html_attachment.php
    – Mark
    Sep 6 '12 at 13:40






  • 2




    @ChristianNikkanen it's just an well set script, It also has a lot of features that are hard to accomplish. Why to reinvent the wheel? It does not use any additional plugins.
    – Mihai Iorga
    Sep 6 '12 at 13:42








15




15




To send an attachment with mail() function is way harder than you expect, for the sake of your time, try to use PHPMailer
– Mihai Iorga
Sep 6 '12 at 13:38






To send an attachment with mail() function is way harder than you expect, for the sake of your time, try to use PHPMailer
– Mihai Iorga
Sep 6 '12 at 13:38














Or you could just link to it?
– user849137
Sep 6 '12 at 13:39






Or you could just link to it?
– user849137
Sep 6 '12 at 13:39














@mihai lorga Doesn't that require server side install? If it's possibible without any extensions or plugins, I need to know how.
– user1537415
Sep 6 '12 at 13:39






@mihai lorga Doesn't that require server side install? If it's possibible without any extensions or plugins, I need to know how.
– user1537415
Sep 6 '12 at 13:39














Quick Google search - webcheatsheet.com/php/send_email_text_html_attachment.php
– Mark
Sep 6 '12 at 13:40




Quick Google search - webcheatsheet.com/php/send_email_text_html_attachment.php
– Mark
Sep 6 '12 at 13:40




2




2




@ChristianNikkanen it's just an well set script, It also has a lot of features that are hard to accomplish. Why to reinvent the wheel? It does not use any additional plugins.
– Mihai Iorga
Sep 6 '12 at 13:42




@ChristianNikkanen it's just an well set script, It also has a lot of features that are hard to accomplish. Why to reinvent the wheel? It does not use any additional plugins.
– Mihai Iorga
Sep 6 '12 at 13:42












13 Answers
13






active

oldest

votes

















up vote
277
down vote



accepted










I agree with @MihaiIorga in the comments – use the PHPMailer script. You sound like you're rejecting it because you want the easier option. Trust me, PHPMailer is the easier option by a very large margin compared to trying to do it yourself with PHP's built-in mail() function. PHP's mail() function really isn't very good.



To use PHPMailer:




  • Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer

  • Extract the archive and copy the script's folder to a convenient place in your project.

  • Include the main script file -- require_once('path/to/file/class.phpmailer.php');


Now, sending emails with attachments goes from being insanely difficult to incredibly easy:



use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

$email = new PHPMailer();
$email->SetFrom('you@example.com', 'Your Name'); //Name is optional
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();


It's just that one line $email->AddAttachment(); -- you couldn't ask for any easier.



If you do it with PHP's mail() function, you'll be writing stacks of code, and you'll probably have lots of really difficult to find bugs.






share|improve this answer



















  • 1




    Yes, that easy. the whole point of phpMailer is that it does the complex stuff so you don't have to. That's why it's complex to read. Even for sending simply text-only emails, I prefer phpMailer to mail(), but for working with attachments it's an absolute no brainer.
    – SDC
    Sep 6 '12 at 15:41








  • 3




    I was the same - wanted to use mail() just because I already had it in my code. PHPMAILER took me less than 5 minutes to getting send attachments!
    – James Wilson
    Dec 12 '13 at 10:28






  • 74




    I found this question looking for an answer how to use the mail() function to add attachments. This answer does not help me do that.
    – Cypher
    Jun 9 '14 at 21:02






  • 11




    This isn't the answer to the question. How to send an attachment with PHPMailer isn't how to send an attachment with PHP's mail() which is what is asked.
    – Toby
    Aug 6 '14 at 1:54








  • 4




    This answer also ignores the license used by the project. By using PHPMailer, you must be sure that you exclude the package from your source to prevent issues with its LGPL license.
    – Axle
    Mar 16 '15 at 18:58


















up vote
159
down vote













You can try using the following code:



    $filename = 'myfile';
$path = 'your path goes here';
$file = $path . "/" . $filename;

$mailto = 'mail@mail.com';
$subject = 'Subject';
$message = 'My message';

$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));

// a random hash will be necessary to send mixed content
$separator = md5(time());

// carriage return type (RFC)
$eol = "rn";

// main header (multipart mandatory)
$headers = "From: name <test@test.com>" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary="" . $separator . """ . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;

// message
$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset="iso-8859-1"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $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;
$body .= $content . $eol;
$body .= "--" . $separator . "--";

//SEND Mail
if (mail($mailto, $subject, $body, $headers)) {
echo "mail send ... OK"; // or use booleans here
} else {
echo "mail send ... ERROR!";
print_r( error_get_last() );
}


Edit 14-June-2018



for more readability in some of email provider
use



$body .= $eol . $message . $eol . $eol; and
$body .= $eol . $content . $eol . $eol;






share|improve this answer



















  • 13




    @Christian The other answer is only easier if you're working from a new project. I found myself in a situation where there's an old site that wants attachments. It would be far more work to go through hundreds of lines and convert all of the emails to use PHPMailer.
    – MiniRagnarok
    Jul 30 '14 at 14:47






  • 3




    As noted here (stackoverflow.com/a/36938634/4876196), PHP 5.5.26 no longer allows blank lines in the additional_headers parameter; therefore, the header in this example has to be broken into a $headers and $contents.
    – Kittsil
    Apr 29 '16 at 12:55






  • 2




    This answer has various flaws, eg it uses PHP_EOL which could be rn or r or n depending on platform. Rfc explicitly mentions using rn.
    – Salman A
    Sep 7 '16 at 15:51






  • 2




    I Updated the answer to work with current PHP version, according to feedback in the comments. Tested and working.
    – Michiel Pater
    Nov 3 '16 at 9:12






  • 2




    It didn't work for me with "PHP 7.0.13-0ubuntu0.16.04.1". I had to add extra empty lines before the message and the base64-encoded content, respectively. Now this works (see the double $eol at the end of each line): $body .= "Content-Transfer-Encoding: 7bit" . $eol. $eol; and $body .= "Content-Disposition: attachment". $eol. $eol;
    – Csongor Halmai
    Feb 21 '17 at 1:54




















up vote
114
down vote













For PHP 5.5.27 security update



$file = $path.$filename;
$content = file_get_contents( $file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);

// header
$header = "From: ".$from_name." <".$from_mail.">rn";
$header .= "Reply-To: ".$replyto."rn";
$header .= "MIME-Version: 1.0rn";
$header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";

// message & attachment
$nmessage = "--".$uid."rn";
$nmessage .= "Content-type:text/plain; charset=iso-8859-1rn";
$nmessage .= "Content-Transfer-Encoding: 7bitrnrn";
$nmessage .= $message."rnrn";
$nmessage .= "--".$uid."rn";
$nmessage .= "Content-Type: application/octet-stream; name="".$filename.""rn";
$nmessage .= "Content-Transfer-Encoding: base64rn";
$nmessage .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
$nmessage .= $content."rnrn";
$nmessage .= "--".$uid."--";

if (mail($mailto, $subject, $nmessage, $header)) {
return true; // Or do something here
} else {
return false;
}





share|improve this answer



















  • 12




    This is the Correct Answer!!!!!
    – N Kumar
    Sep 27 '15 at 20:40






  • 3




    @Jon. $filename, is the actual name of your file and $path is the actual file path without the file name. I thought the variables were descriptive enough to declare and institution them
    – Simon Mokhele
    Nov 5 '15 at 7:30






  • 2




    This is the best answer ever !!!!!!! Thanks mate .... took me 2 days to find this answer !!!
    – owsata
    Jan 13 '16 at 0:36






  • 3




    Note for those sending multiple attachments - separate MIME parts with $nmessage .= "--".$uid."rn";, and after the final MIME part, use $nmessage .= "--".$uid."--"; (as shown above).
    – rinogo
    Apr 26 '16 at 21:49






  • 2




    This finally worked after a headache of trying to get the stupid phpmailer thing to work.
    – E.Arrowood
    Aug 23 '16 at 5:54


















up vote
17
down vote













Swiftmailer is another easy-to-use script that automatically protects against email injection and makes attachments a breeze. I also strongly discourage using PHP's built-in mail() function.



To use:




  • Download Swiftmailer, and place the lib folder in your project

  • Include the main file using require_once 'lib/swift_required.php';


Now add the code when you need to mail:



// Create the message
$message = Swift_Message::newInstance()
->setSubject('Your subject')
->setFrom(array('webmaster@mysite.com' => 'Web Master'))
->setTo(array('receiver@example.com'))
->setBody('Here is the message itself')
->attach(Swift_Attachment::fromPath('myPDF.pdf'));

//send the message
$mailer->send($message);


More information and options can be found in the Swiftmailer Docs.






share|improve this answer



















  • 1




    Why the downvote?
    – Matthew Johnson
    Aug 21 '14 at 16:14






  • 3




    cause you offer to dwonload 3rd-party library, I guess
    – vladkras
    Nov 27 '15 at 13:16


















up vote
14
down vote













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 rn
$headers = "From: webmaster@example.comrnReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "rnContent-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.






share|improve this answer



















  • 14




    copy/paste of the content in the link I added in OP comments
    – Mark
    Sep 6 '12 at 13:42


















up vote
6
down vote













After struggling for a while with badly formatted attachments, this is the code I ended up using:



$email = new PHPMailer();
$email->From = 'from@somedomain.com';
$email->FromName = 'FromName';
$email->Subject = 'Subject';
$email->Body = 'Body';
$email->AddAddress( 'to@somedomain.com' );
$email->AddAttachment( "/path/to/file" , "filename.ext", 'base64', 'application/octet-stream' );
$email->Send();





share|improve this answer






























    up vote
    5
    down vote













    Working Concept :



    if (isset($_POST['submit'])) {
    $mailto = $_POST["mailTo"];
    $from_mail = $_POST["fromEmail"];
    $replyto = $_POST["fromEmail"];
    $from_name = $_POST["fromName"];
    $message = $_POST["message"];
    $subject = $_POST["subject"];

    $filename = $_FILES["fileAttach"]["name"];
    $content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));

    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: " . $from_name . " <" . $from_mail . ">rn";
    $header .= "Reply-To: " . $replyto . "rn";

    $header .= "MIME-Version: 1.0rn";
    $header .= "Content-Type: multipart/mixed; boundary="" . $uid . ""rnrn";
    $header .= "This is a multi-part message in MIME format.rn";
    $header .= "--" . $uid . "rn";

    // You add html "Content-type: text/html; charset=utf-8n" or for Text "Content-type:text/plain; charset=iso-8859-1rn" by I.khan
    $header .= "Content-type:text/html; charset=utf-8n";
    $header .= "Content-Transfer-Encoding: 7bitrnrn";

    // User Message you can add HTML if You Selected HTML content
    $header .= "<div style='color: red'>" . $message . "</div>rnrn";

    $header .= "--" . $uid . "rn";
    $header .= "Content-Type: application/octet-stream; name="" . $filename . ""rn"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64rn";
    $header .= "Content-Disposition: attachment; filename="" . $filename . ""rnrn"; // For Attachment
    $header .= $content . "rnrn";
    $header .= "--" . $uid . "--";
    if (mail($mailto, $subject, "", $header)) {
    echo "<script>alert('Success');</script>"; // or use booleans here
    } else {
    echo "<script>alert('Failed');</script>";
    }
    }





    share|improve this answer























    • how to send mulitple attachement in above code?
      – Sandeep Shirsat
      Oct 7 '15 at 17:15


















    up vote
    4
    down vote



    +50










    This works for me. It also attaches multiple attachments too. easily



    <?php

    if ($_POST && isset($_FILES['file'])) {
    $recipient_email = "recipient@yourmail.com"; //recepient
    $from_email = "info@your_domain.com"; //from email using site domain.
    $subject = "Attachment email from your website!"; //email subject line

    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['file'];

    //php validation
    if (strlen($sender_name) < 4) {
    die('Name is too short or empty');
    }
    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
    die('Invalid email');
    }
    if (strlen($sender_message) < 4) {
    die('Too short message! Please enter something');
    }

    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("specialToken$4332"); // boundary token to be used

    if ($file_count > 0) { //if attachment exists
    //header
    $headers = "MIME-Version: 1.0rn";
    $headers .= "From:" . $from_email . "rn";
    $headers .= "Reply-To: " . $sender_email . "" . "rn";
    $headers .= "Content-Type: multipart/mixed; boundary = $boundaryrnrn";

    //message text
    $body = "--$boundaryrn";
    $body .= "Content-Type: text/plain; charset=ISO-8859-1rn";
    $body .= "Content-Transfer-Encoding: base64rnrn";
    $body .= chunk_split(base64_encode($sender_message));

    //attachments
    for ($x = 0; $x < $file_count; $x++) {
    if (!empty($attachments['name'][$x])) {

    if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
    $mymsg = array(
    1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
    2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
    3 => "The uploaded file was only partially uploaded",
    4 => "No file was uploaded",
    6 => "Missing a temporary folder");
    die($mymsg[$attachments['error'][$x]]);
    }

    //get file info
    $file_name = $attachments['name'][$x];
    $file_size = $attachments['size'][$x];
    $file_type = $attachments['type'][$x];

    //read file
    $handle = fopen($attachments['tmp_name'][$x], "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

    $body .= "--$boundaryrn";
    $body .= "Content-Type: $file_type; name=" . $file_name . "rn";
    $body .= "Content-Disposition: attachment; filename=" . $file_name . "rn";
    $body .= "Content-Transfer-Encoding: base64rn";
    $body .= "X-Attachment-Id: " . rand(1000, 99999) . "rnrn";
    $body .= $encoded_content;
    }
    }
    } else { //send plain email otherwise
    $headers = "From:" . $from_email . "rn" .
    "Reply-To: " . $sender_email . "n" .
    "X-Mailer: PHP/" . phpversion();
    $body = $sender_message;
    }

    $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if ($sentMail) { //output success or failure messages
    die('Thank you for your email');
    } else {
    die('Could not send mail! Please check your PHP mail configuration.');
    }
    }
    ?>





    share|improve this answer























    • This code is vulnerable to header injection attacks due to the lack of validation & appropriate contextual escaping of user input.
      – Synchro
      Oct 31 at 13:41


















    up vote
    3
    down vote













    None of the above answers worked for me due to their specified attachment format (application/octet-stream). Use application/pdf for best results with PDF files.



    <?php

    // just edit these
    $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

    // creates headers and mime boundary
    $eol = PHP_EOL;
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_$semi_rand";
    $headers = "From: $from$eolMIME-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";

    // fetches pdf
    $file = fopen($pdfLocation, 'rb');
    $data = fread($file, filesize($pdfLocation));
    fclose($file);
    $pdf = chunk_split(base64_encode($data));

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

    // Sends the email
    if(mail($to, $subject, $message, $headers)) {
    echo "The email was sent.";
    }
    else {
    echo "There was an error sending the mail.";
    }





    share|improve this answer






























      up vote
      1
      down vote













      I ended up writing my own email sending/encoding function. This has worked well for me for sending PDF attachments. I have not used the other features in production.



      Note: Despite the spec being quite emphatic that you must use rn to separate headers, I found it only worked when I used PHP_EOL. I have only tested this on Linux. YMMV



      <?php
      # $args must be an associative array
      # required keys: from, to, body
      # body can be a string or a [tree of] associative arrays. See examples below
      # optional keys: subject, reply_to, cc, bcc
      # EXAMPLES:
      # # text-only email:
      # email2(array(
      # 'from' => 'noreply@foo.com',
      # 'to' => 'jason@jasonwoof.com',
      # 'subject' => 'test',
      # # body will be text/plain because we're passing a string that doesn't start with '<'
      # 'body' => 'Hi, testing 1 2 3',
      # ));
      #
      # # html-only email
      # email2(array(
      # 'from' => 'noreply@foo.com',
      # 'to' => 'jason@jasonwoof.com',
      # 'subject' => 'test',
      # # body will be text/html because we're passing a string that starts with '<'
      # 'body' => '<h1>Hi!</h1>I like <a href="http://cheese.com">cheese</a>',
      # ));
      #
      # # text-only email (explicitly, in case first character is dynamic or something)
      # email2(array(
      # 'from' => 'noreply@foo.com',
      # 'to' => 'jason@jasonwoof.com',
      # 'subject' => 'test',
      # # body will be text/plain because we're passing a string that doesn't start with '<'
      # 'body' => array(
      # 'type' => 'text',
      # 'body' => $message_text,
      # )
      # ));
      #
      # # email with text and html alternatives (auto-detected mime types)
      # email2(array(
      # 'from' => 'noreply@foo.com',
      # 'to' => 'jason@jasonwoof.com',
      # 'subject' => 'test',
      # 'body' => array(
      # 'type' => 'alternatives',
      # 'body' => array(
      # "Hi!nnI like cheese",
      # '<h1>Hi!</h1><p>I like <a href="http://cheese.com">cheese</a></p>',
      # )
      # )
      # ));
      #
      # # email with text and html alternatives (explicit types)
      # email2(array(
      # 'from' => 'noreply@foo.com',
      # 'to' => 'jason@jasonwoof.com',
      # 'subject' => 'test',
      # 'body' => array(
      # 'type' => 'alternatives',
      # 'body' => array(
      # array(
      # 'type' => 'text',
      # 'body' => "Hi!nnI like cheese",
      # ),
      # array(
      # 'type' => 'html',
      # 'body' => '<h1>Hi!</h1><p>I like cheese</p>',
      # ),
      # )
      # )
      # ));
      #
      # # email with an attachment
      # email2(array(
      # 'from' => 'noreply@foo.com',
      # 'to' => 'jason@jasonwoof.com',
      # 'subject' => 'test',
      # 'body' => array(
      # 'type' => 'mixed',
      # 'body' => array(
      # "Hi!nnCheck out this (inline) image",
      # array(
      # 'type' => 'image/png',
      # 'disposition' => 'inline',
      # 'body' => $image_data, # raw file contents
      # ),
      # "Hi!nnAnd here's an attachment",
      # array(
      # 'type' => 'application/pdf; name="attachment.pdf"',
      # 'disposition' => 'attachment; filename="attachment.pdf"',
      # 'body' => $pdf_data, # raw file contents
      # ),
      # "Or you can use shorthand:",
      # array(
      # 'type' => 'application/pdf',
      # 'attachment' => 'attachment.pdf', # name for client (not data source)
      # 'body' => $pdf_data, # raw file contents
      # ),
      # )
      # )
      # ))
      function email2($args) {
      if (!isset($args['from'])) { return 1; }
      $from = $args['from'];
      if (!isset($args['to'])) { return 2; }
      $to = $args['to'];
      $subject = isset($args['subject']) ? $args['subject'] : '';
      $reply_to = isset($args['reply_to']) ? $args['reply_to'] : '';
      $cc = isset($args['cc']) ? $args['cc'] : '';
      $bcc = isset($args['bcc']) ? $args['bcc'] : '';

      #FIXME should allow many more characters here (and do Q encoding)
      $subject = isset($args['subject']) ? $args['subject'] : '';
      $subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);

      $headers = "From: $from";
      if($reply_to) {
      $headers .= PHP_EOL . "Reply-To: $reply_to";
      }
      if($cc) {
      $headers .= PHP_EOL . "CC: $cc";
      }
      if($bcc) {
      $headers .= PHP_EOL . "BCC: $bcc";
      }

      $r = email2_helper($args['body']);
      $headers .= PHP_EOL . $r[0];
      $body = $r[1];

      if (mail($to, $subject, $body, $headers)) {
      return 0;
      } else {
      return 5;
      }
      }

      function email2_helper($body, $top = true) {
      if (is_string($body)) {
      if (substr($body, 0, 1) == '<') {
      return email2_helper(array('type' => 'html', 'body' => $body), $top);
      } else {
      return email2_helper(array('type' => 'text', 'body' => $body), $top);
      }
      }
      # now we can assume $body is an associative array
      # defaults:
      $type = 'application/octet-stream';
      $mime = false;
      $boundary = null;
      $disposition = null;
      $charset = false;
      # process 'type' first, because it sets defaults for others
      if (isset($body['type'])) {
      $type = $body['type'];
      if ($type === 'text') {
      $type = 'text/plain';
      $charset = true;
      } elseif ($type === 'html') {
      $type = 'text/html';
      $charset = true;
      } elseif ($type === 'alternative' || $type === 'alternatives') {
      $mime = true;
      $type = 'multipart/alternative';
      } elseif ($type === 'mixed') {
      $mime = true;
      $type = 'multipart/mixed';
      }
      }
      if (isset($body['disposition'])) {
      $disposition = $body['disposition'];
      }
      if (isset($body['attachment'])) {
      if ($disposition == null) {
      $disposition = 'attachment';
      }
      $disposition .= "; filename="{$body['attachment']}"";
      $type .= "; name="{$body['attachment']}"";
      }
      # make headers
      $headers = array();
      if ($top && $mime) {
      $headers = 'MIME-Version: 1.0';
      }
      if ($mime) {
      $boundary = md5('5sd^%Ca)~aAfF0=4mIN' . rand() . rand());
      $type .= "; boundary=$boundary";
      }
      if ($charset) {
      $type .= '; charset=' . (isset($body['charset']) ? $body['charset'] : 'UTF-8');
      }
      $headers = "Content-Type: $type";
      if ($disposition !== null) {
      $headers = "Content-Disposition: {$disposition}";
      }

      $data = '';
      # return array, first el is headers, 2nd is body (php's mail() needs them separate)
      if ($mime) {
      foreach ($body['body'] as $sub_body) {
      $data .= "--$boundary" . PHP_EOL;
      $r = email2_helper($sub_body, false);
      $data .= $r[0] . PHP_EOL . PHP_EOL; # headers
      $data .= $r[1] . PHP_EOL . PHP_EOL; # body
      }
      $data .= "--$boundary--";
      } else {
      if(preg_match('/[^x09x0Ax0Dx20-x7E]/', $body['body'])) {
      $headers = "Content-Transfer-Encoding: base64";
      $data .= chunk_split(base64_encode($body['body']));
      } else {
      $data .= $body['body'];
      }
      }
      return array(join(PHP_EOL, $headers), $data);
      }





      share|improve this answer























      • I just realized that my code called some functions that I didn't include. They just made sure that to/from/cc/etc values were legit. I removed them, and now this code works as is, by itself.
        – JasonWoof
        May 6 '17 at 23:25


















      up vote
      1
      down vote













                  $to = "to@gmail.com";
      $subject = "Subject Of The Mail";
      $message = "Hi there,<br/><br/>This is my message.<br><br>";

      $headers = "From: From-Name<from@gmail.com>";
      // boundary
      $semi_rand = md5(time());
      $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

      // headers for attachment
      $headers .= "nMIME-Version: 1.0n" . "Content-Type: multipart/mixed;n" . " boundary="{$mime_boundary}"";

      // multipart boundary
      $message = "This is a multi-part message in MIME format.nn" . "--{$mime_boundary}n" . "Content-Type: text/html; charset=ISO-8859-1"n" . "Content-Transfer-Encoding: 7bitnn" . $message . "nn";

      $message .= "--{$mime_boundary}n";
      $filepath = 'uploads/'.$_FILES['image']['name'];
      move_uploaded_file($_FILES['image']['tmp_name'], $filepath); //upload the file
      $filename = $_FILES['image']['name'];
      $file = fopen($filepath, "rb");
      $data = fread($file, filesize($filepath));
      fclose($file);
      $data = chunk_split(base64_encode($data));
      $message .= "Content-Type: {"application/octet-stream"};n" . " name="$filename"n" .
      "Content-Disposition: attachment;n" . " filename="$filename"n" .
      "Content-Transfer-Encoding: base64nn" . $data . "nn";
      $message .= "--{$mime_boundary}n";

      mail($to, $subject, $message, $headers);





      share|improve this answer




























        up vote
        -1
        down vote













        Copying the code from this page - works in mail()



        He starts off my making a function mail_attachment that can be called later. Which he does later with his attachment code.



        <?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.">rn";
        $header .= "Reply-To: ".$replyto."rn";
        $header .= "MIME-Version: 1.0rn";
        $header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";
        $header .= "This is a multi-part message in MIME format.rn";
        $header .= "--".$uid."rn";
        $header .= "Content-type:text/plain; charset=iso-8859-1rn";
        $header .= "Content-Transfer-Encoding: 7bitrnrn";
        $header .= $message."rnrn";
        $header .= "--".$uid."rn";
        $header .= "Content-Type: application/octet-stream; name="".$filename.""rn"; // use different content types here
        $header .= "Content-Transfer-Encoding: base64rn";
        $header .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
        $header .= $content."rnrn";
        $header .= "--".$uid."--";
        if (mail($mailto, $subject, "", $header)) {
        echo "mail send ... OK"; // or use booleans here
        } else {
        echo "mail send ... ERROR!";
        }
        }

        //start editing and inputting attachment details here
        $my_file = "somefile.zip";
        $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,rndo you like this script? I hope it will help.rnrngr. Olaf";
        mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
        ?>


        He has more details on his page and answers some problems in the comments section.






        share|improve this answer




























          up vote
          -1
          down vote













          100% working Concept to send email with attachment in php :



          if (isset($_POST['submit'])) {
          extract($_POST);
          require_once('mail/class.phpmailer.php');

          $subject = "$name Applied For - $position";
          $email_message = "<div>Thanks for Applying ....</div> ";

          $mail = new PHPMailer;
          $mail->IsSMTP(); // telling the class to use SMTP
          $mail->Host = "mail.companyname.com"; // SMTP server
          $mail->SMTPDebug = 0;
          $mail->SMTPAuth = true;
          $mail->SMTPSecure = "ssl";
          $mail->Host = "smtp.gmail.com";
          $mail->Port = 465;
          $mail->IsHTML(true);
          $mail->Username = "info@companyname.com"; // GMAIL username
          $mail->Password = "mailPassword"; // GMAIL password

          $mail->SetFrom('info@companyname.com', 'new application submitted');
          $mail->AddReplyTo("name@yourdomain.com","First Last");
          $mail->Subject = "your subject";

          $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

          $mail->MsgHTML($email_message);

          $address = 'info@companyname.com';
          $mail->AddAddress($address, "companyname");

          $mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']); // attachment

          if (!$mail->Send()) {
          /* Error */
          echo 'Message not Sent! Email at info@companyname.com';
          } else {
          /* Success */
          echo 'Sent Successfully! <b> Check your Mail</b>';
          }
          }


          I used this code for google smtp mail sending with Attachment....



          Note: Download PHPMailer Library from here -> https://github.com/PHPMailer/PHPMailer






          share|improve this answer




















            protected by Community Jan 20 '15 at 6:26



            Thank you for your interest in this question.
            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



            Would you like to answer one of these unanswered questions instead?













            13 Answers
            13






            active

            oldest

            votes








            13 Answers
            13






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            277
            down vote



            accepted










            I agree with @MihaiIorga in the comments – use the PHPMailer script. You sound like you're rejecting it because you want the easier option. Trust me, PHPMailer is the easier option by a very large margin compared to trying to do it yourself with PHP's built-in mail() function. PHP's mail() function really isn't very good.



            To use PHPMailer:




            • Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer

            • Extract the archive and copy the script's folder to a convenient place in your project.

            • Include the main script file -- require_once('path/to/file/class.phpmailer.php');


            Now, sending emails with attachments goes from being insanely difficult to incredibly easy:



            use PHPMailerPHPMailerPHPMailer;
            use PHPMailerPHPMailerException;

            $email = new PHPMailer();
            $email->SetFrom('you@example.com', 'Your Name'); //Name is optional
            $email->Subject = 'Message Subject';
            $email->Body = $bodytext;
            $email->AddAddress( 'destinationaddress@example.com' );

            $file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

            $email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

            return $email->Send();


            It's just that one line $email->AddAttachment(); -- you couldn't ask for any easier.



            If you do it with PHP's mail() function, you'll be writing stacks of code, and you'll probably have lots of really difficult to find bugs.






            share|improve this answer



















            • 1




              Yes, that easy. the whole point of phpMailer is that it does the complex stuff so you don't have to. That's why it's complex to read. Even for sending simply text-only emails, I prefer phpMailer to mail(), but for working with attachments it's an absolute no brainer.
              – SDC
              Sep 6 '12 at 15:41








            • 3




              I was the same - wanted to use mail() just because I already had it in my code. PHPMAILER took me less than 5 minutes to getting send attachments!
              – James Wilson
              Dec 12 '13 at 10:28






            • 74




              I found this question looking for an answer how to use the mail() function to add attachments. This answer does not help me do that.
              – Cypher
              Jun 9 '14 at 21:02






            • 11




              This isn't the answer to the question. How to send an attachment with PHPMailer isn't how to send an attachment with PHP's mail() which is what is asked.
              – Toby
              Aug 6 '14 at 1:54








            • 4




              This answer also ignores the license used by the project. By using PHPMailer, you must be sure that you exclude the package from your source to prevent issues with its LGPL license.
              – Axle
              Mar 16 '15 at 18:58















            up vote
            277
            down vote



            accepted










            I agree with @MihaiIorga in the comments – use the PHPMailer script. You sound like you're rejecting it because you want the easier option. Trust me, PHPMailer is the easier option by a very large margin compared to trying to do it yourself with PHP's built-in mail() function. PHP's mail() function really isn't very good.



            To use PHPMailer:




            • Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer

            • Extract the archive and copy the script's folder to a convenient place in your project.

            • Include the main script file -- require_once('path/to/file/class.phpmailer.php');


            Now, sending emails with attachments goes from being insanely difficult to incredibly easy:



            use PHPMailerPHPMailerPHPMailer;
            use PHPMailerPHPMailerException;

            $email = new PHPMailer();
            $email->SetFrom('you@example.com', 'Your Name'); //Name is optional
            $email->Subject = 'Message Subject';
            $email->Body = $bodytext;
            $email->AddAddress( 'destinationaddress@example.com' );

            $file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

            $email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

            return $email->Send();


            It's just that one line $email->AddAttachment(); -- you couldn't ask for any easier.



            If you do it with PHP's mail() function, you'll be writing stacks of code, and you'll probably have lots of really difficult to find bugs.






            share|improve this answer



















            • 1




              Yes, that easy. the whole point of phpMailer is that it does the complex stuff so you don't have to. That's why it's complex to read. Even for sending simply text-only emails, I prefer phpMailer to mail(), but for working with attachments it's an absolute no brainer.
              – SDC
              Sep 6 '12 at 15:41








            • 3




              I was the same - wanted to use mail() just because I already had it in my code. PHPMAILER took me less than 5 minutes to getting send attachments!
              – James Wilson
              Dec 12 '13 at 10:28






            • 74




              I found this question looking for an answer how to use the mail() function to add attachments. This answer does not help me do that.
              – Cypher
              Jun 9 '14 at 21:02






            • 11




              This isn't the answer to the question. How to send an attachment with PHPMailer isn't how to send an attachment with PHP's mail() which is what is asked.
              – Toby
              Aug 6 '14 at 1:54








            • 4




              This answer also ignores the license used by the project. By using PHPMailer, you must be sure that you exclude the package from your source to prevent issues with its LGPL license.
              – Axle
              Mar 16 '15 at 18:58













            up vote
            277
            down vote



            accepted







            up vote
            277
            down vote



            accepted






            I agree with @MihaiIorga in the comments – use the PHPMailer script. You sound like you're rejecting it because you want the easier option. Trust me, PHPMailer is the easier option by a very large margin compared to trying to do it yourself with PHP's built-in mail() function. PHP's mail() function really isn't very good.



            To use PHPMailer:




            • Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer

            • Extract the archive and copy the script's folder to a convenient place in your project.

            • Include the main script file -- require_once('path/to/file/class.phpmailer.php');


            Now, sending emails with attachments goes from being insanely difficult to incredibly easy:



            use PHPMailerPHPMailerPHPMailer;
            use PHPMailerPHPMailerException;

            $email = new PHPMailer();
            $email->SetFrom('you@example.com', 'Your Name'); //Name is optional
            $email->Subject = 'Message Subject';
            $email->Body = $bodytext;
            $email->AddAddress( 'destinationaddress@example.com' );

            $file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

            $email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

            return $email->Send();


            It's just that one line $email->AddAttachment(); -- you couldn't ask for any easier.



            If you do it with PHP's mail() function, you'll be writing stacks of code, and you'll probably have lots of really difficult to find bugs.






            share|improve this answer














            I agree with @MihaiIorga in the comments – use the PHPMailer script. You sound like you're rejecting it because you want the easier option. Trust me, PHPMailer is the easier option by a very large margin compared to trying to do it yourself with PHP's built-in mail() function. PHP's mail() function really isn't very good.



            To use PHPMailer:




            • Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer

            • Extract the archive and copy the script's folder to a convenient place in your project.

            • Include the main script file -- require_once('path/to/file/class.phpmailer.php');


            Now, sending emails with attachments goes from being insanely difficult to incredibly easy:



            use PHPMailerPHPMailerPHPMailer;
            use PHPMailerPHPMailerException;

            $email = new PHPMailer();
            $email->SetFrom('you@example.com', 'Your Name'); //Name is optional
            $email->Subject = 'Message Subject';
            $email->Body = $bodytext;
            $email->AddAddress( 'destinationaddress@example.com' );

            $file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

            $email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

            return $email->Send();


            It's just that one line $email->AddAttachment(); -- you couldn't ask for any easier.



            If you do it with PHP's mail() function, you'll be writing stacks of code, and you'll probably have lots of really difficult to find bugs.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Aug 24 at 13:46









            Travis

            258313




            258313










            answered Sep 6 '12 at 14:27









            SDC

            12k22445




            12k22445








            • 1




              Yes, that easy. the whole point of phpMailer is that it does the complex stuff so you don't have to. That's why it's complex to read. Even for sending simply text-only emails, I prefer phpMailer to mail(), but for working with attachments it's an absolute no brainer.
              – SDC
              Sep 6 '12 at 15:41








            • 3




              I was the same - wanted to use mail() just because I already had it in my code. PHPMAILER took me less than 5 minutes to getting send attachments!
              – James Wilson
              Dec 12 '13 at 10:28






            • 74




              I found this question looking for an answer how to use the mail() function to add attachments. This answer does not help me do that.
              – Cypher
              Jun 9 '14 at 21:02






            • 11




              This isn't the answer to the question. How to send an attachment with PHPMailer isn't how to send an attachment with PHP's mail() which is what is asked.
              – Toby
              Aug 6 '14 at 1:54








            • 4




              This answer also ignores the license used by the project. By using PHPMailer, you must be sure that you exclude the package from your source to prevent issues with its LGPL license.
              – Axle
              Mar 16 '15 at 18:58














            • 1




              Yes, that easy. the whole point of phpMailer is that it does the complex stuff so you don't have to. That's why it's complex to read. Even for sending simply text-only emails, I prefer phpMailer to mail(), but for working with attachments it's an absolute no brainer.
              – SDC
              Sep 6 '12 at 15:41








            • 3




              I was the same - wanted to use mail() just because I already had it in my code. PHPMAILER took me less than 5 minutes to getting send attachments!
              – James Wilson
              Dec 12 '13 at 10:28






            • 74




              I found this question looking for an answer how to use the mail() function to add attachments. This answer does not help me do that.
              – Cypher
              Jun 9 '14 at 21:02






            • 11




              This isn't the answer to the question. How to send an attachment with PHPMailer isn't how to send an attachment with PHP's mail() which is what is asked.
              – Toby
              Aug 6 '14 at 1:54








            • 4




              This answer also ignores the license used by the project. By using PHPMailer, you must be sure that you exclude the package from your source to prevent issues with its LGPL license.
              – Axle
              Mar 16 '15 at 18:58








            1




            1




            Yes, that easy. the whole point of phpMailer is that it does the complex stuff so you don't have to. That's why it's complex to read. Even for sending simply text-only emails, I prefer phpMailer to mail(), but for working with attachments it's an absolute no brainer.
            – SDC
            Sep 6 '12 at 15:41






            Yes, that easy. the whole point of phpMailer is that it does the complex stuff so you don't have to. That's why it's complex to read. Even for sending simply text-only emails, I prefer phpMailer to mail(), but for working with attachments it's an absolute no brainer.
            – SDC
            Sep 6 '12 at 15:41






            3




            3




            I was the same - wanted to use mail() just because I already had it in my code. PHPMAILER took me less than 5 minutes to getting send attachments!
            – James Wilson
            Dec 12 '13 at 10:28




            I was the same - wanted to use mail() just because I already had it in my code. PHPMAILER took me less than 5 minutes to getting send attachments!
            – James Wilson
            Dec 12 '13 at 10:28




            74




            74




            I found this question looking for an answer how to use the mail() function to add attachments. This answer does not help me do that.
            – Cypher
            Jun 9 '14 at 21:02




            I found this question looking for an answer how to use the mail() function to add attachments. This answer does not help me do that.
            – Cypher
            Jun 9 '14 at 21:02




            11




            11




            This isn't the answer to the question. How to send an attachment with PHPMailer isn't how to send an attachment with PHP's mail() which is what is asked.
            – Toby
            Aug 6 '14 at 1:54






            This isn't the answer to the question. How to send an attachment with PHPMailer isn't how to send an attachment with PHP's mail() which is what is asked.
            – Toby
            Aug 6 '14 at 1:54






            4




            4




            This answer also ignores the license used by the project. By using PHPMailer, you must be sure that you exclude the package from your source to prevent issues with its LGPL license.
            – Axle
            Mar 16 '15 at 18:58




            This answer also ignores the license used by the project. By using PHPMailer, you must be sure that you exclude the package from your source to prevent issues with its LGPL license.
            – Axle
            Mar 16 '15 at 18:58












            up vote
            159
            down vote













            You can try using the following code:



                $filename = 'myfile';
            $path = 'your path goes here';
            $file = $path . "/" . $filename;

            $mailto = 'mail@mail.com';
            $subject = 'Subject';
            $message = 'My message';

            $content = file_get_contents($file);
            $content = chunk_split(base64_encode($content));

            // a random hash will be necessary to send mixed content
            $separator = md5(time());

            // carriage return type (RFC)
            $eol = "rn";

            // main header (multipart mandatory)
            $headers = "From: name <test@test.com>" . $eol;
            $headers .= "MIME-Version: 1.0" . $eol;
            $headers .= "Content-Type: multipart/mixed; boundary="" . $separator . """ . $eol;
            $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
            $headers .= "This is a MIME encoded message." . $eol;

            // message
            $body = "--" . $separator . $eol;
            $body .= "Content-Type: text/plain; charset="iso-8859-1"" . $eol;
            $body .= "Content-Transfer-Encoding: 8bit" . $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;
            $body .= $content . $eol;
            $body .= "--" . $separator . "--";

            //SEND Mail
            if (mail($mailto, $subject, $body, $headers)) {
            echo "mail send ... OK"; // or use booleans here
            } else {
            echo "mail send ... ERROR!";
            print_r( error_get_last() );
            }


            Edit 14-June-2018



            for more readability in some of email provider
            use



            $body .= $eol . $message . $eol . $eol; and
            $body .= $eol . $content . $eol . $eol;






            share|improve this answer



















            • 13




              @Christian The other answer is only easier if you're working from a new project. I found myself in a situation where there's an old site that wants attachments. It would be far more work to go through hundreds of lines and convert all of the emails to use PHPMailer.
              – MiniRagnarok
              Jul 30 '14 at 14:47






            • 3




              As noted here (stackoverflow.com/a/36938634/4876196), PHP 5.5.26 no longer allows blank lines in the additional_headers parameter; therefore, the header in this example has to be broken into a $headers and $contents.
              – Kittsil
              Apr 29 '16 at 12:55






            • 2




              This answer has various flaws, eg it uses PHP_EOL which could be rn or r or n depending on platform. Rfc explicitly mentions using rn.
              – Salman A
              Sep 7 '16 at 15:51






            • 2




              I Updated the answer to work with current PHP version, according to feedback in the comments. Tested and working.
              – Michiel Pater
              Nov 3 '16 at 9:12






            • 2




              It didn't work for me with "PHP 7.0.13-0ubuntu0.16.04.1". I had to add extra empty lines before the message and the base64-encoded content, respectively. Now this works (see the double $eol at the end of each line): $body .= "Content-Transfer-Encoding: 7bit" . $eol. $eol; and $body .= "Content-Disposition: attachment". $eol. $eol;
              – Csongor Halmai
              Feb 21 '17 at 1:54

















            up vote
            159
            down vote













            You can try using the following code:



                $filename = 'myfile';
            $path = 'your path goes here';
            $file = $path . "/" . $filename;

            $mailto = 'mail@mail.com';
            $subject = 'Subject';
            $message = 'My message';

            $content = file_get_contents($file);
            $content = chunk_split(base64_encode($content));

            // a random hash will be necessary to send mixed content
            $separator = md5(time());

            // carriage return type (RFC)
            $eol = "rn";

            // main header (multipart mandatory)
            $headers = "From: name <test@test.com>" . $eol;
            $headers .= "MIME-Version: 1.0" . $eol;
            $headers .= "Content-Type: multipart/mixed; boundary="" . $separator . """ . $eol;
            $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
            $headers .= "This is a MIME encoded message." . $eol;

            // message
            $body = "--" . $separator . $eol;
            $body .= "Content-Type: text/plain; charset="iso-8859-1"" . $eol;
            $body .= "Content-Transfer-Encoding: 8bit" . $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;
            $body .= $content . $eol;
            $body .= "--" . $separator . "--";

            //SEND Mail
            if (mail($mailto, $subject, $body, $headers)) {
            echo "mail send ... OK"; // or use booleans here
            } else {
            echo "mail send ... ERROR!";
            print_r( error_get_last() );
            }


            Edit 14-June-2018



            for more readability in some of email provider
            use



            $body .= $eol . $message . $eol . $eol; and
            $body .= $eol . $content . $eol . $eol;






            share|improve this answer



















            • 13




              @Christian The other answer is only easier if you're working from a new project. I found myself in a situation where there's an old site that wants attachments. It would be far more work to go through hundreds of lines and convert all of the emails to use PHPMailer.
              – MiniRagnarok
              Jul 30 '14 at 14:47






            • 3




              As noted here (stackoverflow.com/a/36938634/4876196), PHP 5.5.26 no longer allows blank lines in the additional_headers parameter; therefore, the header in this example has to be broken into a $headers and $contents.
              – Kittsil
              Apr 29 '16 at 12:55






            • 2




              This answer has various flaws, eg it uses PHP_EOL which could be rn or r or n depending on platform. Rfc explicitly mentions using rn.
              – Salman A
              Sep 7 '16 at 15:51






            • 2




              I Updated the answer to work with current PHP version, according to feedback in the comments. Tested and working.
              – Michiel Pater
              Nov 3 '16 at 9:12






            • 2




              It didn't work for me with "PHP 7.0.13-0ubuntu0.16.04.1". I had to add extra empty lines before the message and the base64-encoded content, respectively. Now this works (see the double $eol at the end of each line): $body .= "Content-Transfer-Encoding: 7bit" . $eol. $eol; and $body .= "Content-Disposition: attachment". $eol. $eol;
              – Csongor Halmai
              Feb 21 '17 at 1:54















            up vote
            159
            down vote










            up vote
            159
            down vote









            You can try using the following code:



                $filename = 'myfile';
            $path = 'your path goes here';
            $file = $path . "/" . $filename;

            $mailto = 'mail@mail.com';
            $subject = 'Subject';
            $message = 'My message';

            $content = file_get_contents($file);
            $content = chunk_split(base64_encode($content));

            // a random hash will be necessary to send mixed content
            $separator = md5(time());

            // carriage return type (RFC)
            $eol = "rn";

            // main header (multipart mandatory)
            $headers = "From: name <test@test.com>" . $eol;
            $headers .= "MIME-Version: 1.0" . $eol;
            $headers .= "Content-Type: multipart/mixed; boundary="" . $separator . """ . $eol;
            $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
            $headers .= "This is a MIME encoded message." . $eol;

            // message
            $body = "--" . $separator . $eol;
            $body .= "Content-Type: text/plain; charset="iso-8859-1"" . $eol;
            $body .= "Content-Transfer-Encoding: 8bit" . $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;
            $body .= $content . $eol;
            $body .= "--" . $separator . "--";

            //SEND Mail
            if (mail($mailto, $subject, $body, $headers)) {
            echo "mail send ... OK"; // or use booleans here
            } else {
            echo "mail send ... ERROR!";
            print_r( error_get_last() );
            }


            Edit 14-June-2018



            for more readability in some of email provider
            use



            $body .= $eol . $message . $eol . $eol; and
            $body .= $eol . $content . $eol . $eol;






            share|improve this answer














            You can try using the following code:



                $filename = 'myfile';
            $path = 'your path goes here';
            $file = $path . "/" . $filename;

            $mailto = 'mail@mail.com';
            $subject = 'Subject';
            $message = 'My message';

            $content = file_get_contents($file);
            $content = chunk_split(base64_encode($content));

            // a random hash will be necessary to send mixed content
            $separator = md5(time());

            // carriage return type (RFC)
            $eol = "rn";

            // main header (multipart mandatory)
            $headers = "From: name <test@test.com>" . $eol;
            $headers .= "MIME-Version: 1.0" . $eol;
            $headers .= "Content-Type: multipart/mixed; boundary="" . $separator . """ . $eol;
            $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
            $headers .= "This is a MIME encoded message." . $eol;

            // message
            $body = "--" . $separator . $eol;
            $body .= "Content-Type: text/plain; charset="iso-8859-1"" . $eol;
            $body .= "Content-Transfer-Encoding: 8bit" . $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;
            $body .= $content . $eol;
            $body .= "--" . $separator . "--";

            //SEND Mail
            if (mail($mailto, $subject, $body, $headers)) {
            echo "mail send ... OK"; // or use booleans here
            } else {
            echo "mail send ... ERROR!";
            print_r( error_get_last() );
            }


            Edit 14-June-2018



            for more readability in some of email provider
            use



            $body .= $eol . $message . $eol . $eol; and
            $body .= $eol . $content . $eol . $eol;







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jun 14 at 5:34

























            answered Sep 7 '12 at 6:46









            Pragnesh Chauhan

            6,54993049




            6,54993049








            • 13




              @Christian The other answer is only easier if you're working from a new project. I found myself in a situation where there's an old site that wants attachments. It would be far more work to go through hundreds of lines and convert all of the emails to use PHPMailer.
              – MiniRagnarok
              Jul 30 '14 at 14:47






            • 3




              As noted here (stackoverflow.com/a/36938634/4876196), PHP 5.5.26 no longer allows blank lines in the additional_headers parameter; therefore, the header in this example has to be broken into a $headers and $contents.
              – Kittsil
              Apr 29 '16 at 12:55






            • 2




              This answer has various flaws, eg it uses PHP_EOL which could be rn or r or n depending on platform. Rfc explicitly mentions using rn.
              – Salman A
              Sep 7 '16 at 15:51






            • 2




              I Updated the answer to work with current PHP version, according to feedback in the comments. Tested and working.
              – Michiel Pater
              Nov 3 '16 at 9:12






            • 2




              It didn't work for me with "PHP 7.0.13-0ubuntu0.16.04.1". I had to add extra empty lines before the message and the base64-encoded content, respectively. Now this works (see the double $eol at the end of each line): $body .= "Content-Transfer-Encoding: 7bit" . $eol. $eol; and $body .= "Content-Disposition: attachment". $eol. $eol;
              – Csongor Halmai
              Feb 21 '17 at 1:54
















            • 13




              @Christian The other answer is only easier if you're working from a new project. I found myself in a situation where there's an old site that wants attachments. It would be far more work to go through hundreds of lines and convert all of the emails to use PHPMailer.
              – MiniRagnarok
              Jul 30 '14 at 14:47






            • 3




              As noted here (stackoverflow.com/a/36938634/4876196), PHP 5.5.26 no longer allows blank lines in the additional_headers parameter; therefore, the header in this example has to be broken into a $headers and $contents.
              – Kittsil
              Apr 29 '16 at 12:55






            • 2




              This answer has various flaws, eg it uses PHP_EOL which could be rn or r or n depending on platform. Rfc explicitly mentions using rn.
              – Salman A
              Sep 7 '16 at 15:51






            • 2




              I Updated the answer to work with current PHP version, according to feedback in the comments. Tested and working.
              – Michiel Pater
              Nov 3 '16 at 9:12






            • 2




              It didn't work for me with "PHP 7.0.13-0ubuntu0.16.04.1". I had to add extra empty lines before the message and the base64-encoded content, respectively. Now this works (see the double $eol at the end of each line): $body .= "Content-Transfer-Encoding: 7bit" . $eol. $eol; and $body .= "Content-Disposition: attachment". $eol. $eol;
              – Csongor Halmai
              Feb 21 '17 at 1:54










            13




            13




            @Christian The other answer is only easier if you're working from a new project. I found myself in a situation where there's an old site that wants attachments. It would be far more work to go through hundreds of lines and convert all of the emails to use PHPMailer.
            – MiniRagnarok
            Jul 30 '14 at 14:47




            @Christian The other answer is only easier if you're working from a new project. I found myself in a situation where there's an old site that wants attachments. It would be far more work to go through hundreds of lines and convert all of the emails to use PHPMailer.
            – MiniRagnarok
            Jul 30 '14 at 14:47




            3




            3




            As noted here (stackoverflow.com/a/36938634/4876196), PHP 5.5.26 no longer allows blank lines in the additional_headers parameter; therefore, the header in this example has to be broken into a $headers and $contents.
            – Kittsil
            Apr 29 '16 at 12:55




            As noted here (stackoverflow.com/a/36938634/4876196), PHP 5.5.26 no longer allows blank lines in the additional_headers parameter; therefore, the header in this example has to be broken into a $headers and $contents.
            – Kittsil
            Apr 29 '16 at 12:55




            2




            2




            This answer has various flaws, eg it uses PHP_EOL which could be rn or r or n depending on platform. Rfc explicitly mentions using rn.
            – Salman A
            Sep 7 '16 at 15:51




            This answer has various flaws, eg it uses PHP_EOL which could be rn or r or n depending on platform. Rfc explicitly mentions using rn.
            – Salman A
            Sep 7 '16 at 15:51




            2




            2




            I Updated the answer to work with current PHP version, according to feedback in the comments. Tested and working.
            – Michiel Pater
            Nov 3 '16 at 9:12




            I Updated the answer to work with current PHP version, according to feedback in the comments. Tested and working.
            – Michiel Pater
            Nov 3 '16 at 9:12




            2




            2




            It didn't work for me with "PHP 7.0.13-0ubuntu0.16.04.1". I had to add extra empty lines before the message and the base64-encoded content, respectively. Now this works (see the double $eol at the end of each line): $body .= "Content-Transfer-Encoding: 7bit" . $eol. $eol; and $body .= "Content-Disposition: attachment". $eol. $eol;
            – Csongor Halmai
            Feb 21 '17 at 1:54






            It didn't work for me with "PHP 7.0.13-0ubuntu0.16.04.1". I had to add extra empty lines before the message and the base64-encoded content, respectively. Now this works (see the double $eol at the end of each line): $body .= "Content-Transfer-Encoding: 7bit" . $eol. $eol; and $body .= "Content-Disposition: attachment". $eol. $eol;
            – Csongor Halmai
            Feb 21 '17 at 1:54












            up vote
            114
            down vote













            For PHP 5.5.27 security update



            $file = $path.$filename;
            $content = file_get_contents( $file);
            $content = chunk_split(base64_encode($content));
            $uid = md5(uniqid(time()));
            $name = basename($file);

            // header
            $header = "From: ".$from_name." <".$from_mail.">rn";
            $header .= "Reply-To: ".$replyto."rn";
            $header .= "MIME-Version: 1.0rn";
            $header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";

            // message & attachment
            $nmessage = "--".$uid."rn";
            $nmessage .= "Content-type:text/plain; charset=iso-8859-1rn";
            $nmessage .= "Content-Transfer-Encoding: 7bitrnrn";
            $nmessage .= $message."rnrn";
            $nmessage .= "--".$uid."rn";
            $nmessage .= "Content-Type: application/octet-stream; name="".$filename.""rn";
            $nmessage .= "Content-Transfer-Encoding: base64rn";
            $nmessage .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
            $nmessage .= $content."rnrn";
            $nmessage .= "--".$uid."--";

            if (mail($mailto, $subject, $nmessage, $header)) {
            return true; // Or do something here
            } else {
            return false;
            }





            share|improve this answer



















            • 12




              This is the Correct Answer!!!!!
              – N Kumar
              Sep 27 '15 at 20:40






            • 3




              @Jon. $filename, is the actual name of your file and $path is the actual file path without the file name. I thought the variables were descriptive enough to declare and institution them
              – Simon Mokhele
              Nov 5 '15 at 7:30






            • 2




              This is the best answer ever !!!!!!! Thanks mate .... took me 2 days to find this answer !!!
              – owsata
              Jan 13 '16 at 0:36






            • 3




              Note for those sending multiple attachments - separate MIME parts with $nmessage .= "--".$uid."rn";, and after the final MIME part, use $nmessage .= "--".$uid."--"; (as shown above).
              – rinogo
              Apr 26 '16 at 21:49






            • 2




              This finally worked after a headache of trying to get the stupid phpmailer thing to work.
              – E.Arrowood
              Aug 23 '16 at 5:54















            up vote
            114
            down vote













            For PHP 5.5.27 security update



            $file = $path.$filename;
            $content = file_get_contents( $file);
            $content = chunk_split(base64_encode($content));
            $uid = md5(uniqid(time()));
            $name = basename($file);

            // header
            $header = "From: ".$from_name." <".$from_mail.">rn";
            $header .= "Reply-To: ".$replyto."rn";
            $header .= "MIME-Version: 1.0rn";
            $header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";

            // message & attachment
            $nmessage = "--".$uid."rn";
            $nmessage .= "Content-type:text/plain; charset=iso-8859-1rn";
            $nmessage .= "Content-Transfer-Encoding: 7bitrnrn";
            $nmessage .= $message."rnrn";
            $nmessage .= "--".$uid."rn";
            $nmessage .= "Content-Type: application/octet-stream; name="".$filename.""rn";
            $nmessage .= "Content-Transfer-Encoding: base64rn";
            $nmessage .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
            $nmessage .= $content."rnrn";
            $nmessage .= "--".$uid."--";

            if (mail($mailto, $subject, $nmessage, $header)) {
            return true; // Or do something here
            } else {
            return false;
            }





            share|improve this answer



















            • 12




              This is the Correct Answer!!!!!
              – N Kumar
              Sep 27 '15 at 20:40






            • 3




              @Jon. $filename, is the actual name of your file and $path is the actual file path without the file name. I thought the variables were descriptive enough to declare and institution them
              – Simon Mokhele
              Nov 5 '15 at 7:30






            • 2




              This is the best answer ever !!!!!!! Thanks mate .... took me 2 days to find this answer !!!
              – owsata
              Jan 13 '16 at 0:36






            • 3




              Note for those sending multiple attachments - separate MIME parts with $nmessage .= "--".$uid."rn";, and after the final MIME part, use $nmessage .= "--".$uid."--"; (as shown above).
              – rinogo
              Apr 26 '16 at 21:49






            • 2




              This finally worked after a headache of trying to get the stupid phpmailer thing to work.
              – E.Arrowood
              Aug 23 '16 at 5:54













            up vote
            114
            down vote










            up vote
            114
            down vote









            For PHP 5.5.27 security update



            $file = $path.$filename;
            $content = file_get_contents( $file);
            $content = chunk_split(base64_encode($content));
            $uid = md5(uniqid(time()));
            $name = basename($file);

            // header
            $header = "From: ".$from_name." <".$from_mail.">rn";
            $header .= "Reply-To: ".$replyto."rn";
            $header .= "MIME-Version: 1.0rn";
            $header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";

            // message & attachment
            $nmessage = "--".$uid."rn";
            $nmessage .= "Content-type:text/plain; charset=iso-8859-1rn";
            $nmessage .= "Content-Transfer-Encoding: 7bitrnrn";
            $nmessage .= $message."rnrn";
            $nmessage .= "--".$uid."rn";
            $nmessage .= "Content-Type: application/octet-stream; name="".$filename.""rn";
            $nmessage .= "Content-Transfer-Encoding: base64rn";
            $nmessage .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
            $nmessage .= $content."rnrn";
            $nmessage .= "--".$uid."--";

            if (mail($mailto, $subject, $nmessage, $header)) {
            return true; // Or do something here
            } else {
            return false;
            }





            share|improve this answer














            For PHP 5.5.27 security update



            $file = $path.$filename;
            $content = file_get_contents( $file);
            $content = chunk_split(base64_encode($content));
            $uid = md5(uniqid(time()));
            $name = basename($file);

            // header
            $header = "From: ".$from_name." <".$from_mail.">rn";
            $header .= "Reply-To: ".$replyto."rn";
            $header .= "MIME-Version: 1.0rn";
            $header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";

            // message & attachment
            $nmessage = "--".$uid."rn";
            $nmessage .= "Content-type:text/plain; charset=iso-8859-1rn";
            $nmessage .= "Content-Transfer-Encoding: 7bitrnrn";
            $nmessage .= $message."rnrn";
            $nmessage .= "--".$uid."rn";
            $nmessage .= "Content-Type: application/octet-stream; name="".$filename.""rn";
            $nmessage .= "Content-Transfer-Encoding: base64rn";
            $nmessage .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
            $nmessage .= $content."rnrn";
            $nmessage .= "--".$uid."--";

            if (mail($mailto, $subject, $nmessage, $header)) {
            return true; // Or do something here
            } else {
            return false;
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jul 28 '16 at 18:51









            T.Todua

            27.8k10118118




            27.8k10118118










            answered Jul 15 '15 at 11:11









            Simon Mokhele

            2,79931620




            2,79931620








            • 12




              This is the Correct Answer!!!!!
              – N Kumar
              Sep 27 '15 at 20:40






            • 3




              @Jon. $filename, is the actual name of your file and $path is the actual file path without the file name. I thought the variables were descriptive enough to declare and institution them
              – Simon Mokhele
              Nov 5 '15 at 7:30






            • 2




              This is the best answer ever !!!!!!! Thanks mate .... took me 2 days to find this answer !!!
              – owsata
              Jan 13 '16 at 0:36






            • 3




              Note for those sending multiple attachments - separate MIME parts with $nmessage .= "--".$uid."rn";, and after the final MIME part, use $nmessage .= "--".$uid."--"; (as shown above).
              – rinogo
              Apr 26 '16 at 21:49






            • 2




              This finally worked after a headache of trying to get the stupid phpmailer thing to work.
              – E.Arrowood
              Aug 23 '16 at 5:54














            • 12




              This is the Correct Answer!!!!!
              – N Kumar
              Sep 27 '15 at 20:40






            • 3




              @Jon. $filename, is the actual name of your file and $path is the actual file path without the file name. I thought the variables were descriptive enough to declare and institution them
              – Simon Mokhele
              Nov 5 '15 at 7:30






            • 2




              This is the best answer ever !!!!!!! Thanks mate .... took me 2 days to find this answer !!!
              – owsata
              Jan 13 '16 at 0:36






            • 3




              Note for those sending multiple attachments - separate MIME parts with $nmessage .= "--".$uid."rn";, and after the final MIME part, use $nmessage .= "--".$uid."--"; (as shown above).
              – rinogo
              Apr 26 '16 at 21:49






            • 2




              This finally worked after a headache of trying to get the stupid phpmailer thing to work.
              – E.Arrowood
              Aug 23 '16 at 5:54








            12




            12




            This is the Correct Answer!!!!!
            – N Kumar
            Sep 27 '15 at 20:40




            This is the Correct Answer!!!!!
            – N Kumar
            Sep 27 '15 at 20:40




            3




            3




            @Jon. $filename, is the actual name of your file and $path is the actual file path without the file name. I thought the variables were descriptive enough to declare and institution them
            – Simon Mokhele
            Nov 5 '15 at 7:30




            @Jon. $filename, is the actual name of your file and $path is the actual file path without the file name. I thought the variables were descriptive enough to declare and institution them
            – Simon Mokhele
            Nov 5 '15 at 7:30




            2




            2




            This is the best answer ever !!!!!!! Thanks mate .... took me 2 days to find this answer !!!
            – owsata
            Jan 13 '16 at 0:36




            This is the best answer ever !!!!!!! Thanks mate .... took me 2 days to find this answer !!!
            – owsata
            Jan 13 '16 at 0:36




            3




            3




            Note for those sending multiple attachments - separate MIME parts with $nmessage .= "--".$uid."rn";, and after the final MIME part, use $nmessage .= "--".$uid."--"; (as shown above).
            – rinogo
            Apr 26 '16 at 21:49




            Note for those sending multiple attachments - separate MIME parts with $nmessage .= "--".$uid."rn";, and after the final MIME part, use $nmessage .= "--".$uid."--"; (as shown above).
            – rinogo
            Apr 26 '16 at 21:49




            2




            2




            This finally worked after a headache of trying to get the stupid phpmailer thing to work.
            – E.Arrowood
            Aug 23 '16 at 5:54




            This finally worked after a headache of trying to get the stupid phpmailer thing to work.
            – E.Arrowood
            Aug 23 '16 at 5:54










            up vote
            17
            down vote













            Swiftmailer is another easy-to-use script that automatically protects against email injection and makes attachments a breeze. I also strongly discourage using PHP's built-in mail() function.



            To use:




            • Download Swiftmailer, and place the lib folder in your project

            • Include the main file using require_once 'lib/swift_required.php';


            Now add the code when you need to mail:



            // Create the message
            $message = Swift_Message::newInstance()
            ->setSubject('Your subject')
            ->setFrom(array('webmaster@mysite.com' => 'Web Master'))
            ->setTo(array('receiver@example.com'))
            ->setBody('Here is the message itself')
            ->attach(Swift_Attachment::fromPath('myPDF.pdf'));

            //send the message
            $mailer->send($message);


            More information and options can be found in the Swiftmailer Docs.






            share|improve this answer



















            • 1




              Why the downvote?
              – Matthew Johnson
              Aug 21 '14 at 16:14






            • 3




              cause you offer to dwonload 3rd-party library, I guess
              – vladkras
              Nov 27 '15 at 13:16















            up vote
            17
            down vote













            Swiftmailer is another easy-to-use script that automatically protects against email injection and makes attachments a breeze. I also strongly discourage using PHP's built-in mail() function.



            To use:




            • Download Swiftmailer, and place the lib folder in your project

            • Include the main file using require_once 'lib/swift_required.php';


            Now add the code when you need to mail:



            // Create the message
            $message = Swift_Message::newInstance()
            ->setSubject('Your subject')
            ->setFrom(array('webmaster@mysite.com' => 'Web Master'))
            ->setTo(array('receiver@example.com'))
            ->setBody('Here is the message itself')
            ->attach(Swift_Attachment::fromPath('myPDF.pdf'));

            //send the message
            $mailer->send($message);


            More information and options can be found in the Swiftmailer Docs.






            share|improve this answer



















            • 1




              Why the downvote?
              – Matthew Johnson
              Aug 21 '14 at 16:14






            • 3




              cause you offer to dwonload 3rd-party library, I guess
              – vladkras
              Nov 27 '15 at 13:16













            up vote
            17
            down vote










            up vote
            17
            down vote









            Swiftmailer is another easy-to-use script that automatically protects against email injection and makes attachments a breeze. I also strongly discourage using PHP's built-in mail() function.



            To use:




            • Download Swiftmailer, and place the lib folder in your project

            • Include the main file using require_once 'lib/swift_required.php';


            Now add the code when you need to mail:



            // Create the message
            $message = Swift_Message::newInstance()
            ->setSubject('Your subject')
            ->setFrom(array('webmaster@mysite.com' => 'Web Master'))
            ->setTo(array('receiver@example.com'))
            ->setBody('Here is the message itself')
            ->attach(Swift_Attachment::fromPath('myPDF.pdf'));

            //send the message
            $mailer->send($message);


            More information and options can be found in the Swiftmailer Docs.






            share|improve this answer














            Swiftmailer is another easy-to-use script that automatically protects against email injection and makes attachments a breeze. I also strongly discourage using PHP's built-in mail() function.



            To use:




            • Download Swiftmailer, and place the lib folder in your project

            • Include the main file using require_once 'lib/swift_required.php';


            Now add the code when you need to mail:



            // Create the message
            $message = Swift_Message::newInstance()
            ->setSubject('Your subject')
            ->setFrom(array('webmaster@mysite.com' => 'Web Master'))
            ->setTo(array('receiver@example.com'))
            ->setBody('Here is the message itself')
            ->attach(Swift_Attachment::fromPath('myPDF.pdf'));

            //send the message
            $mailer->send($message);


            More information and options can be found in the Swiftmailer Docs.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 16 '14 at 13:37

























            answered May 15 '14 at 21:14









            Matthew Johnson

            3,44812238




            3,44812238








            • 1




              Why the downvote?
              – Matthew Johnson
              Aug 21 '14 at 16:14






            • 3




              cause you offer to dwonload 3rd-party library, I guess
              – vladkras
              Nov 27 '15 at 13:16














            • 1




              Why the downvote?
              – Matthew Johnson
              Aug 21 '14 at 16:14






            • 3




              cause you offer to dwonload 3rd-party library, I guess
              – vladkras
              Nov 27 '15 at 13:16








            1




            1




            Why the downvote?
            – Matthew Johnson
            Aug 21 '14 at 16:14




            Why the downvote?
            – Matthew Johnson
            Aug 21 '14 at 16:14




            3




            3




            cause you offer to dwonload 3rd-party library, I guess
            – vladkras
            Nov 27 '15 at 13:16




            cause you offer to dwonload 3rd-party library, I guess
            – vladkras
            Nov 27 '15 at 13:16










            up vote
            14
            down vote













            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 rn
            $headers = "From: webmaster@example.comrnReply-To: webmaster@example.com";
            //add boundary string and mime type specification
            $headers .= "rnContent-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.






            share|improve this answer



















            • 14




              copy/paste of the content in the link I added in OP comments
              – Mark
              Sep 6 '12 at 13:42















            up vote
            14
            down vote













            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 rn
            $headers = "From: webmaster@example.comrnReply-To: webmaster@example.com";
            //add boundary string and mime type specification
            $headers .= "rnContent-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.






            share|improve this answer



















            • 14




              copy/paste of the content in the link I added in OP comments
              – Mark
              Sep 6 '12 at 13:42













            up vote
            14
            down vote










            up vote
            14
            down vote









            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 rn
            $headers = "From: webmaster@example.comrnReply-To: webmaster@example.com";
            //add boundary string and mime type specification
            $headers .= "rnContent-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.






            share|improve this answer














            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 rn
            $headers = "From: webmaster@example.comrnReply-To: webmaster@example.com";
            //add boundary string and mime type specification
            $headers .= "rnContent-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.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Sep 6 '12 at 13:44







            user849137

















            answered Sep 6 '12 at 13:39









            Basith

            988621




            988621








            • 14




              copy/paste of the content in the link I added in OP comments
              – Mark
              Sep 6 '12 at 13:42














            • 14




              copy/paste of the content in the link I added in OP comments
              – Mark
              Sep 6 '12 at 13:42








            14




            14




            copy/paste of the content in the link I added in OP comments
            – Mark
            Sep 6 '12 at 13:42




            copy/paste of the content in the link I added in OP comments
            – Mark
            Sep 6 '12 at 13:42










            up vote
            6
            down vote













            After struggling for a while with badly formatted attachments, this is the code I ended up using:



            $email = new PHPMailer();
            $email->From = 'from@somedomain.com';
            $email->FromName = 'FromName';
            $email->Subject = 'Subject';
            $email->Body = 'Body';
            $email->AddAddress( 'to@somedomain.com' );
            $email->AddAttachment( "/path/to/file" , "filename.ext", 'base64', 'application/octet-stream' );
            $email->Send();





            share|improve this answer



























              up vote
              6
              down vote













              After struggling for a while with badly formatted attachments, this is the code I ended up using:



              $email = new PHPMailer();
              $email->From = 'from@somedomain.com';
              $email->FromName = 'FromName';
              $email->Subject = 'Subject';
              $email->Body = 'Body';
              $email->AddAddress( 'to@somedomain.com' );
              $email->AddAttachment( "/path/to/file" , "filename.ext", 'base64', 'application/octet-stream' );
              $email->Send();





              share|improve this answer

























                up vote
                6
                down vote










                up vote
                6
                down vote









                After struggling for a while with badly formatted attachments, this is the code I ended up using:



                $email = new PHPMailer();
                $email->From = 'from@somedomain.com';
                $email->FromName = 'FromName';
                $email->Subject = 'Subject';
                $email->Body = 'Body';
                $email->AddAddress( 'to@somedomain.com' );
                $email->AddAttachment( "/path/to/file" , "filename.ext", 'base64', 'application/octet-stream' );
                $email->Send();





                share|improve this answer














                After struggling for a while with badly formatted attachments, this is the code I ended up using:



                $email = new PHPMailer();
                $email->From = 'from@somedomain.com';
                $email->FromName = 'FromName';
                $email->Subject = 'Subject';
                $email->Body = 'Body';
                $email->AddAddress( 'to@somedomain.com' );
                $email->AddAttachment( "/path/to/file" , "filename.ext", 'base64', 'application/octet-stream' );
                $email->Send();






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 15 '16 at 5:27

























                answered May 24 '16 at 17:30









                Pedro Lobito

                45.7k14127158




                45.7k14127158






















                    up vote
                    5
                    down vote













                    Working Concept :



                    if (isset($_POST['submit'])) {
                    $mailto = $_POST["mailTo"];
                    $from_mail = $_POST["fromEmail"];
                    $replyto = $_POST["fromEmail"];
                    $from_name = $_POST["fromName"];
                    $message = $_POST["message"];
                    $subject = $_POST["subject"];

                    $filename = $_FILES["fileAttach"]["name"];
                    $content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));

                    $uid = md5(uniqid(time()));
                    $name = basename($file);
                    $header = "From: " . $from_name . " <" . $from_mail . ">rn";
                    $header .= "Reply-To: " . $replyto . "rn";

                    $header .= "MIME-Version: 1.0rn";
                    $header .= "Content-Type: multipart/mixed; boundary="" . $uid . ""rnrn";
                    $header .= "This is a multi-part message in MIME format.rn";
                    $header .= "--" . $uid . "rn";

                    // You add html "Content-type: text/html; charset=utf-8n" or for Text "Content-type:text/plain; charset=iso-8859-1rn" by I.khan
                    $header .= "Content-type:text/html; charset=utf-8n";
                    $header .= "Content-Transfer-Encoding: 7bitrnrn";

                    // User Message you can add HTML if You Selected HTML content
                    $header .= "<div style='color: red'>" . $message . "</div>rnrn";

                    $header .= "--" . $uid . "rn";
                    $header .= "Content-Type: application/octet-stream; name="" . $filename . ""rn"; // use different content types here
                    $header .= "Content-Transfer-Encoding: base64rn";
                    $header .= "Content-Disposition: attachment; filename="" . $filename . ""rnrn"; // For Attachment
                    $header .= $content . "rnrn";
                    $header .= "--" . $uid . "--";
                    if (mail($mailto, $subject, "", $header)) {
                    echo "<script>alert('Success');</script>"; // or use booleans here
                    } else {
                    echo "<script>alert('Failed');</script>";
                    }
                    }





                    share|improve this answer























                    • how to send mulitple attachement in above code?
                      – Sandeep Shirsat
                      Oct 7 '15 at 17:15















                    up vote
                    5
                    down vote













                    Working Concept :



                    if (isset($_POST['submit'])) {
                    $mailto = $_POST["mailTo"];
                    $from_mail = $_POST["fromEmail"];
                    $replyto = $_POST["fromEmail"];
                    $from_name = $_POST["fromName"];
                    $message = $_POST["message"];
                    $subject = $_POST["subject"];

                    $filename = $_FILES["fileAttach"]["name"];
                    $content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));

                    $uid = md5(uniqid(time()));
                    $name = basename($file);
                    $header = "From: " . $from_name . " <" . $from_mail . ">rn";
                    $header .= "Reply-To: " . $replyto . "rn";

                    $header .= "MIME-Version: 1.0rn";
                    $header .= "Content-Type: multipart/mixed; boundary="" . $uid . ""rnrn";
                    $header .= "This is a multi-part message in MIME format.rn";
                    $header .= "--" . $uid . "rn";

                    // You add html "Content-type: text/html; charset=utf-8n" or for Text "Content-type:text/plain; charset=iso-8859-1rn" by I.khan
                    $header .= "Content-type:text/html; charset=utf-8n";
                    $header .= "Content-Transfer-Encoding: 7bitrnrn";

                    // User Message you can add HTML if You Selected HTML content
                    $header .= "<div style='color: red'>" . $message . "</div>rnrn";

                    $header .= "--" . $uid . "rn";
                    $header .= "Content-Type: application/octet-stream; name="" . $filename . ""rn"; // use different content types here
                    $header .= "Content-Transfer-Encoding: base64rn";
                    $header .= "Content-Disposition: attachment; filename="" . $filename . ""rnrn"; // For Attachment
                    $header .= $content . "rnrn";
                    $header .= "--" . $uid . "--";
                    if (mail($mailto, $subject, "", $header)) {
                    echo "<script>alert('Success');</script>"; // or use booleans here
                    } else {
                    echo "<script>alert('Failed');</script>";
                    }
                    }





                    share|improve this answer























                    • how to send mulitple attachement in above code?
                      – Sandeep Shirsat
                      Oct 7 '15 at 17:15













                    up vote
                    5
                    down vote










                    up vote
                    5
                    down vote









                    Working Concept :



                    if (isset($_POST['submit'])) {
                    $mailto = $_POST["mailTo"];
                    $from_mail = $_POST["fromEmail"];
                    $replyto = $_POST["fromEmail"];
                    $from_name = $_POST["fromName"];
                    $message = $_POST["message"];
                    $subject = $_POST["subject"];

                    $filename = $_FILES["fileAttach"]["name"];
                    $content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));

                    $uid = md5(uniqid(time()));
                    $name = basename($file);
                    $header = "From: " . $from_name . " <" . $from_mail . ">rn";
                    $header .= "Reply-To: " . $replyto . "rn";

                    $header .= "MIME-Version: 1.0rn";
                    $header .= "Content-Type: multipart/mixed; boundary="" . $uid . ""rnrn";
                    $header .= "This is a multi-part message in MIME format.rn";
                    $header .= "--" . $uid . "rn";

                    // You add html "Content-type: text/html; charset=utf-8n" or for Text "Content-type:text/plain; charset=iso-8859-1rn" by I.khan
                    $header .= "Content-type:text/html; charset=utf-8n";
                    $header .= "Content-Transfer-Encoding: 7bitrnrn";

                    // User Message you can add HTML if You Selected HTML content
                    $header .= "<div style='color: red'>" . $message . "</div>rnrn";

                    $header .= "--" . $uid . "rn";
                    $header .= "Content-Type: application/octet-stream; name="" . $filename . ""rn"; // use different content types here
                    $header .= "Content-Transfer-Encoding: base64rn";
                    $header .= "Content-Disposition: attachment; filename="" . $filename . ""rnrn"; // For Attachment
                    $header .= $content . "rnrn";
                    $header .= "--" . $uid . "--";
                    if (mail($mailto, $subject, "", $header)) {
                    echo "<script>alert('Success');</script>"; // or use booleans here
                    } else {
                    echo "<script>alert('Failed');</script>";
                    }
                    }





                    share|improve this answer














                    Working Concept :



                    if (isset($_POST['submit'])) {
                    $mailto = $_POST["mailTo"];
                    $from_mail = $_POST["fromEmail"];
                    $replyto = $_POST["fromEmail"];
                    $from_name = $_POST["fromName"];
                    $message = $_POST["message"];
                    $subject = $_POST["subject"];

                    $filename = $_FILES["fileAttach"]["name"];
                    $content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));

                    $uid = md5(uniqid(time()));
                    $name = basename($file);
                    $header = "From: " . $from_name . " <" . $from_mail . ">rn";
                    $header .= "Reply-To: " . $replyto . "rn";

                    $header .= "MIME-Version: 1.0rn";
                    $header .= "Content-Type: multipart/mixed; boundary="" . $uid . ""rnrn";
                    $header .= "This is a multi-part message in MIME format.rn";
                    $header .= "--" . $uid . "rn";

                    // You add html "Content-type: text/html; charset=utf-8n" or for Text "Content-type:text/plain; charset=iso-8859-1rn" by I.khan
                    $header .= "Content-type:text/html; charset=utf-8n";
                    $header .= "Content-Transfer-Encoding: 7bitrnrn";

                    // User Message you can add HTML if You Selected HTML content
                    $header .= "<div style='color: red'>" . $message . "</div>rnrn";

                    $header .= "--" . $uid . "rn";
                    $header .= "Content-Type: application/octet-stream; name="" . $filename . ""rn"; // use different content types here
                    $header .= "Content-Transfer-Encoding: base64rn";
                    $header .= "Content-Disposition: attachment; filename="" . $filename . ""rnrn"; // For Attachment
                    $header .= $content . "rnrn";
                    $header .= "--" . $uid . "--";
                    if (mail($mailto, $subject, "", $header)) {
                    echo "<script>alert('Success');</script>"; // or use booleans here
                    } else {
                    echo "<script>alert('Failed');</script>";
                    }
                    }






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Sep 9 '15 at 7:18

























                    answered Apr 28 '15 at 7:59









                    Irshad Khan

                    2,3221915




                    2,3221915












                    • how to send mulitple attachement in above code?
                      – Sandeep Shirsat
                      Oct 7 '15 at 17:15


















                    • how to send mulitple attachement in above code?
                      – Sandeep Shirsat
                      Oct 7 '15 at 17:15
















                    how to send mulitple attachement in above code?
                    – Sandeep Shirsat
                    Oct 7 '15 at 17:15




                    how to send mulitple attachement in above code?
                    – Sandeep Shirsat
                    Oct 7 '15 at 17:15










                    up vote
                    4
                    down vote



                    +50










                    This works for me. It also attaches multiple attachments too. easily



                    <?php

                    if ($_POST && isset($_FILES['file'])) {
                    $recipient_email = "recipient@yourmail.com"; //recepient
                    $from_email = "info@your_domain.com"; //from email using site domain.
                    $subject = "Attachment email from your website!"; //email subject line

                    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
                    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
                    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
                    $attachments = $_FILES['file'];

                    //php validation
                    if (strlen($sender_name) < 4) {
                    die('Name is too short or empty');
                    }
                    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
                    die('Invalid email');
                    }
                    if (strlen($sender_message) < 4) {
                    die('Too short message! Please enter something');
                    }

                    $file_count = count($attachments['name']); //count total files attached
                    $boundary = md5("specialToken$4332"); // boundary token to be used

                    if ($file_count > 0) { //if attachment exists
                    //header
                    $headers = "MIME-Version: 1.0rn";
                    $headers .= "From:" . $from_email . "rn";
                    $headers .= "Reply-To: " . $sender_email . "" . "rn";
                    $headers .= "Content-Type: multipart/mixed; boundary = $boundaryrnrn";

                    //message text
                    $body = "--$boundaryrn";
                    $body .= "Content-Type: text/plain; charset=ISO-8859-1rn";
                    $body .= "Content-Transfer-Encoding: base64rnrn";
                    $body .= chunk_split(base64_encode($sender_message));

                    //attachments
                    for ($x = 0; $x < $file_count; $x++) {
                    if (!empty($attachments['name'][$x])) {

                    if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
                    $mymsg = array(
                    1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                    2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                    3 => "The uploaded file was only partially uploaded",
                    4 => "No file was uploaded",
                    6 => "Missing a temporary folder");
                    die($mymsg[$attachments['error'][$x]]);
                    }

                    //get file info
                    $file_name = $attachments['name'][$x];
                    $file_size = $attachments['size'][$x];
                    $file_type = $attachments['type'][$x];

                    //read file
                    $handle = fopen($attachments['tmp_name'][$x], "r");
                    $content = fread($handle, $file_size);
                    fclose($handle);
                    $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                    $body .= "--$boundaryrn";
                    $body .= "Content-Type: $file_type; name=" . $file_name . "rn";
                    $body .= "Content-Disposition: attachment; filename=" . $file_name . "rn";
                    $body .= "Content-Transfer-Encoding: base64rn";
                    $body .= "X-Attachment-Id: " . rand(1000, 99999) . "rnrn";
                    $body .= $encoded_content;
                    }
                    }
                    } else { //send plain email otherwise
                    $headers = "From:" . $from_email . "rn" .
                    "Reply-To: " . $sender_email . "n" .
                    "X-Mailer: PHP/" . phpversion();
                    $body = $sender_message;
                    }

                    $sentMail = @mail($recipient_email, $subject, $body, $headers);
                    if ($sentMail) { //output success or failure messages
                    die('Thank you for your email');
                    } else {
                    die('Could not send mail! Please check your PHP mail configuration.');
                    }
                    }
                    ?>





                    share|improve this answer























                    • This code is vulnerable to header injection attacks due to the lack of validation & appropriate contextual escaping of user input.
                      – Synchro
                      Oct 31 at 13:41















                    up vote
                    4
                    down vote



                    +50










                    This works for me. It also attaches multiple attachments too. easily



                    <?php

                    if ($_POST && isset($_FILES['file'])) {
                    $recipient_email = "recipient@yourmail.com"; //recepient
                    $from_email = "info@your_domain.com"; //from email using site domain.
                    $subject = "Attachment email from your website!"; //email subject line

                    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
                    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
                    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
                    $attachments = $_FILES['file'];

                    //php validation
                    if (strlen($sender_name) < 4) {
                    die('Name is too short or empty');
                    }
                    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
                    die('Invalid email');
                    }
                    if (strlen($sender_message) < 4) {
                    die('Too short message! Please enter something');
                    }

                    $file_count = count($attachments['name']); //count total files attached
                    $boundary = md5("specialToken$4332"); // boundary token to be used

                    if ($file_count > 0) { //if attachment exists
                    //header
                    $headers = "MIME-Version: 1.0rn";
                    $headers .= "From:" . $from_email . "rn";
                    $headers .= "Reply-To: " . $sender_email . "" . "rn";
                    $headers .= "Content-Type: multipart/mixed; boundary = $boundaryrnrn";

                    //message text
                    $body = "--$boundaryrn";
                    $body .= "Content-Type: text/plain; charset=ISO-8859-1rn";
                    $body .= "Content-Transfer-Encoding: base64rnrn";
                    $body .= chunk_split(base64_encode($sender_message));

                    //attachments
                    for ($x = 0; $x < $file_count; $x++) {
                    if (!empty($attachments['name'][$x])) {

                    if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
                    $mymsg = array(
                    1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                    2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                    3 => "The uploaded file was only partially uploaded",
                    4 => "No file was uploaded",
                    6 => "Missing a temporary folder");
                    die($mymsg[$attachments['error'][$x]]);
                    }

                    //get file info
                    $file_name = $attachments['name'][$x];
                    $file_size = $attachments['size'][$x];
                    $file_type = $attachments['type'][$x];

                    //read file
                    $handle = fopen($attachments['tmp_name'][$x], "r");
                    $content = fread($handle, $file_size);
                    fclose($handle);
                    $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                    $body .= "--$boundaryrn";
                    $body .= "Content-Type: $file_type; name=" . $file_name . "rn";
                    $body .= "Content-Disposition: attachment; filename=" . $file_name . "rn";
                    $body .= "Content-Transfer-Encoding: base64rn";
                    $body .= "X-Attachment-Id: " . rand(1000, 99999) . "rnrn";
                    $body .= $encoded_content;
                    }
                    }
                    } else { //send plain email otherwise
                    $headers = "From:" . $from_email . "rn" .
                    "Reply-To: " . $sender_email . "n" .
                    "X-Mailer: PHP/" . phpversion();
                    $body = $sender_message;
                    }

                    $sentMail = @mail($recipient_email, $subject, $body, $headers);
                    if ($sentMail) { //output success or failure messages
                    die('Thank you for your email');
                    } else {
                    die('Could not send mail! Please check your PHP mail configuration.');
                    }
                    }
                    ?>





                    share|improve this answer























                    • This code is vulnerable to header injection attacks due to the lack of validation & appropriate contextual escaping of user input.
                      – Synchro
                      Oct 31 at 13:41













                    up vote
                    4
                    down vote



                    +50







                    up vote
                    4
                    down vote



                    +50




                    +50




                    This works for me. It also attaches multiple attachments too. easily



                    <?php

                    if ($_POST && isset($_FILES['file'])) {
                    $recipient_email = "recipient@yourmail.com"; //recepient
                    $from_email = "info@your_domain.com"; //from email using site domain.
                    $subject = "Attachment email from your website!"; //email subject line

                    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
                    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
                    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
                    $attachments = $_FILES['file'];

                    //php validation
                    if (strlen($sender_name) < 4) {
                    die('Name is too short or empty');
                    }
                    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
                    die('Invalid email');
                    }
                    if (strlen($sender_message) < 4) {
                    die('Too short message! Please enter something');
                    }

                    $file_count = count($attachments['name']); //count total files attached
                    $boundary = md5("specialToken$4332"); // boundary token to be used

                    if ($file_count > 0) { //if attachment exists
                    //header
                    $headers = "MIME-Version: 1.0rn";
                    $headers .= "From:" . $from_email . "rn";
                    $headers .= "Reply-To: " . $sender_email . "" . "rn";
                    $headers .= "Content-Type: multipart/mixed; boundary = $boundaryrnrn";

                    //message text
                    $body = "--$boundaryrn";
                    $body .= "Content-Type: text/plain; charset=ISO-8859-1rn";
                    $body .= "Content-Transfer-Encoding: base64rnrn";
                    $body .= chunk_split(base64_encode($sender_message));

                    //attachments
                    for ($x = 0; $x < $file_count; $x++) {
                    if (!empty($attachments['name'][$x])) {

                    if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
                    $mymsg = array(
                    1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                    2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                    3 => "The uploaded file was only partially uploaded",
                    4 => "No file was uploaded",
                    6 => "Missing a temporary folder");
                    die($mymsg[$attachments['error'][$x]]);
                    }

                    //get file info
                    $file_name = $attachments['name'][$x];
                    $file_size = $attachments['size'][$x];
                    $file_type = $attachments['type'][$x];

                    //read file
                    $handle = fopen($attachments['tmp_name'][$x], "r");
                    $content = fread($handle, $file_size);
                    fclose($handle);
                    $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                    $body .= "--$boundaryrn";
                    $body .= "Content-Type: $file_type; name=" . $file_name . "rn";
                    $body .= "Content-Disposition: attachment; filename=" . $file_name . "rn";
                    $body .= "Content-Transfer-Encoding: base64rn";
                    $body .= "X-Attachment-Id: " . rand(1000, 99999) . "rnrn";
                    $body .= $encoded_content;
                    }
                    }
                    } else { //send plain email otherwise
                    $headers = "From:" . $from_email . "rn" .
                    "Reply-To: " . $sender_email . "n" .
                    "X-Mailer: PHP/" . phpversion();
                    $body = $sender_message;
                    }

                    $sentMail = @mail($recipient_email, $subject, $body, $headers);
                    if ($sentMail) { //output success or failure messages
                    die('Thank you for your email');
                    } else {
                    die('Could not send mail! Please check your PHP mail configuration.');
                    }
                    }
                    ?>





                    share|improve this answer














                    This works for me. It also attaches multiple attachments too. easily



                    <?php

                    if ($_POST && isset($_FILES['file'])) {
                    $recipient_email = "recipient@yourmail.com"; //recepient
                    $from_email = "info@your_domain.com"; //from email using site domain.
                    $subject = "Attachment email from your website!"; //email subject line

                    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
                    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
                    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
                    $attachments = $_FILES['file'];

                    //php validation
                    if (strlen($sender_name) < 4) {
                    die('Name is too short or empty');
                    }
                    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
                    die('Invalid email');
                    }
                    if (strlen($sender_message) < 4) {
                    die('Too short message! Please enter something');
                    }

                    $file_count = count($attachments['name']); //count total files attached
                    $boundary = md5("specialToken$4332"); // boundary token to be used

                    if ($file_count > 0) { //if attachment exists
                    //header
                    $headers = "MIME-Version: 1.0rn";
                    $headers .= "From:" . $from_email . "rn";
                    $headers .= "Reply-To: " . $sender_email . "" . "rn";
                    $headers .= "Content-Type: multipart/mixed; boundary = $boundaryrnrn";

                    //message text
                    $body = "--$boundaryrn";
                    $body .= "Content-Type: text/plain; charset=ISO-8859-1rn";
                    $body .= "Content-Transfer-Encoding: base64rnrn";
                    $body .= chunk_split(base64_encode($sender_message));

                    //attachments
                    for ($x = 0; $x < $file_count; $x++) {
                    if (!empty($attachments['name'][$x])) {

                    if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
                    $mymsg = array(
                    1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                    2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                    3 => "The uploaded file was only partially uploaded",
                    4 => "No file was uploaded",
                    6 => "Missing a temporary folder");
                    die($mymsg[$attachments['error'][$x]]);
                    }

                    //get file info
                    $file_name = $attachments['name'][$x];
                    $file_size = $attachments['size'][$x];
                    $file_type = $attachments['type'][$x];

                    //read file
                    $handle = fopen($attachments['tmp_name'][$x], "r");
                    $content = fread($handle, $file_size);
                    fclose($handle);
                    $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                    $body .= "--$boundaryrn";
                    $body .= "Content-Type: $file_type; name=" . $file_name . "rn";
                    $body .= "Content-Disposition: attachment; filename=" . $file_name . "rn";
                    $body .= "Content-Transfer-Encoding: base64rn";
                    $body .= "X-Attachment-Id: " . rand(1000, 99999) . "rnrn";
                    $body .= $encoded_content;
                    }
                    }
                    } else { //send plain email otherwise
                    $headers = "From:" . $from_email . "rn" .
                    "Reply-To: " . $sender_email . "n" .
                    "X-Mailer: PHP/" . phpversion();
                    $body = $sender_message;
                    }

                    $sentMail = @mail($recipient_email, $subject, $body, $headers);
                    if ($sentMail) { //output success or failure messages
                    die('Thank you for your email');
                    } else {
                    die('Could not send mail! Please check your PHP mail configuration.');
                    }
                    }
                    ?>






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 27 at 9:48

























                    answered Apr 21 '17 at 8:13









                    Akintunde-Rotimi

                    3,65631123




                    3,65631123












                    • This code is vulnerable to header injection attacks due to the lack of validation & appropriate contextual escaping of user input.
                      – Synchro
                      Oct 31 at 13:41


















                    • This code is vulnerable to header injection attacks due to the lack of validation & appropriate contextual escaping of user input.
                      – Synchro
                      Oct 31 at 13:41
















                    This code is vulnerable to header injection attacks due to the lack of validation & appropriate contextual escaping of user input.
                    – Synchro
                    Oct 31 at 13:41




                    This code is vulnerable to header injection attacks due to the lack of validation & appropriate contextual escaping of user input.
                    – Synchro
                    Oct 31 at 13:41










                    up vote
                    3
                    down vote













                    None of the above answers worked for me due to their specified attachment format (application/octet-stream). Use application/pdf for best results with PDF files.



                    <?php

                    // just edit these
                    $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

                    // creates headers and mime boundary
                    $eol = PHP_EOL;
                    $semi_rand = md5(time());
                    $mime_boundary = "==Multipart_Boundary_$semi_rand";
                    $headers = "From: $from$eolMIME-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";

                    // fetches pdf
                    $file = fopen($pdfLocation, 'rb');
                    $data = fread($file, filesize($pdfLocation));
                    fclose($file);
                    $pdf = chunk_split(base64_encode($data));

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

                    // Sends the email
                    if(mail($to, $subject, $message, $headers)) {
                    echo "The email was sent.";
                    }
                    else {
                    echo "There was an error sending the mail.";
                    }





                    share|improve this answer



























                      up vote
                      3
                      down vote













                      None of the above answers worked for me due to their specified attachment format (application/octet-stream). Use application/pdf for best results with PDF files.



                      <?php

                      // just edit these
                      $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

                      // creates headers and mime boundary
                      $eol = PHP_EOL;
                      $semi_rand = md5(time());
                      $mime_boundary = "==Multipart_Boundary_$semi_rand";
                      $headers = "From: $from$eolMIME-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";

                      // fetches pdf
                      $file = fopen($pdfLocation, 'rb');
                      $data = fread($file, filesize($pdfLocation));
                      fclose($file);
                      $pdf = chunk_split(base64_encode($data));

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

                      // Sends the email
                      if(mail($to, $subject, $message, $headers)) {
                      echo "The email was sent.";
                      }
                      else {
                      echo "There was an error sending the mail.";
                      }





                      share|improve this answer

























                        up vote
                        3
                        down vote










                        up vote
                        3
                        down vote









                        None of the above answers worked for me due to their specified attachment format (application/octet-stream). Use application/pdf for best results with PDF files.



                        <?php

                        // just edit these
                        $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

                        // creates headers and mime boundary
                        $eol = PHP_EOL;
                        $semi_rand = md5(time());
                        $mime_boundary = "==Multipart_Boundary_$semi_rand";
                        $headers = "From: $from$eolMIME-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";

                        // fetches pdf
                        $file = fopen($pdfLocation, 'rb');
                        $data = fread($file, filesize($pdfLocation));
                        fclose($file);
                        $pdf = chunk_split(base64_encode($data));

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

                        // Sends the email
                        if(mail($to, $subject, $message, $headers)) {
                        echo "The email was sent.";
                        }
                        else {
                        echo "There was an error sending the mail.";
                        }





                        share|improve this answer














                        None of the above answers worked for me due to their specified attachment format (application/octet-stream). Use application/pdf for best results with PDF files.



                        <?php

                        // just edit these
                        $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

                        // creates headers and mime boundary
                        $eol = PHP_EOL;
                        $semi_rand = md5(time());
                        $mime_boundary = "==Multipart_Boundary_$semi_rand";
                        $headers = "From: $from$eolMIME-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";

                        // fetches pdf
                        $file = fopen($pdfLocation, 'rb');
                        $data = fread($file, filesize($pdfLocation));
                        fclose($file);
                        $pdf = chunk_split(base64_encode($data));

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

                        // Sends the email
                        if(mail($to, $subject, $message, $headers)) {
                        echo "The email was sent.";
                        }
                        else {
                        echo "There was an error sending the mail.";
                        }






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Mar 29 at 20:32

























                        answered Mar 28 at 18:56









                        oMiKeY

                        2,89351839




                        2,89351839






















                            up vote
                            1
                            down vote













                            I ended up writing my own email sending/encoding function. This has worked well for me for sending PDF attachments. I have not used the other features in production.



                            Note: Despite the spec being quite emphatic that you must use rn to separate headers, I found it only worked when I used PHP_EOL. I have only tested this on Linux. YMMV



                            <?php
                            # $args must be an associative array
                            # required keys: from, to, body
                            # body can be a string or a [tree of] associative arrays. See examples below
                            # optional keys: subject, reply_to, cc, bcc
                            # EXAMPLES:
                            # # text-only email:
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/plain because we're passing a string that doesn't start with '<'
                            # 'body' => 'Hi, testing 1 2 3',
                            # ));
                            #
                            # # html-only email
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/html because we're passing a string that starts with '<'
                            # 'body' => '<h1>Hi!</h1>I like <a href="http://cheese.com">cheese</a>',
                            # ));
                            #
                            # # text-only email (explicitly, in case first character is dynamic or something)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/plain because we're passing a string that doesn't start with '<'
                            # 'body' => array(
                            # 'type' => 'text',
                            # 'body' => $message_text,
                            # )
                            # ));
                            #
                            # # email with text and html alternatives (auto-detected mime types)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'alternatives',
                            # 'body' => array(
                            # "Hi!nnI like cheese",
                            # '<h1>Hi!</h1><p>I like <a href="http://cheese.com">cheese</a></p>',
                            # )
                            # )
                            # ));
                            #
                            # # email with text and html alternatives (explicit types)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'alternatives',
                            # 'body' => array(
                            # array(
                            # 'type' => 'text',
                            # 'body' => "Hi!nnI like cheese",
                            # ),
                            # array(
                            # 'type' => 'html',
                            # 'body' => '<h1>Hi!</h1><p>I like cheese</p>',
                            # ),
                            # )
                            # )
                            # ));
                            #
                            # # email with an attachment
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'mixed',
                            # 'body' => array(
                            # "Hi!nnCheck out this (inline) image",
                            # array(
                            # 'type' => 'image/png',
                            # 'disposition' => 'inline',
                            # 'body' => $image_data, # raw file contents
                            # ),
                            # "Hi!nnAnd here's an attachment",
                            # array(
                            # 'type' => 'application/pdf; name="attachment.pdf"',
                            # 'disposition' => 'attachment; filename="attachment.pdf"',
                            # 'body' => $pdf_data, # raw file contents
                            # ),
                            # "Or you can use shorthand:",
                            # array(
                            # 'type' => 'application/pdf',
                            # 'attachment' => 'attachment.pdf', # name for client (not data source)
                            # 'body' => $pdf_data, # raw file contents
                            # ),
                            # )
                            # )
                            # ))
                            function email2($args) {
                            if (!isset($args['from'])) { return 1; }
                            $from = $args['from'];
                            if (!isset($args['to'])) { return 2; }
                            $to = $args['to'];
                            $subject = isset($args['subject']) ? $args['subject'] : '';
                            $reply_to = isset($args['reply_to']) ? $args['reply_to'] : '';
                            $cc = isset($args['cc']) ? $args['cc'] : '';
                            $bcc = isset($args['bcc']) ? $args['bcc'] : '';

                            #FIXME should allow many more characters here (and do Q encoding)
                            $subject = isset($args['subject']) ? $args['subject'] : '';
                            $subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);

                            $headers = "From: $from";
                            if($reply_to) {
                            $headers .= PHP_EOL . "Reply-To: $reply_to";
                            }
                            if($cc) {
                            $headers .= PHP_EOL . "CC: $cc";
                            }
                            if($bcc) {
                            $headers .= PHP_EOL . "BCC: $bcc";
                            }

                            $r = email2_helper($args['body']);
                            $headers .= PHP_EOL . $r[0];
                            $body = $r[1];

                            if (mail($to, $subject, $body, $headers)) {
                            return 0;
                            } else {
                            return 5;
                            }
                            }

                            function email2_helper($body, $top = true) {
                            if (is_string($body)) {
                            if (substr($body, 0, 1) == '<') {
                            return email2_helper(array('type' => 'html', 'body' => $body), $top);
                            } else {
                            return email2_helper(array('type' => 'text', 'body' => $body), $top);
                            }
                            }
                            # now we can assume $body is an associative array
                            # defaults:
                            $type = 'application/octet-stream';
                            $mime = false;
                            $boundary = null;
                            $disposition = null;
                            $charset = false;
                            # process 'type' first, because it sets defaults for others
                            if (isset($body['type'])) {
                            $type = $body['type'];
                            if ($type === 'text') {
                            $type = 'text/plain';
                            $charset = true;
                            } elseif ($type === 'html') {
                            $type = 'text/html';
                            $charset = true;
                            } elseif ($type === 'alternative' || $type === 'alternatives') {
                            $mime = true;
                            $type = 'multipart/alternative';
                            } elseif ($type === 'mixed') {
                            $mime = true;
                            $type = 'multipart/mixed';
                            }
                            }
                            if (isset($body['disposition'])) {
                            $disposition = $body['disposition'];
                            }
                            if (isset($body['attachment'])) {
                            if ($disposition == null) {
                            $disposition = 'attachment';
                            }
                            $disposition .= "; filename="{$body['attachment']}"";
                            $type .= "; name="{$body['attachment']}"";
                            }
                            # make headers
                            $headers = array();
                            if ($top && $mime) {
                            $headers = 'MIME-Version: 1.0';
                            }
                            if ($mime) {
                            $boundary = md5('5sd^%Ca)~aAfF0=4mIN' . rand() . rand());
                            $type .= "; boundary=$boundary";
                            }
                            if ($charset) {
                            $type .= '; charset=' . (isset($body['charset']) ? $body['charset'] : 'UTF-8');
                            }
                            $headers = "Content-Type: $type";
                            if ($disposition !== null) {
                            $headers = "Content-Disposition: {$disposition}";
                            }

                            $data = '';
                            # return array, first el is headers, 2nd is body (php's mail() needs them separate)
                            if ($mime) {
                            foreach ($body['body'] as $sub_body) {
                            $data .= "--$boundary" . PHP_EOL;
                            $r = email2_helper($sub_body, false);
                            $data .= $r[0] . PHP_EOL . PHP_EOL; # headers
                            $data .= $r[1] . PHP_EOL . PHP_EOL; # body
                            }
                            $data .= "--$boundary--";
                            } else {
                            if(preg_match('/[^x09x0Ax0Dx20-x7E]/', $body['body'])) {
                            $headers = "Content-Transfer-Encoding: base64";
                            $data .= chunk_split(base64_encode($body['body']));
                            } else {
                            $data .= $body['body'];
                            }
                            }
                            return array(join(PHP_EOL, $headers), $data);
                            }





                            share|improve this answer























                            • I just realized that my code called some functions that I didn't include. They just made sure that to/from/cc/etc values were legit. I removed them, and now this code works as is, by itself.
                              – JasonWoof
                              May 6 '17 at 23:25















                            up vote
                            1
                            down vote













                            I ended up writing my own email sending/encoding function. This has worked well for me for sending PDF attachments. I have not used the other features in production.



                            Note: Despite the spec being quite emphatic that you must use rn to separate headers, I found it only worked when I used PHP_EOL. I have only tested this on Linux. YMMV



                            <?php
                            # $args must be an associative array
                            # required keys: from, to, body
                            # body can be a string or a [tree of] associative arrays. See examples below
                            # optional keys: subject, reply_to, cc, bcc
                            # EXAMPLES:
                            # # text-only email:
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/plain because we're passing a string that doesn't start with '<'
                            # 'body' => 'Hi, testing 1 2 3',
                            # ));
                            #
                            # # html-only email
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/html because we're passing a string that starts with '<'
                            # 'body' => '<h1>Hi!</h1>I like <a href="http://cheese.com">cheese</a>',
                            # ));
                            #
                            # # text-only email (explicitly, in case first character is dynamic or something)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/plain because we're passing a string that doesn't start with '<'
                            # 'body' => array(
                            # 'type' => 'text',
                            # 'body' => $message_text,
                            # )
                            # ));
                            #
                            # # email with text and html alternatives (auto-detected mime types)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'alternatives',
                            # 'body' => array(
                            # "Hi!nnI like cheese",
                            # '<h1>Hi!</h1><p>I like <a href="http://cheese.com">cheese</a></p>',
                            # )
                            # )
                            # ));
                            #
                            # # email with text and html alternatives (explicit types)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'alternatives',
                            # 'body' => array(
                            # array(
                            # 'type' => 'text',
                            # 'body' => "Hi!nnI like cheese",
                            # ),
                            # array(
                            # 'type' => 'html',
                            # 'body' => '<h1>Hi!</h1><p>I like cheese</p>',
                            # ),
                            # )
                            # )
                            # ));
                            #
                            # # email with an attachment
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'mixed',
                            # 'body' => array(
                            # "Hi!nnCheck out this (inline) image",
                            # array(
                            # 'type' => 'image/png',
                            # 'disposition' => 'inline',
                            # 'body' => $image_data, # raw file contents
                            # ),
                            # "Hi!nnAnd here's an attachment",
                            # array(
                            # 'type' => 'application/pdf; name="attachment.pdf"',
                            # 'disposition' => 'attachment; filename="attachment.pdf"',
                            # 'body' => $pdf_data, # raw file contents
                            # ),
                            # "Or you can use shorthand:",
                            # array(
                            # 'type' => 'application/pdf',
                            # 'attachment' => 'attachment.pdf', # name for client (not data source)
                            # 'body' => $pdf_data, # raw file contents
                            # ),
                            # )
                            # )
                            # ))
                            function email2($args) {
                            if (!isset($args['from'])) { return 1; }
                            $from = $args['from'];
                            if (!isset($args['to'])) { return 2; }
                            $to = $args['to'];
                            $subject = isset($args['subject']) ? $args['subject'] : '';
                            $reply_to = isset($args['reply_to']) ? $args['reply_to'] : '';
                            $cc = isset($args['cc']) ? $args['cc'] : '';
                            $bcc = isset($args['bcc']) ? $args['bcc'] : '';

                            #FIXME should allow many more characters here (and do Q encoding)
                            $subject = isset($args['subject']) ? $args['subject'] : '';
                            $subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);

                            $headers = "From: $from";
                            if($reply_to) {
                            $headers .= PHP_EOL . "Reply-To: $reply_to";
                            }
                            if($cc) {
                            $headers .= PHP_EOL . "CC: $cc";
                            }
                            if($bcc) {
                            $headers .= PHP_EOL . "BCC: $bcc";
                            }

                            $r = email2_helper($args['body']);
                            $headers .= PHP_EOL . $r[0];
                            $body = $r[1];

                            if (mail($to, $subject, $body, $headers)) {
                            return 0;
                            } else {
                            return 5;
                            }
                            }

                            function email2_helper($body, $top = true) {
                            if (is_string($body)) {
                            if (substr($body, 0, 1) == '<') {
                            return email2_helper(array('type' => 'html', 'body' => $body), $top);
                            } else {
                            return email2_helper(array('type' => 'text', 'body' => $body), $top);
                            }
                            }
                            # now we can assume $body is an associative array
                            # defaults:
                            $type = 'application/octet-stream';
                            $mime = false;
                            $boundary = null;
                            $disposition = null;
                            $charset = false;
                            # process 'type' first, because it sets defaults for others
                            if (isset($body['type'])) {
                            $type = $body['type'];
                            if ($type === 'text') {
                            $type = 'text/plain';
                            $charset = true;
                            } elseif ($type === 'html') {
                            $type = 'text/html';
                            $charset = true;
                            } elseif ($type === 'alternative' || $type === 'alternatives') {
                            $mime = true;
                            $type = 'multipart/alternative';
                            } elseif ($type === 'mixed') {
                            $mime = true;
                            $type = 'multipart/mixed';
                            }
                            }
                            if (isset($body['disposition'])) {
                            $disposition = $body['disposition'];
                            }
                            if (isset($body['attachment'])) {
                            if ($disposition == null) {
                            $disposition = 'attachment';
                            }
                            $disposition .= "; filename="{$body['attachment']}"";
                            $type .= "; name="{$body['attachment']}"";
                            }
                            # make headers
                            $headers = array();
                            if ($top && $mime) {
                            $headers = 'MIME-Version: 1.0';
                            }
                            if ($mime) {
                            $boundary = md5('5sd^%Ca)~aAfF0=4mIN' . rand() . rand());
                            $type .= "; boundary=$boundary";
                            }
                            if ($charset) {
                            $type .= '; charset=' . (isset($body['charset']) ? $body['charset'] : 'UTF-8');
                            }
                            $headers = "Content-Type: $type";
                            if ($disposition !== null) {
                            $headers = "Content-Disposition: {$disposition}";
                            }

                            $data = '';
                            # return array, first el is headers, 2nd is body (php's mail() needs them separate)
                            if ($mime) {
                            foreach ($body['body'] as $sub_body) {
                            $data .= "--$boundary" . PHP_EOL;
                            $r = email2_helper($sub_body, false);
                            $data .= $r[0] . PHP_EOL . PHP_EOL; # headers
                            $data .= $r[1] . PHP_EOL . PHP_EOL; # body
                            }
                            $data .= "--$boundary--";
                            } else {
                            if(preg_match('/[^x09x0Ax0Dx20-x7E]/', $body['body'])) {
                            $headers = "Content-Transfer-Encoding: base64";
                            $data .= chunk_split(base64_encode($body['body']));
                            } else {
                            $data .= $body['body'];
                            }
                            }
                            return array(join(PHP_EOL, $headers), $data);
                            }





                            share|improve this answer























                            • I just realized that my code called some functions that I didn't include. They just made sure that to/from/cc/etc values were legit. I removed them, and now this code works as is, by itself.
                              – JasonWoof
                              May 6 '17 at 23:25













                            up vote
                            1
                            down vote










                            up vote
                            1
                            down vote









                            I ended up writing my own email sending/encoding function. This has worked well for me for sending PDF attachments. I have not used the other features in production.



                            Note: Despite the spec being quite emphatic that you must use rn to separate headers, I found it only worked when I used PHP_EOL. I have only tested this on Linux. YMMV



                            <?php
                            # $args must be an associative array
                            # required keys: from, to, body
                            # body can be a string or a [tree of] associative arrays. See examples below
                            # optional keys: subject, reply_to, cc, bcc
                            # EXAMPLES:
                            # # text-only email:
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/plain because we're passing a string that doesn't start with '<'
                            # 'body' => 'Hi, testing 1 2 3',
                            # ));
                            #
                            # # html-only email
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/html because we're passing a string that starts with '<'
                            # 'body' => '<h1>Hi!</h1>I like <a href="http://cheese.com">cheese</a>',
                            # ));
                            #
                            # # text-only email (explicitly, in case first character is dynamic or something)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/plain because we're passing a string that doesn't start with '<'
                            # 'body' => array(
                            # 'type' => 'text',
                            # 'body' => $message_text,
                            # )
                            # ));
                            #
                            # # email with text and html alternatives (auto-detected mime types)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'alternatives',
                            # 'body' => array(
                            # "Hi!nnI like cheese",
                            # '<h1>Hi!</h1><p>I like <a href="http://cheese.com">cheese</a></p>',
                            # )
                            # )
                            # ));
                            #
                            # # email with text and html alternatives (explicit types)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'alternatives',
                            # 'body' => array(
                            # array(
                            # 'type' => 'text',
                            # 'body' => "Hi!nnI like cheese",
                            # ),
                            # array(
                            # 'type' => 'html',
                            # 'body' => '<h1>Hi!</h1><p>I like cheese</p>',
                            # ),
                            # )
                            # )
                            # ));
                            #
                            # # email with an attachment
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'mixed',
                            # 'body' => array(
                            # "Hi!nnCheck out this (inline) image",
                            # array(
                            # 'type' => 'image/png',
                            # 'disposition' => 'inline',
                            # 'body' => $image_data, # raw file contents
                            # ),
                            # "Hi!nnAnd here's an attachment",
                            # array(
                            # 'type' => 'application/pdf; name="attachment.pdf"',
                            # 'disposition' => 'attachment; filename="attachment.pdf"',
                            # 'body' => $pdf_data, # raw file contents
                            # ),
                            # "Or you can use shorthand:",
                            # array(
                            # 'type' => 'application/pdf',
                            # 'attachment' => 'attachment.pdf', # name for client (not data source)
                            # 'body' => $pdf_data, # raw file contents
                            # ),
                            # )
                            # )
                            # ))
                            function email2($args) {
                            if (!isset($args['from'])) { return 1; }
                            $from = $args['from'];
                            if (!isset($args['to'])) { return 2; }
                            $to = $args['to'];
                            $subject = isset($args['subject']) ? $args['subject'] : '';
                            $reply_to = isset($args['reply_to']) ? $args['reply_to'] : '';
                            $cc = isset($args['cc']) ? $args['cc'] : '';
                            $bcc = isset($args['bcc']) ? $args['bcc'] : '';

                            #FIXME should allow many more characters here (and do Q encoding)
                            $subject = isset($args['subject']) ? $args['subject'] : '';
                            $subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);

                            $headers = "From: $from";
                            if($reply_to) {
                            $headers .= PHP_EOL . "Reply-To: $reply_to";
                            }
                            if($cc) {
                            $headers .= PHP_EOL . "CC: $cc";
                            }
                            if($bcc) {
                            $headers .= PHP_EOL . "BCC: $bcc";
                            }

                            $r = email2_helper($args['body']);
                            $headers .= PHP_EOL . $r[0];
                            $body = $r[1];

                            if (mail($to, $subject, $body, $headers)) {
                            return 0;
                            } else {
                            return 5;
                            }
                            }

                            function email2_helper($body, $top = true) {
                            if (is_string($body)) {
                            if (substr($body, 0, 1) == '<') {
                            return email2_helper(array('type' => 'html', 'body' => $body), $top);
                            } else {
                            return email2_helper(array('type' => 'text', 'body' => $body), $top);
                            }
                            }
                            # now we can assume $body is an associative array
                            # defaults:
                            $type = 'application/octet-stream';
                            $mime = false;
                            $boundary = null;
                            $disposition = null;
                            $charset = false;
                            # process 'type' first, because it sets defaults for others
                            if (isset($body['type'])) {
                            $type = $body['type'];
                            if ($type === 'text') {
                            $type = 'text/plain';
                            $charset = true;
                            } elseif ($type === 'html') {
                            $type = 'text/html';
                            $charset = true;
                            } elseif ($type === 'alternative' || $type === 'alternatives') {
                            $mime = true;
                            $type = 'multipart/alternative';
                            } elseif ($type === 'mixed') {
                            $mime = true;
                            $type = 'multipart/mixed';
                            }
                            }
                            if (isset($body['disposition'])) {
                            $disposition = $body['disposition'];
                            }
                            if (isset($body['attachment'])) {
                            if ($disposition == null) {
                            $disposition = 'attachment';
                            }
                            $disposition .= "; filename="{$body['attachment']}"";
                            $type .= "; name="{$body['attachment']}"";
                            }
                            # make headers
                            $headers = array();
                            if ($top && $mime) {
                            $headers = 'MIME-Version: 1.0';
                            }
                            if ($mime) {
                            $boundary = md5('5sd^%Ca)~aAfF0=4mIN' . rand() . rand());
                            $type .= "; boundary=$boundary";
                            }
                            if ($charset) {
                            $type .= '; charset=' . (isset($body['charset']) ? $body['charset'] : 'UTF-8');
                            }
                            $headers = "Content-Type: $type";
                            if ($disposition !== null) {
                            $headers = "Content-Disposition: {$disposition}";
                            }

                            $data = '';
                            # return array, first el is headers, 2nd is body (php's mail() needs them separate)
                            if ($mime) {
                            foreach ($body['body'] as $sub_body) {
                            $data .= "--$boundary" . PHP_EOL;
                            $r = email2_helper($sub_body, false);
                            $data .= $r[0] . PHP_EOL . PHP_EOL; # headers
                            $data .= $r[1] . PHP_EOL . PHP_EOL; # body
                            }
                            $data .= "--$boundary--";
                            } else {
                            if(preg_match('/[^x09x0Ax0Dx20-x7E]/', $body['body'])) {
                            $headers = "Content-Transfer-Encoding: base64";
                            $data .= chunk_split(base64_encode($body['body']));
                            } else {
                            $data .= $body['body'];
                            }
                            }
                            return array(join(PHP_EOL, $headers), $data);
                            }





                            share|improve this answer














                            I ended up writing my own email sending/encoding function. This has worked well for me for sending PDF attachments. I have not used the other features in production.



                            Note: Despite the spec being quite emphatic that you must use rn to separate headers, I found it only worked when I used PHP_EOL. I have only tested this on Linux. YMMV



                            <?php
                            # $args must be an associative array
                            # required keys: from, to, body
                            # body can be a string or a [tree of] associative arrays. See examples below
                            # optional keys: subject, reply_to, cc, bcc
                            # EXAMPLES:
                            # # text-only email:
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/plain because we're passing a string that doesn't start with '<'
                            # 'body' => 'Hi, testing 1 2 3',
                            # ));
                            #
                            # # html-only email
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/html because we're passing a string that starts with '<'
                            # 'body' => '<h1>Hi!</h1>I like <a href="http://cheese.com">cheese</a>',
                            # ));
                            #
                            # # text-only email (explicitly, in case first character is dynamic or something)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # # body will be text/plain because we're passing a string that doesn't start with '<'
                            # 'body' => array(
                            # 'type' => 'text',
                            # 'body' => $message_text,
                            # )
                            # ));
                            #
                            # # email with text and html alternatives (auto-detected mime types)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'alternatives',
                            # 'body' => array(
                            # "Hi!nnI like cheese",
                            # '<h1>Hi!</h1><p>I like <a href="http://cheese.com">cheese</a></p>',
                            # )
                            # )
                            # ));
                            #
                            # # email with text and html alternatives (explicit types)
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'alternatives',
                            # 'body' => array(
                            # array(
                            # 'type' => 'text',
                            # 'body' => "Hi!nnI like cheese",
                            # ),
                            # array(
                            # 'type' => 'html',
                            # 'body' => '<h1>Hi!</h1><p>I like cheese</p>',
                            # ),
                            # )
                            # )
                            # ));
                            #
                            # # email with an attachment
                            # email2(array(
                            # 'from' => 'noreply@foo.com',
                            # 'to' => 'jason@jasonwoof.com',
                            # 'subject' => 'test',
                            # 'body' => array(
                            # 'type' => 'mixed',
                            # 'body' => array(
                            # "Hi!nnCheck out this (inline) image",
                            # array(
                            # 'type' => 'image/png',
                            # 'disposition' => 'inline',
                            # 'body' => $image_data, # raw file contents
                            # ),
                            # "Hi!nnAnd here's an attachment",
                            # array(
                            # 'type' => 'application/pdf; name="attachment.pdf"',
                            # 'disposition' => 'attachment; filename="attachment.pdf"',
                            # 'body' => $pdf_data, # raw file contents
                            # ),
                            # "Or you can use shorthand:",
                            # array(
                            # 'type' => 'application/pdf',
                            # 'attachment' => 'attachment.pdf', # name for client (not data source)
                            # 'body' => $pdf_data, # raw file contents
                            # ),
                            # )
                            # )
                            # ))
                            function email2($args) {
                            if (!isset($args['from'])) { return 1; }
                            $from = $args['from'];
                            if (!isset($args['to'])) { return 2; }
                            $to = $args['to'];
                            $subject = isset($args['subject']) ? $args['subject'] : '';
                            $reply_to = isset($args['reply_to']) ? $args['reply_to'] : '';
                            $cc = isset($args['cc']) ? $args['cc'] : '';
                            $bcc = isset($args['bcc']) ? $args['bcc'] : '';

                            #FIXME should allow many more characters here (and do Q encoding)
                            $subject = isset($args['subject']) ? $args['subject'] : '';
                            $subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);

                            $headers = "From: $from";
                            if($reply_to) {
                            $headers .= PHP_EOL . "Reply-To: $reply_to";
                            }
                            if($cc) {
                            $headers .= PHP_EOL . "CC: $cc";
                            }
                            if($bcc) {
                            $headers .= PHP_EOL . "BCC: $bcc";
                            }

                            $r = email2_helper($args['body']);
                            $headers .= PHP_EOL . $r[0];
                            $body = $r[1];

                            if (mail($to, $subject, $body, $headers)) {
                            return 0;
                            } else {
                            return 5;
                            }
                            }

                            function email2_helper($body, $top = true) {
                            if (is_string($body)) {
                            if (substr($body, 0, 1) == '<') {
                            return email2_helper(array('type' => 'html', 'body' => $body), $top);
                            } else {
                            return email2_helper(array('type' => 'text', 'body' => $body), $top);
                            }
                            }
                            # now we can assume $body is an associative array
                            # defaults:
                            $type = 'application/octet-stream';
                            $mime = false;
                            $boundary = null;
                            $disposition = null;
                            $charset = false;
                            # process 'type' first, because it sets defaults for others
                            if (isset($body['type'])) {
                            $type = $body['type'];
                            if ($type === 'text') {
                            $type = 'text/plain';
                            $charset = true;
                            } elseif ($type === 'html') {
                            $type = 'text/html';
                            $charset = true;
                            } elseif ($type === 'alternative' || $type === 'alternatives') {
                            $mime = true;
                            $type = 'multipart/alternative';
                            } elseif ($type === 'mixed') {
                            $mime = true;
                            $type = 'multipart/mixed';
                            }
                            }
                            if (isset($body['disposition'])) {
                            $disposition = $body['disposition'];
                            }
                            if (isset($body['attachment'])) {
                            if ($disposition == null) {
                            $disposition = 'attachment';
                            }
                            $disposition .= "; filename="{$body['attachment']}"";
                            $type .= "; name="{$body['attachment']}"";
                            }
                            # make headers
                            $headers = array();
                            if ($top && $mime) {
                            $headers = 'MIME-Version: 1.0';
                            }
                            if ($mime) {
                            $boundary = md5('5sd^%Ca)~aAfF0=4mIN' . rand() . rand());
                            $type .= "; boundary=$boundary";
                            }
                            if ($charset) {
                            $type .= '; charset=' . (isset($body['charset']) ? $body['charset'] : 'UTF-8');
                            }
                            $headers = "Content-Type: $type";
                            if ($disposition !== null) {
                            $headers = "Content-Disposition: {$disposition}";
                            }

                            $data = '';
                            # return array, first el is headers, 2nd is body (php's mail() needs them separate)
                            if ($mime) {
                            foreach ($body['body'] as $sub_body) {
                            $data .= "--$boundary" . PHP_EOL;
                            $r = email2_helper($sub_body, false);
                            $data .= $r[0] . PHP_EOL . PHP_EOL; # headers
                            $data .= $r[1] . PHP_EOL . PHP_EOL; # body
                            }
                            $data .= "--$boundary--";
                            } else {
                            if(preg_match('/[^x09x0Ax0Dx20-x7E]/', $body['body'])) {
                            $headers = "Content-Transfer-Encoding: base64";
                            $data .= chunk_split(base64_encode($body['body']));
                            } else {
                            $data .= $body['body'];
                            }
                            }
                            return array(join(PHP_EOL, $headers), $data);
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited May 6 '17 at 23:24

























                            answered Jan 11 '17 at 0:10









                            JasonWoof

                            3,34011225




                            3,34011225












                            • I just realized that my code called some functions that I didn't include. They just made sure that to/from/cc/etc values were legit. I removed them, and now this code works as is, by itself.
                              – JasonWoof
                              May 6 '17 at 23:25


















                            • I just realized that my code called some functions that I didn't include. They just made sure that to/from/cc/etc values were legit. I removed them, and now this code works as is, by itself.
                              – JasonWoof
                              May 6 '17 at 23:25
















                            I just realized that my code called some functions that I didn't include. They just made sure that to/from/cc/etc values were legit. I removed them, and now this code works as is, by itself.
                            – JasonWoof
                            May 6 '17 at 23:25




                            I just realized that my code called some functions that I didn't include. They just made sure that to/from/cc/etc values were legit. I removed them, and now this code works as is, by itself.
                            – JasonWoof
                            May 6 '17 at 23:25










                            up vote
                            1
                            down vote













                                        $to = "to@gmail.com";
                            $subject = "Subject Of The Mail";
                            $message = "Hi there,<br/><br/>This is my message.<br><br>";

                            $headers = "From: From-Name<from@gmail.com>";
                            // boundary
                            $semi_rand = md5(time());
                            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

                            // headers for attachment
                            $headers .= "nMIME-Version: 1.0n" . "Content-Type: multipart/mixed;n" . " boundary="{$mime_boundary}"";

                            // multipart boundary
                            $message = "This is a multi-part message in MIME format.nn" . "--{$mime_boundary}n" . "Content-Type: text/html; charset=ISO-8859-1"n" . "Content-Transfer-Encoding: 7bitnn" . $message . "nn";

                            $message .= "--{$mime_boundary}n";
                            $filepath = 'uploads/'.$_FILES['image']['name'];
                            move_uploaded_file($_FILES['image']['tmp_name'], $filepath); //upload the file
                            $filename = $_FILES['image']['name'];
                            $file = fopen($filepath, "rb");
                            $data = fread($file, filesize($filepath));
                            fclose($file);
                            $data = chunk_split(base64_encode($data));
                            $message .= "Content-Type: {"application/octet-stream"};n" . " name="$filename"n" .
                            "Content-Disposition: attachment;n" . " filename="$filename"n" .
                            "Content-Transfer-Encoding: base64nn" . $data . "nn";
                            $message .= "--{$mime_boundary}n";

                            mail($to, $subject, $message, $headers);





                            share|improve this answer

























                              up vote
                              1
                              down vote













                                          $to = "to@gmail.com";
                              $subject = "Subject Of The Mail";
                              $message = "Hi there,<br/><br/>This is my message.<br><br>";

                              $headers = "From: From-Name<from@gmail.com>";
                              // boundary
                              $semi_rand = md5(time());
                              $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

                              // headers for attachment
                              $headers .= "nMIME-Version: 1.0n" . "Content-Type: multipart/mixed;n" . " boundary="{$mime_boundary}"";

                              // multipart boundary
                              $message = "This is a multi-part message in MIME format.nn" . "--{$mime_boundary}n" . "Content-Type: text/html; charset=ISO-8859-1"n" . "Content-Transfer-Encoding: 7bitnn" . $message . "nn";

                              $message .= "--{$mime_boundary}n";
                              $filepath = 'uploads/'.$_FILES['image']['name'];
                              move_uploaded_file($_FILES['image']['tmp_name'], $filepath); //upload the file
                              $filename = $_FILES['image']['name'];
                              $file = fopen($filepath, "rb");
                              $data = fread($file, filesize($filepath));
                              fclose($file);
                              $data = chunk_split(base64_encode($data));
                              $message .= "Content-Type: {"application/octet-stream"};n" . " name="$filename"n" .
                              "Content-Disposition: attachment;n" . " filename="$filename"n" .
                              "Content-Transfer-Encoding: base64nn" . $data . "nn";
                              $message .= "--{$mime_boundary}n";

                              mail($to, $subject, $message, $headers);





                              share|improve this answer























                                up vote
                                1
                                down vote










                                up vote
                                1
                                down vote









                                            $to = "to@gmail.com";
                                $subject = "Subject Of The Mail";
                                $message = "Hi there,<br/><br/>This is my message.<br><br>";

                                $headers = "From: From-Name<from@gmail.com>";
                                // boundary
                                $semi_rand = md5(time());
                                $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

                                // headers for attachment
                                $headers .= "nMIME-Version: 1.0n" . "Content-Type: multipart/mixed;n" . " boundary="{$mime_boundary}"";

                                // multipart boundary
                                $message = "This is a multi-part message in MIME format.nn" . "--{$mime_boundary}n" . "Content-Type: text/html; charset=ISO-8859-1"n" . "Content-Transfer-Encoding: 7bitnn" . $message . "nn";

                                $message .= "--{$mime_boundary}n";
                                $filepath = 'uploads/'.$_FILES['image']['name'];
                                move_uploaded_file($_FILES['image']['tmp_name'], $filepath); //upload the file
                                $filename = $_FILES['image']['name'];
                                $file = fopen($filepath, "rb");
                                $data = fread($file, filesize($filepath));
                                fclose($file);
                                $data = chunk_split(base64_encode($data));
                                $message .= "Content-Type: {"application/octet-stream"};n" . " name="$filename"n" .
                                "Content-Disposition: attachment;n" . " filename="$filename"n" .
                                "Content-Transfer-Encoding: base64nn" . $data . "nn";
                                $message .= "--{$mime_boundary}n";

                                mail($to, $subject, $message, $headers);





                                share|improve this answer












                                            $to = "to@gmail.com";
                                $subject = "Subject Of The Mail";
                                $message = "Hi there,<br/><br/>This is my message.<br><br>";

                                $headers = "From: From-Name<from@gmail.com>";
                                // boundary
                                $semi_rand = md5(time());
                                $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

                                // headers for attachment
                                $headers .= "nMIME-Version: 1.0n" . "Content-Type: multipart/mixed;n" . " boundary="{$mime_boundary}"";

                                // multipart boundary
                                $message = "This is a multi-part message in MIME format.nn" . "--{$mime_boundary}n" . "Content-Type: text/html; charset=ISO-8859-1"n" . "Content-Transfer-Encoding: 7bitnn" . $message . "nn";

                                $message .= "--{$mime_boundary}n";
                                $filepath = 'uploads/'.$_FILES['image']['name'];
                                move_uploaded_file($_FILES['image']['tmp_name'], $filepath); //upload the file
                                $filename = $_FILES['image']['name'];
                                $file = fopen($filepath, "rb");
                                $data = fread($file, filesize($filepath));
                                fclose($file);
                                $data = chunk_split(base64_encode($data));
                                $message .= "Content-Type: {"application/octet-stream"};n" . " name="$filename"n" .
                                "Content-Disposition: attachment;n" . " filename="$filename"n" .
                                "Content-Transfer-Encoding: base64nn" . $data . "nn";
                                $message .= "--{$mime_boundary}n";

                                mail($to, $subject, $message, $headers);






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Sep 21 '17 at 7:11









                                Dhawal Naik

                                16216




                                16216






















                                    up vote
                                    -1
                                    down vote













                                    Copying the code from this page - works in mail()



                                    He starts off my making a function mail_attachment that can be called later. Which he does later with his attachment code.



                                    <?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.">rn";
                                    $header .= "Reply-To: ".$replyto."rn";
                                    $header .= "MIME-Version: 1.0rn";
                                    $header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";
                                    $header .= "This is a multi-part message in MIME format.rn";
                                    $header .= "--".$uid."rn";
                                    $header .= "Content-type:text/plain; charset=iso-8859-1rn";
                                    $header .= "Content-Transfer-Encoding: 7bitrnrn";
                                    $header .= $message."rnrn";
                                    $header .= "--".$uid."rn";
                                    $header .= "Content-Type: application/octet-stream; name="".$filename.""rn"; // use different content types here
                                    $header .= "Content-Transfer-Encoding: base64rn";
                                    $header .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
                                    $header .= $content."rnrn";
                                    $header .= "--".$uid."--";
                                    if (mail($mailto, $subject, "", $header)) {
                                    echo "mail send ... OK"; // or use booleans here
                                    } else {
                                    echo "mail send ... ERROR!";
                                    }
                                    }

                                    //start editing and inputting attachment details here
                                    $my_file = "somefile.zip";
                                    $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,rndo you like this script? I hope it will help.rnrngr. Olaf";
                                    mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
                                    ?>


                                    He has more details on his page and answers some problems in the comments section.






                                    share|improve this answer

























                                      up vote
                                      -1
                                      down vote













                                      Copying the code from this page - works in mail()



                                      He starts off my making a function mail_attachment that can be called later. Which he does later with his attachment code.



                                      <?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.">rn";
                                      $header .= "Reply-To: ".$replyto."rn";
                                      $header .= "MIME-Version: 1.0rn";
                                      $header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";
                                      $header .= "This is a multi-part message in MIME format.rn";
                                      $header .= "--".$uid."rn";
                                      $header .= "Content-type:text/plain; charset=iso-8859-1rn";
                                      $header .= "Content-Transfer-Encoding: 7bitrnrn";
                                      $header .= $message."rnrn";
                                      $header .= "--".$uid."rn";
                                      $header .= "Content-Type: application/octet-stream; name="".$filename.""rn"; // use different content types here
                                      $header .= "Content-Transfer-Encoding: base64rn";
                                      $header .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
                                      $header .= $content."rnrn";
                                      $header .= "--".$uid."--";
                                      if (mail($mailto, $subject, "", $header)) {
                                      echo "mail send ... OK"; // or use booleans here
                                      } else {
                                      echo "mail send ... ERROR!";
                                      }
                                      }

                                      //start editing and inputting attachment details here
                                      $my_file = "somefile.zip";
                                      $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,rndo you like this script? I hope it will help.rnrngr. Olaf";
                                      mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
                                      ?>


                                      He has more details on his page and answers some problems in the comments section.






                                      share|improve this answer























                                        up vote
                                        -1
                                        down vote










                                        up vote
                                        -1
                                        down vote









                                        Copying the code from this page - works in mail()



                                        He starts off my making a function mail_attachment that can be called later. Which he does later with his attachment code.



                                        <?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.">rn";
                                        $header .= "Reply-To: ".$replyto."rn";
                                        $header .= "MIME-Version: 1.0rn";
                                        $header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";
                                        $header .= "This is a multi-part message in MIME format.rn";
                                        $header .= "--".$uid."rn";
                                        $header .= "Content-type:text/plain; charset=iso-8859-1rn";
                                        $header .= "Content-Transfer-Encoding: 7bitrnrn";
                                        $header .= $message."rnrn";
                                        $header .= "--".$uid."rn";
                                        $header .= "Content-Type: application/octet-stream; name="".$filename.""rn"; // use different content types here
                                        $header .= "Content-Transfer-Encoding: base64rn";
                                        $header .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
                                        $header .= $content."rnrn";
                                        $header .= "--".$uid."--";
                                        if (mail($mailto, $subject, "", $header)) {
                                        echo "mail send ... OK"; // or use booleans here
                                        } else {
                                        echo "mail send ... ERROR!";
                                        }
                                        }

                                        //start editing and inputting attachment details here
                                        $my_file = "somefile.zip";
                                        $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,rndo you like this script? I hope it will help.rnrngr. Olaf";
                                        mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
                                        ?>


                                        He has more details on his page and answers some problems in the comments section.






                                        share|improve this answer












                                        Copying the code from this page - works in mail()



                                        He starts off my making a function mail_attachment that can be called later. Which he does later with his attachment code.



                                        <?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.">rn";
                                        $header .= "Reply-To: ".$replyto."rn";
                                        $header .= "MIME-Version: 1.0rn";
                                        $header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";
                                        $header .= "This is a multi-part message in MIME format.rn";
                                        $header .= "--".$uid."rn";
                                        $header .= "Content-type:text/plain; charset=iso-8859-1rn";
                                        $header .= "Content-Transfer-Encoding: 7bitrnrn";
                                        $header .= $message."rnrn";
                                        $header .= "--".$uid."rn";
                                        $header .= "Content-Type: application/octet-stream; name="".$filename.""rn"; // use different content types here
                                        $header .= "Content-Transfer-Encoding: base64rn";
                                        $header .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
                                        $header .= $content."rnrn";
                                        $header .= "--".$uid."--";
                                        if (mail($mailto, $subject, "", $header)) {
                                        echo "mail send ... OK"; // or use booleans here
                                        } else {
                                        echo "mail send ... ERROR!";
                                        }
                                        }

                                        //start editing and inputting attachment details here
                                        $my_file = "somefile.zip";
                                        $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,rndo you like this script? I hope it will help.rnrngr. Olaf";
                                        mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
                                        ?>


                                        He has more details on his page and answers some problems in the comments section.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Nov 4 '15 at 17:33









                                        Jon

                                        5,22343049




                                        5,22343049






















                                            up vote
                                            -1
                                            down vote













                                            100% working Concept to send email with attachment in php :



                                            if (isset($_POST['submit'])) {
                                            extract($_POST);
                                            require_once('mail/class.phpmailer.php');

                                            $subject = "$name Applied For - $position";
                                            $email_message = "<div>Thanks for Applying ....</div> ";

                                            $mail = new PHPMailer;
                                            $mail->IsSMTP(); // telling the class to use SMTP
                                            $mail->Host = "mail.companyname.com"; // SMTP server
                                            $mail->SMTPDebug = 0;
                                            $mail->SMTPAuth = true;
                                            $mail->SMTPSecure = "ssl";
                                            $mail->Host = "smtp.gmail.com";
                                            $mail->Port = 465;
                                            $mail->IsHTML(true);
                                            $mail->Username = "info@companyname.com"; // GMAIL username
                                            $mail->Password = "mailPassword"; // GMAIL password

                                            $mail->SetFrom('info@companyname.com', 'new application submitted');
                                            $mail->AddReplyTo("name@yourdomain.com","First Last");
                                            $mail->Subject = "your subject";

                                            $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

                                            $mail->MsgHTML($email_message);

                                            $address = 'info@companyname.com';
                                            $mail->AddAddress($address, "companyname");

                                            $mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']); // attachment

                                            if (!$mail->Send()) {
                                            /* Error */
                                            echo 'Message not Sent! Email at info@companyname.com';
                                            } else {
                                            /* Success */
                                            echo 'Sent Successfully! <b> Check your Mail</b>';
                                            }
                                            }


                                            I used this code for google smtp mail sending with Attachment....



                                            Note: Download PHPMailer Library from here -> https://github.com/PHPMailer/PHPMailer






                                            share|improve this answer

























                                              up vote
                                              -1
                                              down vote













                                              100% working Concept to send email with attachment in php :



                                              if (isset($_POST['submit'])) {
                                              extract($_POST);
                                              require_once('mail/class.phpmailer.php');

                                              $subject = "$name Applied For - $position";
                                              $email_message = "<div>Thanks for Applying ....</div> ";

                                              $mail = new PHPMailer;
                                              $mail->IsSMTP(); // telling the class to use SMTP
                                              $mail->Host = "mail.companyname.com"; // SMTP server
                                              $mail->SMTPDebug = 0;
                                              $mail->SMTPAuth = true;
                                              $mail->SMTPSecure = "ssl";
                                              $mail->Host = "smtp.gmail.com";
                                              $mail->Port = 465;
                                              $mail->IsHTML(true);
                                              $mail->Username = "info@companyname.com"; // GMAIL username
                                              $mail->Password = "mailPassword"; // GMAIL password

                                              $mail->SetFrom('info@companyname.com', 'new application submitted');
                                              $mail->AddReplyTo("name@yourdomain.com","First Last");
                                              $mail->Subject = "your subject";

                                              $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

                                              $mail->MsgHTML($email_message);

                                              $address = 'info@companyname.com';
                                              $mail->AddAddress($address, "companyname");

                                              $mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']); // attachment

                                              if (!$mail->Send()) {
                                              /* Error */
                                              echo 'Message not Sent! Email at info@companyname.com';
                                              } else {
                                              /* Success */
                                              echo 'Sent Successfully! <b> Check your Mail</b>';
                                              }
                                              }


                                              I used this code for google smtp mail sending with Attachment....



                                              Note: Download PHPMailer Library from here -> https://github.com/PHPMailer/PHPMailer






                                              share|improve this answer























                                                up vote
                                                -1
                                                down vote










                                                up vote
                                                -1
                                                down vote









                                                100% working Concept to send email with attachment in php :



                                                if (isset($_POST['submit'])) {
                                                extract($_POST);
                                                require_once('mail/class.phpmailer.php');

                                                $subject = "$name Applied For - $position";
                                                $email_message = "<div>Thanks for Applying ....</div> ";

                                                $mail = new PHPMailer;
                                                $mail->IsSMTP(); // telling the class to use SMTP
                                                $mail->Host = "mail.companyname.com"; // SMTP server
                                                $mail->SMTPDebug = 0;
                                                $mail->SMTPAuth = true;
                                                $mail->SMTPSecure = "ssl";
                                                $mail->Host = "smtp.gmail.com";
                                                $mail->Port = 465;
                                                $mail->IsHTML(true);
                                                $mail->Username = "info@companyname.com"; // GMAIL username
                                                $mail->Password = "mailPassword"; // GMAIL password

                                                $mail->SetFrom('info@companyname.com', 'new application submitted');
                                                $mail->AddReplyTo("name@yourdomain.com","First Last");
                                                $mail->Subject = "your subject";

                                                $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

                                                $mail->MsgHTML($email_message);

                                                $address = 'info@companyname.com';
                                                $mail->AddAddress($address, "companyname");

                                                $mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']); // attachment

                                                if (!$mail->Send()) {
                                                /* Error */
                                                echo 'Message not Sent! Email at info@companyname.com';
                                                } else {
                                                /* Success */
                                                echo 'Sent Successfully! <b> Check your Mail</b>';
                                                }
                                                }


                                                I used this code for google smtp mail sending with Attachment....



                                                Note: Download PHPMailer Library from here -> https://github.com/PHPMailer/PHPMailer






                                                share|improve this answer












                                                100% working Concept to send email with attachment in php :



                                                if (isset($_POST['submit'])) {
                                                extract($_POST);
                                                require_once('mail/class.phpmailer.php');

                                                $subject = "$name Applied For - $position";
                                                $email_message = "<div>Thanks for Applying ....</div> ";

                                                $mail = new PHPMailer;
                                                $mail->IsSMTP(); // telling the class to use SMTP
                                                $mail->Host = "mail.companyname.com"; // SMTP server
                                                $mail->SMTPDebug = 0;
                                                $mail->SMTPAuth = true;
                                                $mail->SMTPSecure = "ssl";
                                                $mail->Host = "smtp.gmail.com";
                                                $mail->Port = 465;
                                                $mail->IsHTML(true);
                                                $mail->Username = "info@companyname.com"; // GMAIL username
                                                $mail->Password = "mailPassword"; // GMAIL password

                                                $mail->SetFrom('info@companyname.com', 'new application submitted');
                                                $mail->AddReplyTo("name@yourdomain.com","First Last");
                                                $mail->Subject = "your subject";

                                                $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

                                                $mail->MsgHTML($email_message);

                                                $address = 'info@companyname.com';
                                                $mail->AddAddress($address, "companyname");

                                                $mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']); // attachment

                                                if (!$mail->Send()) {
                                                /* Error */
                                                echo 'Message not Sent! Email at info@companyname.com';
                                                } else {
                                                /* Success */
                                                echo 'Sent Successfully! <b> Check your Mail</b>';
                                                }
                                                }


                                                I used this code for google smtp mail sending with Attachment....



                                                Note: Download PHPMailer Library from here -> https://github.com/PHPMailer/PHPMailer







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Jun 2 '16 at 10:59









                                                Irshad Khan

                                                2,3221915




                                                2,3221915

















                                                    protected by Community Jan 20 '15 at 6:26



                                                    Thank you for your interest in this question.
                                                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                    Would you like to answer one of these unanswered questions instead?



                                                    Popular posts from this blog

                                                    鏡平學校

                                                    ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

                                                    Why https connections are so slow when debugging (stepping over) in Java?