Mail Server Spam Security Issue - php

I'm getting spam emails from my web form every week. I have tried to make some changes in my query, but that hasn't helped. I am sharing my query below, including the headers.
Can someone help me find where the problem is?
<?php
$submitted_email = '';
if (isset($_SESSION['form'][$mail_from_email])) {
$submitted_email = $_SESSION['form'][$mail_from_email];
}
if (check_email($submitted_email) && $send_from_users_email === false) {
$from = $reply_to = $_SESSION['form'][$mail_from_name].' <'.$submitted_email.'>';
} else {
$from = '<'.$email.'>';
$reply_to = check_email($submitted_email) ? '<'.$submitted_email.'>' : $from;
}
$subject = '';
if (isset($_SESSION['form'][$mail_subject])) {
$subject = $_SESSION['form'][$mail_subject];
}
//email headers
if ($windows_server === true) {
$headers = "From: test.co.uk\r\n" .
"Reply-to: test.co.uk\r\n" .
"Return-Path: test.co.uk\r\n".
"MIME-Version: 1.0\r\nContent-Type: multipart/mixed; " .
"boundary=$mixed_mime_boundary";
} else {
$headers = "From: $from\n" .
"Reply-to: $reply_to\n" .
"MIME-Version: 1.0\nContent-Type: multipart/mixed; " .
"boundary=$mixed_mime_boundary";
} else {
$headers = "From: $from\n" .
"Reply-to: $reply_to\n" .
"MIME-Version: 1.0\nContent-Type: multipart/mixed; " .
"boundary=$mixed_mime_boundary";
}
////////////////////////////
// CONSTRUCT HTML CONTENT //
////////////////////////////
//Construct HTML email content, looping through each form element
//Note: When you get to a file attachment you need to use $_FILES['form_element']['name']
//This will just output the name of the file. The files will actually be attached at the end of the message.
//Set a variable for the message content
$html_content = "<html>\n<head>\n<title>" .
safe_escape_string($subject) .
"</title>\n</head>\n<body>\n<p>\n";
////////////////////////////
// CONSTRUCT TEXT CONTENT //
////////////////////////////
//construct a plain text version of the email.
$text_content = '';
//build a message from the reply for both HTML and text in one loop.
foreach ($form_fields as $field => $label) {
$html_content .= '<b>' . safe_escape_string($label) . '</b> ';
$text_content .= "$label ";
if (isset($_FILES[$field])) {
$string = (isset($_FILES[$field]['name'])) ? $_FILES[$field]['name'] : '';
} else {
$string = (isset($_SESSION['form'][$field])) ? $_SESSION['form'][$field] : '';
}
$html_content .= nl2br(safe_escape_string($string)) . "<br /><br />\n";
$text_content .= "$string\n\n";
}
//close the HTML content.
$html_content .= "</p>\n</body>\n</html>";
/////////////////////////////
// CONSTRUCT EMAIL MESSAGE //
/////////////////////////////
//Now we combine both HTML and plain text version of the email into one.
//Creating the message body which contains a Plain text version and an HTML version,
//users email client will decide which version to display
$message = "\r\n--$mixed_mime_boundary\r\n" .
"Content-Type: multipart/alternative; boundary=$alt_mime_boundary\r\n\r\n" .
"--$alt_mime_boundary\r\n" .
"Content-Type: text/plain; charset=UTF-8; format=flowed\r\n" .
"Content-Transfer-Encoding: Quoted-printable\r\n\r\n" .
"$text_content\r\n\r\n" .
"--$alt_mime_boundary\r\n" .
"Content-Type: text/html; charset=UTF-8\r\n" .
"Content-Transfer-Encoding: Quoted-printable\r\n\r\n" .
"$html_content\r\n\r\n" .
"--$alt_mime_boundary--\r\n\r\n" .
"\r\n\r\n--$mixed_mime_boundary";
//////////////////////
// FILE ATTACHMENTS //
//////////////////////
//loop through the $_FILES global array and add each attachment to the form.
if (isset($_FILES)) {
foreach ($_FILES as $attachment) {
$filename = $attachment['name'];
//if the file has been uploaded
if ($attachment['error'] === UPLOAD_ERR_OK && is_uploaded_file($attachment['tmp_name'])) {
$file = fopen($attachment['tmp_name'],'rb');
$data = fread($file,filesize($attachment['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "\r\nContent-Type: application/octet-stream; name=\"$filename\"" .
"\r\nContent-Disposition: attachment; filename=\"$filename\"" .
"\r\nContent-Transfer-Encoding: base64\r\n\r\n$data\r\n\r\n--$mixed_mime_boundary";
} else if ($attachment['error'] !== UPLOAD_ERR_NO_FILE) {
//try to provide a useful error message determined from the error code.
switch ($attachment['error']) {
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$error = "File $filename exceeds the " . ini_get('upload_max_filesize') . 'B limit for the server.';
break;
case UPLOAD_ERR_PARTIAL:
$error = "Only part of the file $filename could be uploaded, please try again.";
break;
default:
$error = "There has been an error attaching the file $filename, please try again.";
}
redirect($return_url, $error);
}
}
}
//finish off message
$message .= '--';
//for windows users.
if ($windows_server === true) {
ini_set('sendmail_from', $email);
}
//if the mail sending works
if (#mail($email, $subject, $message, $headers)) {
//set the success message
$notice = $message_success;
unset($_SESSION['form']);
} else {
$notice = "I'm sorry, there seems to have been an error trying to send your email. Please try again.";
}
//redirect to the form
redirect($return_url, $notice);
}
?>

Related

PHP - Attaching Text File - Mail Not Working

I am writing an application that is to send an email that contains a CSV as an attachment. However, it is not working. The mail function does not return false (implying that it succeeded); however, the email is not being sent.
I have sent/received email from the server before, so I do not believe that is the issue. However, I do not really have any experience with sending attachments through PHP, so I would suspect the issue lies in there. I have followed this tutorial to an extent: http://www.texelate.co.uk/blog/post/56-send-an-email-attachment-with-php/
Here are some code snippets:
$file = tmpfile();
// code omitted
$fileArray = array(); // this gets filled with more arrays/lines of data
// code omitted
try {
foreach($fileArray as $line) {
var_dump($line);
fputcsv($file, $line);
}
// begin mailing
$toEmail = 'myemail';
$subject = "Insurance Registration";
fseek($file, 0);
$attachData = fread($file, 1024);
$fileName = $lastName . "_" . date('Y');
$random = md5(time());
$boundary = "==Multipart_Boundary_x{$random}x";
$headers = "From: Test \nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed\n" . "boundary=\"{$boundary}\"";
$message = "Testing!.\n\n " . "-{$boundary}\n " . "Content-Type= text/plain; charset=\"iso-8859-1\n" . "Content-Transfer-Encoding 7bit\n\n " . "Testing Again " . "\n\n ";
$attachData = chunk_split(base64_encode($attachData));
$message .= "--{$boundary}\n" . "Content-Type: text/plain;\n" . "name=\"{$fileName}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileName}\"\n" . " . Content-Transfer-Encoding: base64\n\n" . $attachData . "\n\n" . "-{$boundary}-\n";
} catch (Exception $e) {
echo $e->getMessage();
}
if(mail($toEmail, $subject, $message, $headers)) {
} else {
$hasError = true;
}
if($hasError) {
echo "<h2>Error Submitting form. Please check your input and try again</h2>";
} else {
header('Location: success.php');
}
I get redirected to the success page, but never receive an email. Thanks!

php mail() function attachment and body both empty

I have been having difficulty trying to debug my php mail() code. I have included the entire PHP block below, so please forgive the formatting and sections that are not relevant (rCaptcha, field validation etc.)
The issue I am having is that when the emails come through... 1) There is no email body... and 2)The attachment is empty.
If I comment out this line "$body .= $my_attachment ;" I receive the expected text in the body, and unsurprisingly no attachment.
Can anyone spot my undoubtedly rookie mistakes?? I am expecting some replies suggesting I use a PHP mail library, which I am investigating now, but for my understanding and education I would appreciate some specific feedback pointing to my mistakes.
Thank you for your help.
<?php
/********************************************
/ Start processing the email
/*******************************************/
# We'll make a list of error messages in an array
$messages = array();
$upload_folder = "uploads/";
// 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;
// Change this to YOUR address
$recipient = XXX#XXX>COM;
$email = $_POST['myemail'];
$phone = $_POST['phone'];
$realName = $_POST['name'];
$subject = "WEB CONTACT: Careers" ;
$body = "--" . $separator . $eol;
$body .= "FROM: " . $realName .
"\r\nPHONE: " . $phone .
"\r\nEMAIL: " . $email .
"\r\nCONTACT ME VIA: " . $_POST['contact_me'] .
"\r\nMESSAGE:" . $_POST['mymessage'] ;
/********************************************
/ ATTACHMENT
/*******************************************/
//Get the uploaded file information
$name_of_uploaded_file =
basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
//Settings
$max_allowed_file_size = 1024; // size in KB
$allowed_extensions = array("pdf", "doc", "txt");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
$messages[] = "Size of file should be less than " . $max_allowed_file_size;
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$messages[] = "The uploaded file is not supported file type. ".
" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$path_of_uploaded_file))
{
$messages[] = 'Error while copying the uploaded file';
}
}
// attachment
$file = $upload_folder . "/" . $name_of_uploaded_file;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
/***********************************************************
// reCAPTCHA your recaptcha secret key
***********************************************************/
$secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
if(isset($_POST['email']))
{
$email=$_POST['email'];
}
if(isset($_POST['comment']))
{
$email=$_POST['comment'];
}
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
$messages[] = "The reCaptcha Question was not answered correctly. I am begining to suspect that you are a robot.";
}
/***********************************************************
// END reCAPTCHA
***********************************************************/
/***********************************************************
// Message format validations
***********************************************************/
# Allow only reasonable email addresses
if (!preg_match("/^[\w\+\-.~]+\#[\-\w\.\!]+$/", $email)) {
$messages[] = "That is not a valid email address.";
}
# Allow only reasonable real phone numbers
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) {
$messages[] = "The phone number must only include numbers, spaces, brackets(), and '+'.";
}
# Allow only reasonable real names
if (!preg_match("/^[\w\ \+\-\'\"]+$/", $realName)) {
$messages[] = "The real name field must contain only " .
"alphabetical characters, numbers, spaces, and " .
"reasonable punctuation. We apologize for any inconvenience.";
}
# CAREFUL: don't allow hackers to sneak line breaks and additional
# headers into the message and trick us into spamming for them!
$subject = preg_replace('/\s+/', ' ', $subject);
# Make sure the subject isn't blank afterwards!
if (preg_match('/^\s*$/', $subject)) {
$messages[] = "Please choose area and office for your message.";
}
# Make sure the message has a body
if (preg_match('/^\s*$/', $body)) {
$messages[] = "Your message was blank. Did you mean to say " .
"something?";
}
if (count($messages)) {
# There were problems, so tell the user and
# don't send the message yet
foreach ($messages as $message) {
echo("<p>$message</p>\n");
}
echo("<p>Click the back button and correct the problems. " .
"Then click Send Your Message again.</p>");
}
//else
{
# Send the email - we're done
// main header (multipart mandatory)
$headers = "From: " . $realName . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
// message
$headers .= "--" . $separator . $eol;
$headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$headers .= "Content-Transfer-Encoding: 8bit" . $eol;
$headers .= $body . $eol;
// attachment
$my_attachment ="";
$my_attachment .= "--" . $separator . $eol;
$my_attachment .= "Content-Type: application/octet-stream; name=\"" . $name_of_uploaded_file . "\"" . $eol;
$my_attachment .= "Content-Disposition: attachment; filename=\"" . $name_of_uploaded_file . "\"" . $eol;
$my_attachment .= "Content-Transfer-Encoding: base64" . $eol;
$my_attachment .= "Content-Disposition: attachment" . $eol;
$my_attachment .= $content . $eol;
$my_attachment .= "--" . $separator . "--";
$body .= $my_attachment ;
mail($recipient,
$subject,
$body,
$headers
);
echo("<p>Your message has been sent. Thank you!</p>\n");
}
?>
You can use PHPmailer class to send the mail. It is very easy option to send mails.
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:
$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();
It's just that one line $email->AddAttachment(); to add an attachment.

