PHP Send E-Mail with Attachment

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 email with attachment php not working

Are you looking for something like this:

This should work for you for this scenario:

<?php 
function mail_attachment($filename, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$body = '';
$headers = '';

$file = $filename;
$separator = md5(time());
$attachment = chunk_split(base64_encode(file_get_contents($file)));
$headers = "From: ".$from_name."<".$from_mail.">" . PHP_EOL;
$headers .= "Reply-To: ".$replyto . PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . PHP_EOL . PHP_EOL;
$body .= "Content-Transfer-Encoding: 7bit" . PHP_EOL;
$body .= "This is a MIME encoded message." . PHP_EOL;
$body .= "--" . $separator . PHP_EOL;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"" . PHP_EOL;
$body .= "Content-Transfer-Encoding: 8bit" . PHP_EOL . PHP_EOL;
$body .= $message . PHP_EOL;
$body .= "--" . $separator . PHP_EOL;
$body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . PHP_EOL;
$body .= "Content-Transfer-Encoding: base64" . PHP_EOL;
$body .= "Content-Disposition: attachment" . PHP_EOL . PHP_EOL;
$body .= $attachment . PHP_EOL;
$body .= "--" . $separator . "--";
if (mail($mailto, $subject, $body, $headers)) {
echo "Message sent!";
} else {
echo "ERROR sending message.";
}
}

$my_file = "2.doc";
$my_name = "Your Name (or) Your Business";
$my_mail = "myemail@yahoo.com";
$my_replyto = "replyemail@gmail.com";
$to_email = "replyemail@gmail.com";
$my_subject = "Your file has arrived!";
$requester = $_POST['Field101'];
$message = "Hey $requester, Your custom email message goes here";
mail_attachment($my_file, $to_email, $my_mail, $my_name, $my_replyto, $my_subject, $message);
?>

php send email with attachment

 function mail_attachment($to, $subject, $message, $from, $file) {
// $file should include path and filename
$filename = basename($file);
$file_size = filesize($file);
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
$from = str_replace(array("\r", "\n"), '', $from); // to prevent email injection
$header = "From: ".$from."\r\n"
."MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"
."This is a multi-part message in MIME format.\r\n"
."--".$uid."\r\n"
."Content-type:text/plain; charset=iso-8859-1\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n"
.$message."\r\n\r\n"
."--".$uid."\r\n"
."Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n"
.$content."\r\n\r\n"
."--".$uid."--";
return mail($to, $subject, "", $header);
}

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.



Related Topics



Leave a reply



Submit