Skip to content

Instantly share code, notes, and snippets.

@jamalnasir
Last active April 29, 2018 07:18
Show Gist options
  • Save jamalnasir/1757dc73df91d80ec3e336f437240310 to your computer and use it in GitHub Desktop.
Save jamalnasir/1757dc73df91d80ec3e336f437240310 to your computer and use it in GitHub Desktop.
Sending email with attachment in core PHP
<?php
try {
$fileatt = "";
$fileatt_name = $fileatt. "file.pdf";
$email_from = "support@mathkings.com";
$email_subject = "attachment test-subject";
$email_txt = "attachment test-body";
$email_to = "janasir35@gmail.com";
$headers = "From: ".$email_from;
$file = fopen($fileatt_name,'rb');
$data = fread($file,filesize($fileatt_name));
fclose($file);
$data = chunk_split(base64_encode($data));
$fileatt_name = substr($fileatt_name, strlen($fileatt));
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n". $email_txt . "\n\n";
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: application/pdf;\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" .
"--{$mime_boundary}--\n";
$ok = mail($email_to, $email_subject, $email_message, $headers);
if ($ok) {
echo "<p>mail sent!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
} catch (\Exception $e) {
echo $e->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment