I have a problem sending php email using the code below. The MIME heades keep apearing in the message and the attachment appears as scribble text in the mesage body not as attachment. what could be the problem
<?php
session_start();
require_once("includes/functions.php");
require_once("includes/dbconnect.php");
require_once("Mail/mailfunctions.php");
//function_to_be_applied($finaldest_email, $message, $subject, $fromname, $fromemail, $replyto )
function function_to_be_applied($finaldest_email, $key){
//require_once "Mail.php" ;
global $fromemail;
global $message;
global $fromname;
global $subject;
global $replyto;
global $seconds;
global $reprt;
global $headers;
$to = $finaldest_email;
$from = "".$fromname." <$fromemail>";
$subject = $subject;
if(mail($to, $subject, $message, $headers)) {
sleep($seconds);
$reprt .= "Message successfully sent to: ". $to."<br />";
} else {
$reprt .= "Message not successfully sent to: ". $to."<br />";
}
}
if(isset($_POST['submit']))
{
$errors_val = array();
$required_fields = array("subject", "fromemail", "message", "dest_email");
foreach($required_fields as $fieldname)
{
if( !isset($_POST[$fieldname]) || ( empty($_POST[$fieldname]) &&(!is_int($_POST[$fieldname])) ))
{
if($fieldname == "subject")
{$errors_val[0] = "-Sending email without SUBJECT is not allowed";}
if($fieldname == "fromemail")
{$errors_val[1] = "-Sending email without a FROM EMAIL is not allowed";}
if($fieldname == "message")
{$errors_val[2] = "-Sending an empty message is not allow";}
if($fieldname == "dest_email")
{$errors_val[3] = "-There must be at least one email in the destination email address";}
}
}
if(empty($errors_val)){
$errors = array();
if(false == validate_email(trim($_POST['fromemail']))){
$errors[0] = "FROM EMAIL is invalid";
}
if(false == validate_email(trim($_POST['replyto']))){
$errors[1] = "REPLY TO EMAIL is invalid";}
if(!is_numeric(trim($_POST['seconds']))){
$errors[2] = "Seconds between messages must be a number";}
$allowtypes = array("doc", "pdf", "txt", "zip", "gif", "jpeg", "jpg"); //the type of file can be attached
$max_file_size="100"; //describes the size that cab be attached
// checks that we have a file
if((!empty($_FILES["attachment"])) && ($_FILES["attachment"]["error"] == 0)) {
//set a variable $attached = 1
$attached = 1;
// basename -- Returns filename component of path
$filename = basename($_FILES['attachment']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
$filesize=$_FILES['attachment']['size'];
$max_bytes=$max_file_size*1024;
//Check if the file type uploaded is a valid file type.
if (!in_array($ext, $allowtypes)) {
$errors[3]="Invalid extension for your file: <strong>".$filename."</strong>";
unset($attached);
// check the size of each file
} elseif($filesize > $max_bytes) {
$errors[4]= "Your file: <strong>".$filename."</strong> is to big. Max file size is ".$max_file_size."kb.";
unset($attached);
}
}
if(empty($errors)){
//generate a unique boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
if(isset($_POST['seconds']) && ($_POST['seconds'] != ""))
{$seconds = $_POST['seconds'];}else{$seconds = 0.5;}
$subject = trim($_POST['subject']);
$fromname = trim($_POST['fromname']);
$fromemail = trim($_POST['fromemail']);
$from = stripslashes($fromname)."<".stripslashes($fromemail).">";
$emailmessage = trim($_POST['message']);
$replyto = trim($_POST['replyto']);
$dest_email = trim($_POST['dest_email']);
$emailarray = explode("\r\n", $dest_email, 400);
$finaldest_email = array_unique($emailarray );
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To:" . $replyto . "\r\n";
$headers .= "Mime-Version: 1.0\r\n";
$headers .= " Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
//attachment
if(isset($attached)){
$fileatt = $_FILES["attachment"]["tmp_name"];
$fileatt_type = $_FILES["attachment"]["type"];
$fileatt_name = $_FILES["attachment"]["name"];
if (is_uploaded_file($fileatt)) {
// Read the file to be attached ('rb' = read binary)
$data = file_get_contents($fileatt);
//$file = fopen($fileatt,'rb');
//$data = fread($file,filesize($fileatt));
//fclose($file);
// Base64 encode the file data
$finaldata = chunk_split(base64_encode($data));
}
$message = "--{$mime_boundary}\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "{$emailmessage}\r\n";
$message .= "--{$mime_boundary}\r\n";
$message .= "Content-Type: {$fileatt_type}; name=\"{$fileatt_name}\"\n\n".
"Content-Transfer-Encoding: base64\n\n";
$message .= "Content-Disposition: attachment; filename=\"{$fileatt_name}\"\n\n";
$message .= "{$finaldata} \r\n--{$mime_boundary}--\r\n";
}elseif(!isset($attached)){
$message = "--{$mime_boundary}\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\" \r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "{$emailmessage}\r\n";
$message .= "--{$mime_boundary}--\r\n";
}
$reprt = "Preparing to send message..<br />";
if( true == array_walk($finaldest_email, 'function_to_be_applied' )){
$numberofemailsent = count($finaldest_email);
}else{echo "No email sent";}
}else{$string = implode("<br /> -" , $errors); $error_message = $string; }
}else{$string = implode("<br /> -" , $errors_val); $error_message = $string; }
}
?>
Don't generate your own mime emails. Use PHPMailer or Swiftmailer and reduce a huge chunk of that script down to maybe 10 lines of code.
As well, don't verify file types by looking at filenames. It's trivial to forge a filename AND the client-specified mime type. Always use server-side mime verification instead.
Related
I have a html form where i ask my users to fill in their personal and career details and attach their resume. I would like to get those details (form data and the attachment) sent to an email using php.... Any help will be much appreciated....
here is my code for sending mail... Using this i get the file attachment but not the other form data... Pls help where i am going wrong...
<?php
// Settings - working good
$name = "Name goes here";
$email = "test#gmail.com";
$to = "$name <$email>";
$from = "Vijay";
$subject = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$attachments = $_FILES['attachment'];
if(empty($_POST['title']) ||
empty($_POST['exp']) ||
empty($_POST['skill']) ||
empty($_POST['qual']) ||
empty($_POST['certf']) ||
empty($_POST['domain']) ||
empty($_POST['fname']) ||
empty($_POST['lname']) ||
empty($_POST['phone']) ||
empty($_POST['email']) ||
empty($_POST['csal']) ||
empty($_POST['job']) ||
// empty($_POST['file']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}$title = strip_tags(htmlspecialchars($_POST['title']));
$exp = strip_tags(htmlspecialchars($_POST['exp']));
$skill = strip_tags(htmlspecialchars($_POST['skill']));
$qual = strip_tags(htmlspecialchars($_POST['qual']));
$certf = strip_tags(htmlspecialchars($_POST['certf']));
$domain = strip_tags(htmlspecialchars($_POST['domain']));
$fname = strip_tags(htmlspecialchars($_POST['fname']));
$lname = strip_tags(htmlspecialchars($_POST['lname']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$csal = strip_tags(htmlspecialchars($_POST['csal']));
$job = strip_tags(htmlspecialchars($_POST['job']));
// File
//Get uploaded file data
$file_tmp_name = $_FILES['attachment']['tmp_name'];
$file_name = $_FILES['attachment']['name'];
$file_size = $_FILES['attachment']['size'];
$file_type = $_FILES['attachment']['type'];
$file_error = $_FILES['attachment']['error'];
if($file_error > 0)
{
die('Upload error or No files uploaded');
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("sanwebe");
//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;
$Message = "You have received a new resume from your website career application form.\n\n"."Here are the details:\n\n
Title: ".$title."\n
Experience: ".$exp."\n
Skill: ".$skill."\n
Qualification: ".$qual."\n
Domain: ".$domain."\n
First Name: ".$fname."\n
Last Name: ".$lname."\n
Phone: ".$phone."\n
Email: ".$email_address."\n\n
Current Salary: ".$csal."\n\n
Job: ".$job."\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.";
echo "$fileattname";
}
else {
echo "There was an error sending the mail.";
}
?>
You want to use proven, well tested libraries like Swiftmailer or Zend\Mail instead of writing the code like you do.
Following is the code I am using to send multiple files as attachment in a mail, tested it in local environment, the attachments were reaching the mail box but as empty files, and in live environment, result is mail could not be sent, though files get saved in the upload folder on the server...a newbie in php so please can anyone help what am I doing wrong..??
In local environment i was using this code $server_file = "/localhost:81/xyz/uploads/$path_parts[basename]"; in place what is mentioned down there under move this file to the server
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//did files get sent
if(isset($_FILES) && (bool) $_FILES) {
//define allowed extensions
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
$username=$_POST['username'];
$email=$_POST['email'];
//loop through all the files
foreach($_FILES as $name=>$file){
//define some variables
$file_name= $file['name'];
$temp_name= $file['tmp_name'];
//check if this file type is allowed
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("extension not allowed");
}
//move this file to the server
$server_file = "/home/public_html/xyz.com/uploads/$path_parts[basename]";
move_uploaded_file($temp_name,$server_file);
//add this file to array of files
array_push($files,$server_file);
}
//define some mail variables
$to = "info#xyz.com";
$from = "From: $username<$email>\r\nReturn-path: $email";
$subject = "Photo attachment of . $name .";
$msg = "Images of $username, $email";
$headers = "From: $from";
//define our boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//tell the header about the boundary
$headers .= "nMIME-Version:1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
//part1: define the plain text email
$message = "\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n". $msg ."\n\n";
$message .="--{$mime_boundary}\n";
//part2: loop and define mail 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=\"$files\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$files\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
//send the email
$ok = mail($to, $subject, $message, $headers, $from);
if($ok){
header("Location: thank-your.php");
}
else{
echo"<p>mail could not be sent!</p>";
}
die();
}
?>
This is just a sample of the code, essentially I have a form with 4 files to upload. The files are successfully saved on my server in a designated folder. However, I obviously am not attaching them properly since they are empty....can anyone help?
Also, the attachments disply the directory name instead of the file name...what am I missing?
Many thanks!!!
<?php
$username= protect($_POST['username']);
$firstName= protect($_POST['firstName']);
$lastName= protect($_POST['lastName']);
$email= protect($_POST['email']);
$program= protect($_POST['program']);
$dob= protect($_POST['dob']);
$transcript= $_FILES['transcript'];
$resume= $_FILES['resume'];
$letterIntent= protect($_POST['letterIntent']);
$reference1= $_FILES['reference1'];
$reference2= $_FILES['reference2'];
$relevantExperience= protect($_POST['relevantExperience']);
$volunteerExperience= protect($_POST['volunteerExperience']);
$reasonsAbroad= protect($_POST['reasonsAbroad']);
$definitionSuccess= protect($_POST['definitionSuccess']);
$futureGoals= protect($_POST['futureGoals']);
$challengeYourself= protect($_POST['challengeYourself']);
$challengeDevelopment= protect($_POST['challengeDevelopment']);
if (isset($_FILES) && (bool) $_FILES) {
$allowed_ext = array('doc', 'pdf', 'txt', '');
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$path_parts = pathinfo($file_name);
$file_ext = $path_parts['extension'];
if(!in_array($file_ext, $allowed_ext)) {
die ("extension for file $file_name not allowed");
}
if($file_size > 2097152) {
die ("File size must be under 2MB");
}
$server_file = "wp-content/uploads/application-documents";
move_uploaded_file($file_tmp, "$server_file/$file_name");
array_push($files, $server_file);
}
$to = ".....#gmail.com";
$from = "$email";
$subject ="Application from $firstName $lastName with attachments";
$msg = "hello";
$headers = "From: $from";
//define email boundaries
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
$message ="\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n" . $msg . "\n\n";
$message .= "--{$mime_boundary}\n";
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";
}
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
}
?>
I know it's not the answer to your post, but after struggling with this kind of problems in the past, I gave up and used PHPMailer. If you still want to roll your own, you should take a look at its source code.
I have an submit page where client scan submit a fillable PDF form along with a photo, using the attached mailer script. The form uploads to the server correctly, however when it is sent to the client, the PDF is blank.
<?php
// did files get sent
if(isset($_FILES) && (bool) $_FILES) {
// define allowed extensions
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
// loop through all the files
foreach($_FILES as $name=>$file) {
// define some variables
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
// check if this file type is allowed
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("extension not allowed");
}
// move this file to the server YOU HAVE TO DO THIS
$server_file = "/home/castmeb1/public_html/uploads/$path_parts[basename]";
move_uploaded_file($temp_name,$server_file);
// add this file to the array of files
array_push($files,$server_file);
}
// define some mail variables
$to = "castmebg#gmail.com";
$from = "castmebg#gmail.com";
$subject ="test attachment";
$msg = "Please see attached";
$headers = "From: $from";
// define our boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// tell the header about the boundary
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
// part 1: define the plain text email
$message ="\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n" . $msg . "\n\n";
$message .= "--{$mime_boundary}\n";
// part 2: loop and define mail 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";
}
// send the email
$ok = mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
die();
}
?>
Thanks,
JB
if(isset($_FILES) && (bool) $_FILES) {
is an invalid test for a successful upload. The $_FILES array is always set, and assuming a file upload ATTEMPT was made, the array will NEVER be empty.
You should check for errors like this:
if ($_FILES['name_of_file_field']['error'] === UPLOAD_ERR_OK) {
... file was successfully uploaded ...
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
<?php
// array with filenames to be sent as attachment
$files = array("sendFiles.php");
// email fields: to, from, subject, and so on
$to = "dfjdsoj#googlemail.com";
$from = "mail#mail.com";
$subject ="My subject";
$message = "A logo has been sen't by". $_SESSION['loggedin_business_name'];
$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 = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
echo sizeof($files);
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
?>
I get an email with my sendfiles.php then a text file ATT00424.txt. The number changes everytime. Send it to my gmail and it's fine! Very Strange!
$files = array("sendFiles.php");
// email fields: to, from, subject, and so on
$to = "hdfiuhufsadhfu#yaho.com";
$from = "mail#mail.com";
$subject ="My subject";
$message = "A logo has been sen't by". $_POST['loggedin_business_name'];
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\r\nMIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\r\n" . "--{$mime_boundary}\r\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n" . "Content-Transfer-Encoding: 7bit\r\n" . $message . "\r\n";
$message .= "--{$mime_boundary}\r\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\r\n" . " name=\"$files[$x]\"\r\n" .
"Content-Disposition: attachment;\r\n" . " filename=\"$files[$x]\"\r\n" .
"Content-Transfer-Encoding: base64\r\n" . $data . "\r\n";
$message .= "--{$mime_boundary}\r\n";
}
Adding CRLF in the code fixed the attachment issue however now the message "A logo has been sen't by" has disappeared. Why is this?
Use phpMailer()
<?php
require_once('phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSendmail(); // telling the class to use SendMail transport
try {
$mail->AddReplyTo('email#example.com', 'First Last');
$mail->AddAddress('John#example.com', 'John Doe');
$mail->SetFrom('email#example.com', 'First Last');
$mail->Subject = "Subject Line";
$mail->AltBody = "Alternate Text"; // optional, comment out and test
$mail->WordWrap = 50; // set word wrap
$mail->Body = "This is the body of the email";
$mail->IsHTML(true); // send as HTML
// Single or Multiple File Attachments
$mail->AddAttachment('../path-to-file.pdf', 'File-Name.pdf');
$mail->Send(); // Try to send email
//echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
// end try
?>
Try having CRLF (\r\n) line breaks. Outlook can be a bit funny about these things.
You can use this class
<?php
/*
Usage
=====
set $this->to
set $this->subject
set $this->message (with html tags)
set $this->from (Optional)
set $this->cc (this can be an array or a variable) (Optional)
set $this->bcc (this can be an array or a variable) (Optional)
set $this->reply_to (Optional)
set $this->return_path (Optional)
set $this->x_mailer (Optional)
set $this->attach_file_name (this can be an array or a variable) (Optional)
$this->SendMail();
This function returns an array of 2 elements which e[0] = true (on success) or false and e[1] = message
*/
class EMail
{
var $to;
var $from;
var $cc;
var $bcc;
var $reply_to;
var $return_path;
var $x_mailer;
var $subject;
var $message;
var $attach_file_name;
function EMail()
{
$this->to = "";
$this->subject = "";
$this->message = "";
$this->from = "Administrator <admin#" . $_SERVER['SERVER_NAME'] . ">";
$this->cc = "";
$this->bcc = "";
$this->reply_to = $this->from;
$this->return_path = $this->from;
$this->x_mailer = "PHP v" . phpversion();
$this->attach_file_name = "";
}
function makeFileName ($url)
{
$pos=true;
$PrePos=0;
while (!$pos==false)
{
$pos = strpos($url,'\\',$PrePos);
if ($pos===false)
{
$temp = substr($url,$PrePos);
}
else
{
$PrePos = $pos + 1;
}
}
return $temp;
}
function processAttachment()
{
if(is_array($this->attach_file_name))
{
$s = sizeof($this->attach_file_name);
for($i=0; $i<$s; $i++)
{
if($this->attach_file_name[$i] != "")
{
$handle = fopen($this->attach_file_name[$i], 'rb');
$file_contents = fread($handle, filesize($this->attach_file_name[$i]));
$Attach['contents'][$i] = chunk_split(base64_encode($file_contents));
fclose($handle);
$Attach['file_name'][$i] = $this->makeFileName ($this->attach_file_name[$i]);
$pos=true;
$PrePos=0;
while (!$pos==false)
{
$pos = strpos($this->attach_file_name[$i], '.', $PrePos);
if ($pos===false)
{
$Attach['file_type'][$i] = substr($this->attach_file_name[$i], $PrePos);
}
else
{
$PrePos = $pos+1;
}
}
}
}
return $Attach;
}
else
{
$handle = fopen($this->attach_file_name, 'rb');
$file_contents = fread($handle, filesize($this->attach_file_name));
$Attach['contents'][0] = chunk_split(base64_encode($file_contents));
fclose($handle);
$Attach['file_name'][0] = $this->makeFileName ($this->attach_file_name);
$pos=true;
$PrePos=0;
while (!$pos==false)
{
$pos = strpos($this->attach_file_name, '.', $PrePos);
if ($pos===false)
{
$Attach['file_type'][0] = substr($this->attach_file_name, $PrePos);
}
else
{
$PrePos = $pos+1;
}
}
}
return $Attach;
}
function validateMailAddress($MAddress)
{
if (eregi("#", $MAddress) && eregi(".", $MAddress))
{
return true;
}
else
{
return false;
}
}
function Validate()
{
if(is_array($this->to))
{
$msg[0] = false;
$msg[1] = "You should provide only one receiver email address";
return $msg;
}
if(is_array($this->from))
{
$msg[0] = false;
$msg[1] = "You should provide only one sender email address";
return $msg;
}
if($this->to == "")
{
$msg[0] = false;
$msg[1] = "You should provide a receiver email address";
return $msg;
}
if($this->subject == "")
{
$msg[0] = false;
$msg[1] = "You should provide a subject for your email";
return $msg;
}
if($this->message == "")
{
$msg[0] = false;
$msg[1] = "You should provide message for your email";
return $msg;
}
if(!$this->validateMailAddress($this->to))
{
$msg[0] = false;
$msg[1] = "Receiver E-Mail Address is not valid";
return $msg;
}
if(!$this->validateMailAddress($this->from))
{
$msg[0] = false;
$msg[1] = "Sender E-Mail Address is not valid";
return $msg;
}
if(is_array($this->cc))
{
$s = sizeof($this->cc);
for($i=0; $i<$s; $i++)
{
if(!$this->validateMailAddress($this->cc[$i]) && $this->cc[$i] != "")
{
$msg[0] = false;
$msg[1] = $this->cc[$i] . " is not a valid E-Mail Address";
return $msg;
}
}
}
else
{
if(!$this->validateMailAddress($this->cc) && $this->cc[$i] != "")
{
$msg[0] = false;
$msg[1] = "CC E-Mail Address is not valid";
return $msg;
}
}
if(is_array($this->bcc))
{
$s = sizeof($this->bcc);
for($i=0; $i<$s; $i++)
{
if(!$this->validateMailAddress($this->bcc[$i]) && $this->bcc[$i] != "")
{
$msg[0] = false;
$msg[1] = $this->bcc[$i] . " is not a valid E-Mail Address";
return $msg;
}
}
}
else
{
if(!$this->validateMailAddress($this->bcc) && $this->bcc[$i] != "")
{
$msg[0] = false;
$msg[1] = "BCC E-Mail Address is not valid";
return $msg;
}
}
if(is_array($this->reply_to))
{
$msg[0] = false;
$msg[1] = "You should provide only one Reply-to address";
return $msg;
}
else
{
if(!$this->validateMailAddress($this->reply_to))
{
$msg[0] = false;
$msg[1] = "Reply-to E-Mail Address is not valid";
return $msg;
}
}
if(is_array($this->return_path))
{
$msg[0] = false;
$msg[1] = "You should provide only one Return-Path address";
return $msg;
}
else
{
if(!$this->validateMailAddress($this->return_path))
{
$msg[0] = false;
$msg[1] = "Return-Path E-Mail Address is not valid";
return $msg;
}
}
$msg[0] = true;
return $msg;
}
function SendMail()
{
$mess = $this->Validate();
if(!$mess[0])
{
return $mess;
}
# Common Headers
$headers = "From: " . $this->from . "\r\n";
$headers .= "To: <" . $this->to . ">\r\n";
if(is_array($this->cc))
{
$headers .= "Cc: " . implode(", ", $this->cc) . "\r\n";
}
else
{
if($this->cc != "")
$headers .= "Cc: " . $this->cc . "\r\n";
}
if(is_array($this->bcc))
{
$headers .= "BCc: " . implode(", ", $this->bcc) . "\r\n";
}
else
{
if($this->bcc != "")
$headers .= "BCc: " . $this->bcc . "\r\n";
}
// these two to set reply address
$headers .= "Reply-To: " . $this->reply_to . "\r\n";
$headers .= "Return-Path: " . $this->return_path . "\r\n";
// these two to help avoid spam-filters
$headers .= "Message-ID: <message-on " . date("d-m-Y h:i:s A") . "#".$_SERVER['SERVER_NAME'].">\r\n";
$headers .= "X-Mailer: " . $this->x_mailer . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
# Tell the E-Mail client to look for multiple parts or chunks
$headers .= "Content-type: multipart/mixed; boundary=AttachMail0123456\r\n";
# Message Starts here
$msg = "--AttachMail0123456\r\n";
$msg .= "Content-type: multipart/alternative; boundary=AttachMail7890123\r\n\r\n";
$msg .= "--AttachMail7890123\r\n";
$msg .= "Content-Type: text/plain; charset=iso-8859-1\r\n";
$msg .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
$msg .= strip_tags($this->message) . "\r\n";
$msg .= "--AttachMail7890123\r\n";
$msg .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$msg .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
$msg .= "<html><head></head><body>" . $this->message . "</body></html>\r\n";
$msg .= "--AttachMail7890123--\r\n";
if($this->attach_file_name != "" || is_array($this->attach_file_name))
{
$Attach = $this->processAttachment();
$s = sizeof($Attach['file_name']);
for($i=0; $i<$s; $i++)
{
# Start of Attachment chunk
$msg .= "--AttachMail0123456\r\n";
if ($Attach['file_type'][$i]=="gif")
{
$msg .= "Content-Type: image/gif; name=" . $Attach['file_name'][$i] . "\r\n";
}
elseif ($Attach['file_type'][$i]=="jpg" || $Attach['file_type'][$i]=="jpeg")
{
$msg .= "Content-Type: image/jpeg; name=" . $Attach['file_name'][$i] . "\r\n";
}
else
{
$msg .= "Content-Type: application/file; name=" . $Attach['file_name'][$i] . "\r\n";
}
$msg .= "Content-Transfer-Encoding: base64\r\n";
$msg .= "Content-Disposition: attachment; filename=" . $Attach['file_name'][$i] . "\r\n\r\n";
$msg .= $Attach['contents'][$i] . "\r\n";
}
}
$msg .= "--AttachMail0123456--";
$result = mail($this->to, $this->subject, $msg, $headers);
if ($result)
{
$mess[0] = true;
$mess[1] = "Mail Successfully delivered";
}
else
{
$mess[0] = false;
$mess[1] = "Mail can not be send this time. Please try latter.";
}
return $mess;
}
}
?>
$from = stripslashes("from#demo.com");
$to = stripslashes("to#to.com");
$subject =$_POST['subject'];
$message = $_POST['mailbody'];
// Temporary paths of selected files
$file1 = $_FILES['file1']['tmp_name'];
$file2 = $_FILES['file2']['tmp_name'];
$file3 = $_FILES['file3']['tmp_name'];
// File names of selected files
$filename1 = $_FILES['file1']['name'];
$filename2 = $_FILES['file2']['name'];
$filename3 = $_FILES['file3']['name'];
// array of filenames to be as attachments
$files = array($file1, $file2, $file3);
$filenames = array($filename1, $filename2, $filename3);
// include the from email in the headers
$headers = "From: $from";
// boundary
$time = md5(time());
$boundary = "==Multipart_Boundary_x{$time}x";
// headers used for send attachment with email
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$boundary}\"";
// multipart boundary
$message = "--{$boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$boundary}\n";
// attach the attachments to the message
for($x = 0; $x < count($files); $x++){
if($files[$x] != ""){
$file = fopen($files[$x],"r");
$content = fread($file,filesize($files[$x]));
fclose($file);
$content = chunk_split(base64_encode($content));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . "Content-Disposition: attachment;\n" . " filename=\"$filenames[$x]\"\n" . "Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
$message .= "--{$boundary}\n";
}
}
// sending mail
$sendmail = mail($to, $subject, $message, $headers);
As I understand it, Outlook creates ATT12345.txt attachments when it receives messages in sections with mixed encoding. If it is unable to convert the remainder of the message after a change in encoding (or new MIME part), it dumps the rest in an attachment with the generic names you have been seeing. It seems as if Gmail is handling the format better than Outlook (unsurprising).
I am no Outlook expert (never touch the thing), but it looks as if this answer on SO might help (check your $mime_boundary variable for a trailling '--' after the last part).