PHP mail attachment is not working - php

i am using php mail function to sent attachment, but its not working. Here is my code:
$headers = array(
"Mime-Version: 1.0",
"Content-Type: text/html; charset=charset=UTF-8",
"From: Test <myemail>",
"Content-Disposition: attachment; filename=\"" . $_SERVER['DOCUMENT_ROOT']."/project_name/test.txt" . "\"\r\n"; // For Attachment
);
$headers = join("\r\n", $headers);
mail($to, $subject, $body, $headers);
Email sent successfully and file is attached, but the content is hidden.

I recommend you to use PHPMailer.
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 use as :
$email = new PHPMailer();
$email->From = 'you#example.com';
$email->FromName = 'Your Name';
$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();

Your content type should be
"Content-Type: multipart/mixed; charset=charset=UTF-8",
see this answer, this can guide you solve your problem.
I also have a big doubt, if it is correct
"Content-Disposition: attachment; filename=\"" . $_SERVER['DOCUMENT_ROOT']."/project_name/test.txt" . "\"\r\n"; // For Attachment
combination of single and double quote does not seems to good. Can you please change it to
"Content-Disposition: attachment; filename=\" . $_SERVER['DOCUMENT_ROOT'] . "/project_name/test.txt" . "\"\r\n";
or try using single quote as you are not parsing any variable.

If you want to write your own code and don't want to implement the mail libraries. Please do it like this
$handle = fopen($file_name, "r");
$content = fread($handle, filesize($file_name));
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("foobar");
$message = "I have some message";
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//plain 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($message));
//attachment
$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;
mail($to, $subject, $body, $headers);

$to = "YOUR EMAIL ID";
$from = "Website <website#mydomain.com>";
$subject = "Test Attachment Email";
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
$filename = "document.pdf";
//$pdfdoc is PDF generated by FPDF
$attachment = chunk_split(base64_encode($pdfdoc));
// main header
$headers = "From: ".$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 .= "This is a MIME encoded message.".$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
if (mail($to, $subject, $body, $headers)) {
echo "mail send ... OK";
} else {
echo "mail send ... ERROR";
}

Related

how to attach mail in my output file using fpdf

$path=$_SERVER['DOCUMENT_ROOT']."/unwant/test3.pdf";
$filename="test3.pdf";
$pdf->Output($filename,'F');
i got my output file in this code $pdf->Output($filename,'F'); i want to attach my output file in mail.
require('lib/fpdf/fpdf.php');
$pdf = new FPDF('P', 'pt', array(500,233));
$pdf->AddFont('Georgiai','','georgiai.php');
$pdf->AddPage();
$pdf->Image('lib/fpdf/image.jpg',0,0,500);
$pdf->SetFont('georgiai','',16);
$pdf->Cell(40,10,'Hello World!');
// email stuff (change data below)
$to = "myemail#example.com";
$from = "me#example.com";
$subject = "send email with pdf attachment";
$message = "<p>Please see the attachment.</p>";
// 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 = "test.pdf";
// encode data (puts attachment in proper format)
$pdfdoc = $pdf->Output("", "S");
$attachment = chunk_split(base64_encode($pdfdoc));
// main header
$headers = "From: ".$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 .= "This is a MIME encoded message.".$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);
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:
$attachment= $pdf->Output('attachment.pdf', 'S');
$mailer->AddStringAttachment($attachment, 'attachment.pdf');

php mail function can not send attached pdf file and message body

