Send PHP HTML Mail with Attachments

Send attachments with PHP Mail()?

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 PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$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.

Send PHP HTML mail with attachments

To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email.Have a look at the example:

<?php 
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64, split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.

Send HTML Email With Attachments PHP

Actually I wanted to share this code snippet with community, I thought if I click on Answer your question, this question will get posted just as a topic. But let it be,

I hope other users might find it useful.

How to combine HTML and an attachment using PHP mail?

There is a missing "\r\n" at the tail end of the line reading:

. "Contact " . $from . " for tech support."

Below is the ammended function:

function GetHTML()
{
return <<<HTML

<html>
<body>
<p>Testing <i><b>HTML</b></i> right now.</p>
</body>
</html>

HTML;
}

function mailAttachment($to, $subject, $body, $from, $photoPath, $photoName, $filetype)
{
$bound_text = md5(uniqid(rand(), true));;
$bound = "--" . $bound_text . "\r\n";
$bound_last = "--" . $bound_text . "--\r\n";

$headers = "From: " . $from . "\r\n"
. "Reply-To: " . $from . "\r\n"
. "Return-Path: " . $from . "\r\n"
. "MIME-Version: 1.0\r\n"
. "Content-Type: multipart/mixed; boundary=\"$bound_text\"";

$message = "Sorry, your client doesn't support MIME types.\r\n"
. "Contact " . $from . " for tech support.\r\n"
. $bound;

$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
. "Content-Transfer-Encoding: 7bit\r\n\r\n"
. $body . "\r\n"
. $bound;

$file = file_get_contents($photoPath);

$message .= "Content-Type: $filetype; name=\"$photoName\"\r\n"
. "Content-Transfer-Encoding: base64\r\n"
. "Content-disposition: attachment; file=\"$photoName\"\r\n"
. "\r\n"
. chunk_split(base64_encode($file))
. $bound_last;

if(mail($to, $subject, $message, $headers))
{
echo 'MAIL SENT!' . '<br>';
echo 'to: ' . $to . '<br>';
echo 'from: ' . $from . '<br>';
echo 'bodyText: ' . $body . '<br>';
echo 'photoPath: ' . $photoPath . '<br>';
echo 'photoName: ' . $photoName . '<br>';
echo 'filetype: ' . $filetype . '<br>';
}
else
{
echo 'MAIL FAILED';
}
}

mailAttachment('admin@sideapps.com', 'attachmentTest', GetHTML(),
'noreply@sideapps.com', 'testImage.png', 'uploaded.png', 'image/png');


Related Topics



Leave a reply



Submit