I need to send a pdf with mail, is it possible?
$to = \"xxx\";
$subject = \"Subject\" ;
$message = \'Example message with html\';
$header
This works for me. It also attaches multiple attachments too. easily
<?php
if ($_POST && isset($_FILES['file'])) {
$recipient_email = "recipient@yourmail.com"; //recepient
$from_email = "info@your_domain.com"; //from email using site domain.
$subject = "Attachment email from your website!"; //email subject line
$sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
$sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
$sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
$attachments = $_FILES['file'];
//php validation
if (strlen($sender_name) < 4) {
die('Name is too short or empty');
}
if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
die('Invalid email');
}
if (strlen($sender_message) < 4) {
die('Too short message! Please enter something');
}
$file_count = count($attachments['name']); //count total files attached
$boundary = md5("specialToken$4332"); // boundary token to be used
if ($file_count > 0) { //if attachment exists
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:" . $from_email . "\r\n";
$headers .= "Reply-To: " . $sender_email . "" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//message text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($sender_message));
//attachments
for ($x = 0; $x < $file_count; $x++) {
if (!empty($attachments['name'][$x])) {
if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
$mymsg = array(
1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3 => "The uploaded file was only partially uploaded",
4 => "No file was uploaded",
6 => "Missing a temporary folder");
die($mymsg[$attachments['error'][$x]]);
}
//get file info
$file_name = $attachments['name'][$x];
$file_size = $attachments['size'][$x];
$file_type = $attachments['type'][$x];
//read file
$handle = fopen($attachments['tmp_name'][$x], "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
$body .= "--$boundary\r\n";
$body .= "Content-Type: $file_type; name=" . $file_name . "\r\n";
$body .= "Content-Disposition: attachment; filename=" . $file_name . "\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
$body .= $encoded_content;
}
}
} else { //send plain email otherwise
$headers = "From:" . $from_email . "\r\n" .
"Reply-To: " . $sender_email . "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $sender_message;
}
$sentMail = @mail($recipient_email, $subject, $body, $headers);
if ($sentMail) { //output success or failure messages
die('Thank you for your email');
} else {
die('Could not send mail! Please check your PHP mail configuration.');
}
}
?>
Copying the code from this page - works in mail()
He starts off my making a function mail_attachment that can be called later. Which he does later with his attachment code.
<?php
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$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";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
echo "mail send ... OK"; // or use booleans here
} else {
echo "mail send ... ERROR!";
}
}
//start editing and inputting attachment details here
$my_file = "somefile.zip";
$my_path = "/your_path/to_the_attachment/";
$my_name = "Olaf Lederer";
$my_mail = "my@mail.com";
$my_replyto = "my_reply_to@mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo you like this script? I hope it will help.\r\n\r\ngr. Olaf";
mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
?>
He has more details on his page and answers some problems in the comments section.
Working Concept :
if (isset($_POST['submit'])) {
$mailto = $_POST["mailTo"];
$from_mail = $_POST["fromEmail"];
$replyto = $_POST["fromEmail"];
$from_name = $_POST["fromName"];
$message = $_POST["message"];
$subject = $_POST["subject"];
$filename = $_FILES["fileAttach"]["name"];
$content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$uid = md5(uniqid(time()));
$name = basename($file);
$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";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--" . $uid . "\r\n";
// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
$header .= "Content-type:text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
// User Message you can add HTML if You Selected HTML content
$header .= "<div style='color: red'>" . $message . "</div>\r\n\r\n";
$header .= "--" . $uid . "\r\n";
$header .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n"; // For Attachment
$header .= $content . "\r\n\r\n";
$header .= "--" . $uid . "--";
if (mail($mailto, $subject, "", $header)) {
echo "<script>alert('Success');</script>"; // or use booleans here
} else {
echo "<script>alert('Failed');</script>";
}
}
100% working Concept to send email with attachment in php :
if (isset($_POST['submit'])) {
extract($_POST);
require_once('mail/class.phpmailer.php');
$subject = "$name Applied For - $position";
$email_message = "<div>Thanks for Applying ....</div> ";
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.companyname.com"; // SMTP server
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = "info@companyname.com"; // GMAIL username
$mail->Password = "mailPassword"; // GMAIL password
$mail->SetFrom('info@companyname.com', 'new application submitted');
$mail->AddReplyTo("name@yourdomain.com","First Last");
$mail->Subject = "your subject";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($email_message);
$address = 'info@companyname.com';
$mail->AddAddress($address, "companyname");
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']); // attachment
if (!$mail->Send()) {
/* Error */
echo 'Message not Sent! Email at info@companyname.com';
} else {
/* Success */
echo 'Sent Successfully! <b> Check your Mail</b>';
}
}
I used this code for google smtp mail sending with Attachment....
Note: Download PHPMailer Library from here -> https://github.com/PHPMailer/PHPMailer
You can try using the following code:
$filename = 'myfile';
$path = 'your path goes here';
$file = $path . "/" . $filename;
$mailto = 'mail@mail.com';
$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 <test@test.com>" . $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;
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:
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.