Send Email with Attachment in PHP

In this post i am showing you how you can send email with attachment in php. For time being we are using a pdf file as attachment that created using FPDF.
so first we need to create and sample pdf using the fpdf library which can be downloadedby clicking here

See code below to see how we can send email with attachment in PHP

//creating a sample pdf file
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');

$to = 'hello@navaneeth.me';
$from = "no-reply@hello.navaneeth.me";
$message="Test email with attachment";
// a random hash will be necessary to send mixed content
$separator = md5(time());

// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;

// attachment name
$filename = 'sample_data.pdf';

// encode data (puts attachment in proper format)
$pdfdoc = $pdf->Output("", "S");
$attachment = chunk_split(base64_encode($pdfdoc));

// main header
$headers= "From: Navaneeth.me <".$from . ">".$eol;

$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";

// no more headers after this, we start the body! //

$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "".$eol;

// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;

// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";

// send message
mail($to, $subject, $body, $headers);

If the code doesnt works for you have an issue regarding the emails,For some servers the inboud or outbound email address must be an email within server address
Hope it helps you to send email with attachment in php

Leave a Reply

Your email address will not be published. Required fields are marked *