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('[email protected]', 'Your Name'); //Name is optional
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->AddAddress( '[email protected]' );
$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.
You can try using the following code:
$filename = 'myfile';
$path = 'your path goes here';
$file = $path . "/" . $filename;
$mailto = '[email protected]';
$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 = "\r\n";
// main header (multipart mandatory)
$headers = "From: name <[email protected]>" . $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;
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()));
$file_name = basename($file);
// header
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
// message & attachment
$nmessage = "--".$uid."\r\n";
$nmessage .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$nmessage .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$nmessage .= $message."\r\n\r\n";
$nmessage .= "--".$uid."\r\n";
$nmessage .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
$nmessage .= $content."\r\n\r\n";
$nmessage .= "--".$uid."--";
if (mail($mailto, $subject, $nmessage, $header)) {
return true; // Or do something here
} else {
return false;
}
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('[email protected]' => 'Web Master'))
->setTo(array('[email protected]'))
->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.