PHP Email with attachement - php

Am facing a problem to sent a PHP email with an excel attachment. I can see the mail sent message, Mail is coming, but there is no attachment. I dint know the real problem. this is my code. I have put the User.xlsx file in my root directory. Please help me to solve this issue. Thanks
$to = "dibeesh#amt.in";
$subject="attachement";
$mail_msg="message with attach";
$filename="User.xlsx"; // Attachement file in root directory
$contentType="application/zip"; // Not sure about what to put here
$pathToFilename="./";
$random_hash = md5(date('r', time()));
$headers = "From: webmaster#mysite.com\r\nReply-To: ".$to;
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents($pathToFilename)));
ob_start();
echo "
--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary=\"PHP-alt-$random_hash\"
--PHP-alt-$random_hash
Content-Type: text/plain; charset=\"utf-8\"
Content-Transfer-Encoding: 7bit
$mail_msg
--PHP-alt-$random_hash--
--PHP-mixed-$random_hash
Content-Type: $contentType; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--
";
$message = ob_get_clean();
// $fh=fopen('log.txt','w');
// fwrite($fh,$message);
$mail_sent = #mail( $to, $subject, $message, $headers );
echo $mail_sent ? "Mail sent" : "Mail failed";

I have managed to debug my code, sorry for duplicate posting. It may help someone thanks
// Email to Client with attachement
//define the receiver of the email
$to = 'dibeesh#amt.in';
//define the subject of the email
$subject = 'Bayern3 Notification';
$filename = "User.xlsx";
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: lal#amt.in\r\nReply-To: dibeesh#amt.in";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents($filename)));
//define the body of the message.
ob_start(); //Turn on output buffering
echo "--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary=\"PHP-alt-$random_hash\"
--PHP-alt-$random_hash
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
--PHP-alt-$random_hash
Content-Type: text/html; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
<h4>Hi,</h4>
<p><b>$userfullname</b> and his 10 friends qualified for <b>$venuename</b>. Please find the Excel sheet attached. You can download the detailed report form Bayern3 Admin Panel</p>
<h4>Regards,</h4>
<h4>Bayern3 Team</h4>
--PHP-alt-$random_hash--
--PHP-mixed-$random_hash
Content-Type: application/zip; name=$filename
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--";
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
//echo $mail_sent ? "Mail sent" : "Mail failed";
if($mail_sent === True)
{
//echo "Mail Sent";
}
else{
//echo "Mail Failed";
}

Related

PHP file attachment in form file input [duplicate]

This question already has answers here:
Send attachments with PHP Mail()?
(16 answers)
Closed 4 years ago.
My form did send all info except of file/ How it is possible to fix it?
This is input file:
<input type="file" name="file" placeholder="ЗАГРУЗИТЬ ЧЕК" id="file_kd" required>
<br></p>
This is code php mail:
<?php
header('Refresh: 0; URL=http://yougotit.agency/kodabra/thank-you.php'); //
переадресация на страницу спасибо
$to = "stanislav.mandrik#gmail.com"; // емайл получателя данных из формы
$tema = "Kodabra - заявка успешно отправлена!"; // тема полученного емайла
$from = "Kodabra <no-reply#kodabra.com>";
$photo = $_FILES['file']['name'];
$message = "Ваше имя: ".$_POST['kdname']."<br>";
$message .= "E-mail: ".$_POST['kdemail']."<br>";
$message .= "Номер телефона: ".$_POST['kdphone']."<br>";
$message .= "Артикул модели (указан на упаковке): ".$_POST['kdartic']."<br>";
$message .= "Номер чека: ".$_POST['kdbill']."<br>";
$message .= "Комментарий: ".$_POST['kdcomment']."<br>";
$message .= "Согласился на обработку персональных данных. ".$_POST['kdagree']."<br>";
$message .= "Фото чека: ".($photo)."\n";
$headers = "MIME-Version: 1.0"."\r\n".
"Content-type: text/html; charset=\"utf-8\""."\r\n".
"From: $from"."\r\n";
mail($to, $tema, $message, $headers);
?>
from the answer that i marked duplicate please don't upvote this
To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email.Have a look at the example:
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64, split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.
Taken from here.
In order to send email with file attachments you have to split the message into multiple parts with different encoding - here's how I do it. Note that there is a section for plain text information, and then it changes content encoding and adds any attachments by reading in the byte stream and re-encoding to base64 format and adding that to the message body, specifing content type, its file name, etc.
Of course, this all assumes that you have a working mail set up and a mail() of a plain text message works fine...
<?php
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: $from_name <$from_address>\r\n";
$headers .= "Date: " . date("Ymd H:i:s") . "\r\n";
$headers .= "Reply-To: $from_name <$from_address>\r\n";
$headers .= "X-Priority: 1\r\n";
$headers .= "X-MSMail-Priority: High\r\n";
$headers .= "X-Mailer: ".$_SERVER['PHP_SELF']. "?id=". $_SERVER['UNIQUE_ID']. "\r\n";
$separator=md5(time());
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n";
$headers .= "This is a MIME encoded message.\r\n";
// text message as normal for f2m
$messageBody="--".$separator."\r\n";
$messageBody.="Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$messageBody.="Content-Transfer-Encoding: 8bit\r\n";
$messageBody.="\r\n".$message_body."\r\n\r\n";
// add attachments
// $attachments is basically the $_FILES array
for($i=0;$i<count($attachments);$i++){
$attachcontent=chunk_split(base64_encode(file_get_contents($attachments[$i]['tmp_name'])));
$messageBody.="--".$separator."\r\n";
$messageBody.="Content-Type: application/octet-stream; name=\"".$attachments[$i]['name']."\"\r\n";
$messageBody.="Content-Transfer-Encoding: base64\r\n";
$messageBody.="Content-Disposition: attachment; filename=\"".$attachments[$i]['name']."\"\r\n";
$messageBody.="\r\n".$attachcontent."\r\n";
}
$messageBody.="--" . $separator . "--";
mail($to_address, $subject, $messageBody, $headers);
?>