I want to send mail through php mail function. For that I googled it and found the code which send mail attached with pdf file. Result is fine, mail send but mail only send attached pdf file it can not send message body.
Here is Code:
<?php
$name = "myname";
$to = "receive#gmail.com";
$email = "sender#gmail.com";
$from = "myname";
$subject = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$fileatt = $_SERVER['DOCUMENT_ROOT']."/xxx/ticket.pdf";
$fileatttype = "application/pdf";
$fileattname = "ticket.pdf";
$headers = "From: $from";
// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);
// This attaches the file
$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}\"";
$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" .
$mainMessage . "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"-{$mime_boundary}-\n";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
?>
I can not identify where i done mistake, please help me and give some suggestion.
Note: Don't Give suggestion to use PHPMailer.
Thanks
You can try this code:
$to = "youremail#gmail.com";
$from = "Myname <sender#gmail.com>";
$subject = "Test Attachment Email";
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
$filename = "document.pdf";
//$pdfdoc is PDF generated by FPDF
$pdfdoc = "/opt/transmail/2018-03-07_32_11564_invoice.pdf";
$attachment = chunk_split(base64_encode($pdfdoc));
// main header
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
// no more headers after this, we start the body! //
$message = "Thanks";
$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$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
if (mail($to, $subject, $body, $headers)) {
echo "mail send ... OK";
} else {
echo "mail send ... ERROR";
}
hope this will work for you.

php mail() : attachments sent but not body text

I have seen similar questions, but nothing directly on topic...
I have a multi part mail script with attachments. The attachments get sent fine, but the main body text, which is populated from a form, isn't sent. I tried sending with the attachment function commented out and the form elements went through. My code is:
if (empty($_POST['RadioGroup1'])){
echo "PLease select a version of message";
} else {$selected_msg = $_POST['RadioGroup1'];}
if (isset($_FILES) && (bool) $_FILES){
$files = array();
// Check for attachments
$questions = $_POST['questions'];
//loop through all the files
foreach($_FILES as $name=>$file){
// define the variables
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
//check if file type allowed
$path_parts = pathinfo($file_name);
//move this file to server
$server_file = "reports/$path_parts[basename]";
move_uploaded_file($temp_name, $server_file);
//add file to array of file
array_push($files,$server_file);
}
// define mail var
$to = $email;
$from = "[server]";
$subject = "Closed Case: $case_id $casename";
$headers = "From: $from";
//define boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Header know about boundary
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
// Define plain text mail
$message .= "--{$mime_boundary}\n";
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n" . $message . "\r\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
foreach($files as $file){
$aFile = fopen($file, "rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"}\n";
$message .= " name=\"$file\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$file\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
} // END foreach attachment
$message .= $questions;
$message .= $selected_msg;
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p class=\"success\">mail sent to $to!</p>";
The script runs without errors and does sent the file attachments OR the body text. Any insight would be appreciated.
Instead of calling the form variables from within --- $message .= $questions;. $message .= $selected_msg; Hard code the variables into the $message.=
Like-- $message .= "Content-Transfer-Encoding: 7bit\r\n" . $questions . "\r\n" . $selected_msg . "\r\n";
If you like add both text and attachment in email, then used bellow code
$bodyMeaasge = 'Your Body Meaasge';
$filename = yourfile.pdf;
$path = '../';
$mpdf->Output($path.$filename,'F');
$file = $path . "/" . $filename;
$to = "senderemail#gmail.com";
$subject = "My Subject";
$random_hash = md5(date('r', time()));
$headers = "From:your#domain.com\r\n" .
"X-Mailer: PHP" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $random_hash\r\n\r\n";
if(file_exists($file))
{
$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));
//plain text
$body = "--$random_hash\r\n";
$body .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($bodyMeaasge));
//attachment
$body .= "--$random_hash\r\n";
$body .="Content-Type: application/octet-stream; name=".$filename."\r\n";
$body .="Content-Disposition: attachment; filename=".$filename."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $content;
}else{
//plain text
$body = "--$random_hash\r\n";
$body .= "Content-Type: text/html; charset=utf-8\r\n"; // use different content types here
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($bodyMeaasge));
}
if (mail($to,$subject,$body,$headers)) {
header("Location:".$url.'&success=successfully mail send.');
} else {
header("Location:".$url.'&error=There was a problem sending the email.');
}

PHP mail with attachment