A attachment file with a php form in wordpress

I am making a php form in wordpress.I would like to attach a notepad or PDF file along this form.I am getting all this in email using mail function in a body variable for example
$body =" Attachment: $Attachmentfile";
Instead of file i am receiving file name that user uploading instead of file.I am trying to receive file in email.Actually i am learning too that how to do it.
My php code for assigning to htm file tag is,
if(trim($_POST['Attachmentfile']) === '') {
$AttachmentfileError = 'Please enter a Pdf, Notepad or Word file.';
$hasError = true;
}
else
{
if($_FILES["Attachmentfile"]["name"] != "")
{
$strFilesName = $_FILES["Attachmentfile"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["Attachmentfile"]["tmp_name"])));
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
$strHeader .= $strContent."\n\n";
}
else
{
$Attachmentfile = trim($_POST['Attachmentfile']);
}
}
and my Html code for getting file ,
<li class="left">
<label for="CV">Attachments :</label><span class="error">*</span><br>
<input class="txt" type="file" name="Attachmentfile" id="Attachmentfile" value="<?php if(isset($_POST['Attachmentfile'])) echo $_POST['Attachmentfile'];?>">
</li>
and this is my mail function code,
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
$headers .= "\r\n" . 'Content-type: text/html';
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
Can you help and modify my code in order to get file in email.Thanks friends.
function property_add() {
$data = $_POST['data'];
$data = array_map('trim',$data);
extract($data);
$to = "reciever mail here ";
$subject = "subject here";
$message ='Message here';
$attachments = array(); // initialize attachment array
$upload_dir = wp_upload_dir(); // look for this function in wordpress documentation at codex
$upload_dir = $upload_dir['path'];
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["images"]["tmp_name"][$key]; // Get temp name of uploaded file
$name = time().'_'.$_FILES["images"]["name"][$key]; // rename it to whatever
move_uploaded_file($tmp_name, "$upload_dir/$name"); // move file to new location
$attachments[] = "$upload_dir/$name"; // push the new uploaded file in attachment array
}
}
add_filter( 'wp_mail_content_type', 'set_html_content_type' ); // allow html tags in mail
if(wp_mail($to, $subject, $message,'',$attachments)) {
echo "any success message>";
} else {
echo "failure message ";
}
remove_filter( 'wp_mail_content_type', 'set_html_content_type' ); // remove filter to avoid conflicts
if(!empty($attachments)) {
foreach($attachments as $attachment) {
#unlink($attachment); // delete files after sending them
}
}
}
this is an extract of one of my project .. change it according to your needs i wrote comment so that you get better better ..
call this function on form submit

MIME header appearing in the email message body

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.

How to send email attachments in 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).

Categories