PHP mail with attachment of unknown file type

I want to add send mail in my website. user can attach some files with multiple types in email. So i wrote this code to send mail. the problem is file type is not correct. for example i attached a jpg file to send to email. but the attachment received in mail box is empty or is wrong type.
this is my php mail file:
<?php
//Deal with the email
$sender = $_POST['email'];
$to = 'info#matinjewellery.com';
$subject = $_POST['name'];
$message = strip_tags($_POST['message']);
$attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
$filename = $_FILES['file']['name'];
$boundary =md5(date('r', time()));
$headers = "From: ".$sender."\r\nReply-To: ".$to;
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
$message="This is a multi-part message in MIME format.
--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
--_2_$boundary
Content-Type: text/plain; charset=\"utf-8\"
Content-Transfer-Encoding: 7bit
$message
--_2_$boundary--
--_1_$boundary
Content-Type: application/zip; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--_1_$boundary--";
mail($to, $subject, $message, $headers);
?>

How to send HTML email with attachment?

I am using mail() function of PHP,
following is my code;
$to = "info#abc.com";
$subject = "Application for Job";
$attachment =chunk_split(base64_encode(file_get_contents($_FILES['attachresume']['tmp_name'])));
$filename = $_FILES['attachresume']['name'];
$boundary = md5(date('r', time()));
$headers = "From: info#xyz.com\r\nReply-To: info#xyz.com";
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
$message = "Content-Type: text/html; charset='iso-8859-1'
Content-Transfer-Encoding: 7bit
<strong>Candidate Name :</strong> ".$candidatename."<br>
$message .="--_1_$boundary
Content-Type: application/octet-stream; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment $attachment --_2_$boundary--";
mail($to,$subject,$message,$headers);
But I dont know why, in email I am only getting attachment, I am not getting candidate name. I mean html contents.
I am moving to PHPMailer
and I am using this code,
if (isset($_FILES['uploaded_file']) &&
$_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
$_FILES['uploaded_file']['name']);
}
for attachment.

Sending mail with attachments

How do i send a mail in PHP with attachments?
I want to use pure php and not any libraries...
Here's what I already have tried:
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email';
//define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail.";
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Try this:
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Reference: http://webcheatsheet.com/PHP/send_email_text_html_attachment.php
You can try the following, but first you will need to make changes to these:
$name = 'image.jpg';
// The path to the image with the file name:
$fileatt = "images/".$name;
Which is within the code below: (pre-tested)
<?php
// Set who this goes to:
$to = array('Your Name','email#example.com');
// Give the message a subject:
$subject = 'Some subject';
// Set who this message is from:
$from = array("My Company", "email#example.com");
// Create the header information:
$random_hash = md5(date('r', time()));
$mime_boundary = "==Multipart_Boundary_x{$random_hash}x";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-Type: multipart/mixed; boundary="'.$mime_boundary.'"' . "\r\n";
$headers .= 'To: '.$to[0].' <'.$to[1].'>' . "\r\n";
$headers .= 'From: '.$from[0].' <'.$from[1].'>' . "\r\n";
// Build the message (can have HTML in it) message:
$message = 'This is an <b>HTML message</b> it comes with an attachment!'."\n\n".
// Do not edit this part of the message:
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// The image that you would like to send (filename only):
$name = 'image.jpg';
// The path to the image with the file name:
$fileatt = "images/".$name;
$fileatt_type = "application/octet-stream"; // File Type
// Filename that will be used for the file as the attachment
$fileatt_name = $name;
// Read the file attachment:
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
// Create sendable information
$data = chunk_split(base64_encode($data));
// Finalize the message with attachment
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}\n";
unset($data);
unset($file);
unset($fileatt);
unset($fileatt_type);
unset($fileatt_name);
// Send the message:
mail($to[1], $subject, $message, $headers);
echo "Email sent";
?>
You need to make use of base64 encoding inorder to attach a file. So here goes a simpler code.
<?php
$to = "someone#somewhere.com";
$subject = "Email with an Attachment with no Special libraries";
$random_hash = md5(date('r', time()));
$headers = "From: someid#yoursite.com\r\nReply-To: noreply#so.com";
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents("pics.zip")));
$output = "somecontent";
echo mail($to, $subject, $output, $headers);
?>