Hello i'm trying to send email from form^) Here is my code
<?php
$to = "some email";
$from = "site";
$subject = "Resume";
$boundary = "---";
if (isset($_POST['ok'])){
$filename = $_POST['fileField'];
$resumeLink = $_POST['linkField'];
$message = "Attachment: " .$resumeLink;
/* Headers*/
$headers = "From: $from\nReply-To: $from\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";
$body = "--$boundary\n";
/* Add message */
$body .= "Content-type: text/html; charset='utf-8'\n";
$body .= "Content-Transfer-Encoding: quoted-printablenn";
$body .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode($filename)."?=\n\n";
$body .= $message."\n";
$body .= "--$boundary\n";
$file = fopen($filename, "r"); //open file
$text = fread($file, filesize($filename)); //read file
fclose($file); //close file
/* Add message type */
$body .= "Content-Type: application/octet-stream; name==?utf-8?B?".base64_encode($filename)."?=\n";
$body .= "Content-Transfer-Encoding: base64\n";
$body .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode($filename)."?=\n\n";
$body .= chunk_split(base64_encode($text))."\n";
$body .= "--".$boundary ."--\n";
if(mail($to, $subject, $body, $headers)){header("Location: /");}
}
?>
Attachment will send, but it size will be 1 byte without any content inside. Whats wrong?
It's hard to tell exactly, but you've added header fields into mail body, you should add them in headers

PHP: Sending mail with attach

With this code:
$Message = 'TEXT';
$boundary = "---";
$headers = "From: $from\nX-Mailer: Carline Server www.carline.ru";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";
$body = "--$boundary\n";
$body .= "Content-type: text/html; charset='utf-8'\n";
$body .= "Content-Transfer-Encoding: quoted-printable\n\n";
$body .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode($_FILES['photo1']['name'])."?=\n\n";
$body .= $Message."\n";
$body .= "--$boundary\n";
$text = file_get_contents($_FILES['photo1']['tmp_name']);
$body .= "Content-Type: application/octet-stream; name==?utf-8?B?".base64_encode($_FILES['photo1']['name'])."?=\n";
$body .= "Content-Transfer-Encoding: base64\n";
$body .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode($_FILES['photo1']['name'])."?=\n\n";
$body .= chunk_split(base64_encode($text))."\n";
$body .= "--".$boundary ."--\n";
mail($AdminEmail, "RE:", $body, $headers);
It sends a file-content in the message body
Content-Type: application/octet-stream; name==?utf-8?B?MDAwMDU3ODcuanBn?=
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename==?utf-8?B?MDAwMDU3ODcuanBn?=
/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcG
BwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwM
DAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAGQAZADASIA
...
How to change this code for sending file as attachment?
From php.net # http://php.net/manual/en/function.mail.php
Send Multi attachment email
<?php
function multi_attach_mail($to, $files, $sendermail){
// email fields: to, from, subject, and so on
$from = "Files attach <".$sendermail.">";
$subject = date("d.M H:i")." F=".count($files);
$message = date("Y.m.d H:i:s")."\n".count($files)." attachments";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// preparing attachments
for($i=0;$i<count($files);$i++){
if(is_file($files[$i])){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($files[$i],"rb");
$data = #fread($fp,filesize($files[$i]));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
"Content-Description: ".basename($files[$i])."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $sendermail;
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){ return $i; } else { return 0; }
}
?>
An example of header construction
$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";
// content type: mixed or related ( better mixed for attachments
$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."--";
You should be using pre-written libraries (e.g. http://swiftmailer.org/) to send emails, esp. the ones with attachments, whether inline or not.
Constructing valid and cross-mail client supported message is considerably advance task, esp. if you have never done this before. So why spend time re-inventing a weel when someone did the job for you already?
Put this question from the other end and if you want to build your own library, analyze what's already been done in SwiftMailer and use those snippets where needed.

Categories