php send e-mail with attachment

I can't seem to find the problem with this php function i wrote that should send an e-mail with attachment. I've been struggling with it for quite a while.
function myMail($to, $subject, $mail_msg, $filename, $contentType){
$random_hash = md5(date('r', time()));
$headers = "From: webmaster#example.com\r\nReply-To: ".$to;
$headers .= "\r\nContent-Type: ".$contentType.
"; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents($filename)));
ob_start();
echo "
--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary=\"PHP-alt-$random_hash\"
--PHP-alt-$random_hash
Content-Type: text/plain; charset=\"utf-8\"
Content-Transfer-Encoding: 7bit
$mail_msg
--PHP-alt-$random_hash
--PHP-mixed-$random_hash--
Content-Type: text/plain; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--
";
$message = ob_get_clean();
$mail_sent = #mail( $to, $subject, $message, $headers );
return $mail_sent ? "Mail sent" : "Mail failed";
}
Edit The problem is that the message of the mail is mixed with the file and send as an attachment.
I've just looked at a couple of my emails, and I notice the the final attachment boundary ends with '--', while the opening boundary marker does not. In your code, you have:
--PHP-mixed-$random_hash--
Content-Type: text/plain; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--
Perhaps it should be:
--PHP-mixed-$random_hash
Content-Type: text/plain; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--
Have a look at the example here:
http://en.wikipedia.org/wiki/MIME#Multipart_messages
Artefacto made me look at the output with more attention and i've found the fix:
function myMail($to, $subject, $mail_msg, $filename, $contentType, $pathToFilename){
$random_hash = md5(date('r', time()));
$headers = "From: webmaster#mysite.com\r\nReply-To: ".$to;
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents($pathToFilename)));
ob_start();
echo "
--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary=\"PHP-alt-$random_hash\"
--PHP-alt-$random_hash
Content-Type: text/plain; charset=\"utf-8\"
Content-Transfer-Encoding: 7bit
$mail_msg
--PHP-alt-$random_hash--
--PHP-mixed-$random_hash
Content-Type: $contentType; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--
";
$message = ob_get_clean();
$fh=fopen('log.txt','w');
fwrite($fh,$message);
$mail_sent = #mail( $to, $subject, $message, $headers );
return $mail_sent ? "Mail sent" : "Mail failed";
}
Unless you are doing this to learn about the internal workings of MIME mails, the standard answer is to use a mailer library like PHPMailer or Swiftmailer that can deal with attachments out of the box.
SwiftMailer Examples on how to attach files are here.
These are the headers I use and they have always worked like a charm.
$base = basename($_FILES['upload']['name']);
$file = fopen($randname_path,'rb');
$size = filesize($randname_path);
$data = fread($file,$size);
fclose($file);
$data = chunk_split(base64_encode($data));
//boundary
$div = "==Multipart_Boundary_x".md5(time())."x";
//headers
$head = "From: $from\n".
"MIME-Version: 1.0\n".
"Content-Type: multipart/mixed;\n".
" boundary=\"$div\"";
//message
$mess = "--$div\n".
"Content-Type: text/plain; charset=\"iso-8859-1\"\n".
"Content-Transfer-Encoding: 7bit\n\n".
"$message\n\n".
"--$div\n".
"Content-Type: application/octet-stream; name=\"$base\"\n".
"Content-Description: $base\n".
"Content-Disposition: attachment;\n".
" filename=\"$base\"; size=$size;\n".
"Content-Transfer-Encoding: base64\n\n".
"$data\n\n".
"--$div\n";
$return = "-f$from";
http://asdlog.com/Create_form_to_send_email_with_attachment

Categories