PHP email form with attachments not working - php

I'm trying to use a PHP email form I found online that supports attachments, with a bit of extra code, but it's not working, I get a message saying "Sent", but no emails (I checked spam already).
Here is the php file:
function multi_attach_mail($to, $subject, $message, $senderMail, $senderName, $files){
$from = $senderName." <".$senderMail.">";
$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/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// preparing attachments
if(count($files) > 0){
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;
//send email
$mail = #mail($to, $subject, $message, $headers, $returnpath);
//function return true, if email sent, otherwise return fasle
if($mail){ return TRUE; } else { return FALSE; }
}
$message = "Customer Contact"
. "\n" . "Name: " . $_POST['fullName']
. "\n" . "Email: " . $_POST['email']
. "\n" . "Phone: " . $_POST['phone']
. "\n" . "Current Phone: " . $_POST['currentPhone']
. "\n" . "Address: " . $_POST['address']
. "\n" . "Retailer: " . $_POST['retailer']
. "\n" . "Product Type: " . $_POST['productType']
. "\n" . "Specific Item: " . $_POST['item']
. "\n" . "Purchase Date: " . $_POST['purchaseDate']
. "\n" . "Invoice Number: " . $_POST['invoiceNumber']
. "\n" . "Issue: " . $_POST['issue']
. "\n" . "How did the issue happen?: " . $_POST['how']
. "\n" . "When did the issue occur?: " . $_POST['when']
. "\n" . "Have you done anything to try correcting the issue?: " . $_POST['customerTry'];
$to = 'someEmail#gmail.com';
$from = $_POST['email'];
$from_name = $_POST['fullName'];
//attachment files path array
$files = $_FILES['files'];
$subject = 'Customer Contact From Service Form';
$html_content = $message;
//call multi_attach_mail() function and pass the required arguments
$send_email = multi_attach_mail($to,$subject,$html_content,$from,$from_name,$files);
//print message after email sent
echo $send_email?"<h1> Mail Sent</h1><br>".$message:"<h1> Mail not SEND</h1>";
My form looks like this:
<form NOVALIDATE action="processContact.php" enctype="multipart/form-data" id="claimsForm" method="post" name="claimsForm">
..lots of fields...
<div class="form-group">
<label class="control-label claimsForm-field-header" for="customerTry">Photos:</label>
<input type="file" id="files[]" name="files[]" multiple="multiple" />
</div>
<input class="green-btn" id="ss-submit" name="submit" type="submit" value="Submit">
</form>
The function came with the form I downloaded, so I don't think there is a problem with it. I've been playing around with the code and trying different things, but no luck (I'm not a PHP guy).
EDIT:
Based on the suggestion below, I tried using phpMailer, following the example they have, here is my php file now:
/**
* PHPMailer simple file upload and send example
*/
$msg = '';
$message = "Customer Contact"
. "\n" . "Name: " . $_POST['fullName']
. "\n" . "Email: " . $_POST['email']
. "\n" . "Phone: " . $_POST['phone']
. "\n" . "Current Phone: " . $_POST['currentPhone']
. "\n" . "Address: " . $_POST['address']
. "\n" . "Retailer: " . $_POST['retailer']
. "\n" . "Product Type: " . $_POST['productType']
. "\n" . "Specific Item: " . $_POST['item']
. "\n" . "Purchase Date: " . $_POST['purchaseDate']
. "\n" . "Invoice Number: " . $_POST['invoiceNumber']
. "\n" . "Issue: " . $_POST['issue']
. "\n" . "How did the issue happen?: " . $_POST['how']
. "\n" . "When did the issue occur?: " . $_POST['when']
. "\n" . "Have you done anything to try correcting the issue?: " . $_POST['customerTry'];
$to = 'murtorius#gmail.com';
$from = $_POST['email'];
$from_name = $_POST['fullName'];
//attachment files path array
$files = $_FILES['userfile'];
$subject = 'Customer Contact From Service Form';
if (array_key_exists('userfile', $_FILES)) {
// First handle the upload
// Don't trust provided filename - same goes for MIME types
// See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// Upload handled successfully
// Now create a message
// This should be somewhere in your include_path
require 'php-mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom($from, $from_name);
$mail->addAddress($to, 'TEST');
$mail->Subject = $subject;
$mail->msgHTML($message);
// Attach the uploaded file
$mail->addAttachment($uploadfile, 'Photos');
if (!$mail->send()) {
$msg .= "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg .= "Message sent!";
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
I changed the input file field name to 'userfile[]', but I get this:
Warning: sha1() expects parameter 1 to be string, array given in /home/zucora/service.zucora.com/processContact.php on line 35
Warning: move_uploaded_file() expects parameter 1 to be string, array given in /home/zucora/service.zucora.com/processContact.php on line 36
If I change the name to 'userfile' (without []) I get a blank screen and no email.

Related

MIME email, blank message body

So I tried searching but couldn't find an answer that I was able to apply to my code. I have had a developer updating a page for me and these emails come through on my mobile device, but the body is always blank on my computer email, Thunderbird. The code in question looks like this:
$mailBody = "Dog Registration Form Data" . PHP_EOL . $strDogCName . ";" . $strDogFName . ";" . $strBreed . ";" . $strGender . ";" . $strHt . ";" . $strBdmm . "/" . $strBddd . "/" . $strBdyy . ";" . $strFName . ";" . $strLName . ";" . $strAddr1 . ";" . $strCity . ";" . $strState . ";" . $strZip . ";" . $strCountry . ";" . $strPhone . ";" . $strEMail . ";" . $member_num. ";" . $dog_num;
// injection test before setting message headers
$sender_name = $strFName . " " . $strLName;
$sender_name = injection_test($sender_name);
$sender_email = injection_test($strEMail);
// Set headers and send. This should be moved to a reusable function
$mime_boundary = md5(time());
$headers = '';
$msg = '';
$headers .= 'From: ' . $sender_name . ' <' . $sender_email . '>' . PHP_EOL;
$headers .= 'Reply-To: ' . $sender_name . ' <' . $sender_email . '>' . PHP_EOL;
$headers .= 'Return-Path: ' . $sender_name . ' <' . $sender_email . '>' . PHP_EOL;
$headers .= "Message-ID: <" . time() . "cform#" . $_SERVER['SERVER_NAME'] . ">" . PHP_EOL;
$headers .= 'X-Sender-IP: ' . $_SERVER["REMOTE_ADDR"] . PHP_EOL;
$headers .= "X-Mailer: PHP v" . phpversion() . PHP_EOL;
$headers .= 'MIME-Version: 1.0' . PHP_EOL;
$headers .= 'Content-Type: multipart/related; boundary="' . $mime_boundary . '"';
$msg .= '--' . $mime_boundary . PHP_EOL;
$msg .= 'Content-Type: text/plain; charset="UTF-8"' . PHP_EOL;
$msg .= 'Content-Transfer-Encoding: 8bit' . PHP_EOL . PHP_EOL;
$msg .= $mailBody . PHP_EOL . PHP_EOL;
$msg .= '--' . $mime_boundary . '--' . PHP_EOL . PHP_EOL;
ini_set('sendmail_from', $sender_email);
$msg = "Thank you for registering with NADAC.". PHP_EOL. " Here is the info you provided." . PHP_EOL ."Callname: ". $strDogCName . PHP_EOL. "Registered Name: " . $strDogFName . PHP_EOL . "Breed: " . $strBreed .PHP_EOL . "Gender: " . $strGender .PHP_EOL . "Height: " . $strHt .PHP_EOL . "Birthday: " . $strBdmm . "/" . $strBddd . "/" . $strBdyy .PHP_EOL . "Owner First Name: " . $strFName .PHP_EOL . "Owner Last Name: " . $strLName .PHP_EOL . "Address: " . $strAddr1 .PHP_EOL . "City: " . $strCity .PHP_EOL . "State: " . $strState .PHP_EOL . "Zip Code: " . $strZip .PHP_EOL . "Country: " . $strCountry .PHP_EOL . "Phone: " . $strPhone . PHP_EOL . "Email: " . $strEMail .PHP_EOL . "Associate number: " . $member_num. PHP_EOL . "Dog Number: " . $dog_num;
$mailSubject = "Thank you for registering.";
$send_status = mail($mailTo, $mailSubject, $msg, $headers);
$mailTo = $strEMail;
mail($mailTo, $mailSubject, $msg, $headers);
ini_restore('sendmail_from');
// should check send_status here and do something - TODO
unset($_POST['submitted']);
// Done with the mail, display confirmation
I'm sure it's something simple that I'm just missing. But I can't find it, and the programmer working on it doesn't seem to believe the issue. I don't believe it's a local issue with my email provider.
Have you tried with Content-Type: multipart/alternative instead of 'multipart/related'?
The weird thing if the double mail() calling and $send_status to unknown $mailTo var

php mail function headers with attachment [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm not sure why but this has suddenly stopped sending out emails. I have tried to test the email server using mail("email#domain.com","test","test message"); and it sends it fine. I have a feeling something is wrong with my headers?
I have tried to send it with and without attachments but it is not working.
Any help would be greatly appreciated.
Thanks in advance!
<?php
extract($_POST);
$dir = '../uploads/';
$files_temp = scandir($dir, 1);
foreach ($files_temp as $key=>$value) {
if (strpos($value,$file_id) !== false) {
$files[] = $value;
}
}
$message = "";
$message .= "Firm: " . $_POST['firm'] . "\n";
$message .= "Attorney: " . $_POST['attorney'] . "\n";
$message .= "Main Contact: " . $_POST['main_contact'] . "\n";
$message .= "Phone: " . $_POST['phone'] . "\n";
$message .= "Cell: " . $_POST['cell'] . "\n";
$message .= "Fax: " . $_POST['fax'] . "\n";
$message .= "Address: " . $_POST['address'] . "\n";
$message .= "Email: " . $_POST['email'] . "\n";
$message .= "Court County: " . str_replace("_"," ",$_POST['court_county']) . "\n";
$message .= "Court Name: " . $_POST['court_name'] . "\n";
$message .= "Case Type: " . str_replace("_"," ",$_POST['case_type']) . "\n";
$message .= "Appearance Type: " . $_POST['appearance_type'] . "\n";
$message .= "Date: " . $_POST['date'] . "\n";
$message .= "Time: " . $_POST['time'] . "\n";
$message .= "Department: " . $_POST['department'] . "\n";
$message .= "Case Name: " . $_POST['case_name'] . "\n";
$message .= "Case Number: " . $_POST['case_number'] . "\n";
$message .= "Your Client: " . $_POST['your_client'] . "\n";
$message .= "Client Present: " . $client_present_text . "\n";
$message .= "What do you want the attorney to accomplish at this hearing?: " . $_POST['text1'] . "\n";
$message .= "Explain case background: " . $_POST['text2'] . "\n";
$message .= "Signature: " . $_POST['signature'] . "\n";
// email fields: to, from, subject, and so on
$to = "email#domain.com";
$from = "email#domain.com";
$subject ="Appearance form";
$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($dir.$files[$x],"rb");
$data = fread($file,filesize($dir.$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
$ok = #mail($to, $subject, $message, $headers);
Looks like my code wasn't the problem. It was an issue with mailing it from info#mydomain.com. Changed $from variable to a gmail email address and it started sending emails again.

Multi attachment email issue

I have a problem with sending mail attachments , when you leave the empty not including any attachment. Message comes to mail with the extension .asc, it has file size 3 bytes , I would like to stop including this .asc file when attachment was not chosen.
This is the Form code
<?php
/*
error_reporting(E_ALL);
ini_set('display_errors', 1);
*/
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt","");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
array_push($files,$file);
}
$to = "kontakt#lookslike.pl";
$from = "www.jakasstrona.eu";
$subject = $_POST['imie'];
$message = 'Imię: ' . $_POST['imie'] . "\r\n" .
$message = 'Nazwisko: ' . $_POST['nazwisko'] . "\r\n" .
$message = 'PESEL: ' . $_POST['pesel'] . "\r\n" .
$message = 'NIP: ' . $_POST['nip'] . "\r\n" .
$message = 'Data urodzenia: ' . $_POST['data'] . "\r\n" .
$message = 'Data urodzenia: ' . $_POST['data2'] . "\r\n" .
$message = 'Data urodzenia: ' . $_POST['data3'] . "\r\n" .
$message = 'Obywatelstwo: ' . $_POST['obywatelstwo'] . "\r\n" .
$message = 'Typ: ' . $_POST['typ'] . "\r\n" .
$message = 'Numer Dokumentu: ' . $_POST['nr'] . "\r\n" .
$message = 'Data ważności dokumentu: ' . $_POST['datawaz'] . "\r\n" .
$message = 'Adres, ulica, numer budynku, mieszkania: ' . $_POST['long'] . "\r\n" .
$message = 'Miejscowosc: ' . $_POST['miejscowosc'] . "\r\n" .
$message = 'Kod: ' . $_POST['kod'] . "\r\n" .
$message = 'Poczta: ' . $_POST['poczta'] . "\r\n" .
$message = 'Województwo: ' . $_POST['woj'] . "\r\n" .
$message = 'Telefon komórkowy: ' . $_POST['telefonphon'] . "\r\n" .
$message = 'Telefon stacjonarny: ' . $_POST['telefonstac'] . "\r\n" .
$message = 'E-mail: ' . $_POST['email'] . "\r\n" .
$message = 'Data Wyjazdu: ' . $_POST['datawyj'] . "\r\n" .
$message = 'Data Wyjazdu: ' . $_POST['datawyj2'] . "\r\n" .
$message = 'Data Wyjazdu: ' . $_POST['datawyj3'] . "\r\n" .
$message = 'Doświadczenie zawodowe: ' . $_POST['doswiadczenie'] . "\r\n" .
$message = 'Doświadczenie w pracy zagranicą: ' . $_POST['doswiadczenieza'] . "\r\n" .
$message = 'Uprawnienia na wózki widłowe: ' . $_POST['uprawnienia'] . "\r\n" .
$message = 'Język Angielski: ' . $_POST['jezykang'] . "\r\n" .
$message = 'Język Niemiecki: ' . $_POST['jezyknie'] . "\r\n" .
$message = 'Uwagi: ' . $_POST['uwagi'] . "\r\n" .
$headers = "Od: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; // random
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multi boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"utf-8\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
for($x=0;$x<count($files);$x++){
/*
if (filesize($files[$x] == 3))
{
$y=5;
}
*/
$file = fopen($files[$x]['tmp_name'],"rb");
$data = fread($file,filesize($files[$x]['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$name = $files[$x]['name'];
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// sending
$ok = mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>Mail został wysłany do $to! </p>";
} else {
echo "<p>Mail nie został wysłany!</p>";
}
}
?>
I think if you don't send an attachment, you don't want to add the extra hash. See a simple tutorial here: http://webcheatsheet.com/php/send_email_text_html_attachment.php
maybe put:
if(count($files))
$message .= "--{$mime_boundary}\n";
Though generally, I agree that if you aren't doing this to learn how it is done, use an open source library for this kind of thing as suggested in the comments.

Emailing form data in CSV file format

I have a rather large form that when filled out and submitted, I want the data to be formed into a CSV file and emailed to a specific email address.
Does anyone know if it is all at all possible to add a file upload function to the bottom of this form?
This is for a client and have just encountered limitations in my knowledge of PHP.
This is the code I am using:
<?php
if(isset($_POST['formSubmit'])) {
$email=$_REQUEST['email'];
$firstName=$_REQUEST['firstName'];
$lastName=$_REQUEST['lastName'];
$to = "***#***.co.uk";
$subject = "New application submission";
$message = "".
"Email: $email" . "\n" .
"First Name: $firstName" . "\n" .
"Last Name: $lastName";
//The Attachment
$varTitle = $_POST['formTitle'];
$varForname = $_POST['formForname'];
$varMiddlename = $_POST['formMiddlename'];
$varSurname = $_POST['formSurname'];
$varKnownas = $_POST['formKnownas'];
$varAdressline1 = $_POST['formAdressline1'];
$varAdressline2 = $_POST['formAdressline2'];
$varAdressline3 = $_POST['formAdressline3'];
$varAdressline4 = $_POST['formAdressline4'];
$varAdressline5 = $_POST['formAdressline5'];
$varPostcode = $_POST['formPostcode'];
$varTelephone = $_POST['formTelephone'];
$varMobile = $_POST['formMobile'];
$varEmail = $_POST['formEmail'];
$varApproval = $_POST['formApproval'];
$varothersurname = $_POST['formothersurname'];
$varsex = $_POST['formsex'];
$varninumber = $_POST['formninumber'];
$varjobtitle = $_POST['formjobtitle'];
$vardates = $_POST['formdates'];
$varresponsibilities = $_POST['formresponsibilities'];
$varjobtitle2 = $_POST['formjobtitle2'];
$vardates2 = $_POST['formdates2'];
$varresponsibilities2 = $_POST['formresponsibilities2'];
$varjobtitle3 = $_POST['formjobtitle3'];
$vardates3 = $_POST['formdates3'];
$varresponsibilities3 = $_POST['formresponsibilities3'];
$varwebsite = $_POST['formwebsite'];
$vartshirt = $_POST['formtshirt'];
$vardietary = $_POST['formdietary'];
$varpc = $_POST['formpc'];
$varmac = $_POST['formmac'];
$varlaptop = $_POST['formlaptop'];
$vardongle = $_POST['formdongle'];
$varediting = $_POST['formediting'];
$varsocial = $_POST['formsocial'];
$varphotography = $_POST['formphotography'];
$varfilming = $_POST['formfilming'];
$vartraining = $_POST['formtraining'];
$varexhibition = $_POST['formexhibition'];
$varspecial = $_POST['formspecial'];
$varhobbies = $_POST['formhobbies'];
$varphotography = $_POST['formphotography'];
$varfilming = $_POST['formfilming'];
$vartraining = $_POST['formtraining'];
$varexcel = $_POST['formexcel'];
$varbigpicture = $_POST['formbigpicture'];
$varcriminal = $_POST['formcriminal'];
$attachments[] = Array(
'data' => $data,
'name' => 'application.csv',
'type' => 'application/vnd.ms-excel' );
//Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//Add the headers for a file attachment
$headers = "MIME-Version: 1.0\n" .
"From: {$from}\n" .
"Cc: davidkirrage#gmail.com\n".
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
//Add a multipart boundary above the plain message
$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" .
$text . "\n\n";
//Add sttachments
foreach($attachments as $attachment){
$data = chunk_split(base64_encode($attachment['data']));
$name = $attachment['name'];
$type = $attachment['type'];
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" ;
$message = "--{$mime_boundary}--\n";
mail($to, $subject, $message, $headers);
header('Location: http://bigpictest.co.uk/thanks.php');
exit();
}
}
?>
There is no need to go to so much trouble.
The following will probably help:
$filename="directory/csvfile.csv"; //specify filename and path
$keys=array_keys($_POST); //get list of post keys
$file=fopen($filename,"w"); //open a csv file to write to;
fputcsv($file,$keys); //write post keys as first line of CSV file.
fputcsv($file,$_POST); //write post data as second line of csv file.
fclose($file); //close the file.
The csv file you need to attach is created thus. No need for all those variables.
I haven't checked your mail code. If you are having problems with attaching the file, please ask a different question about that (though there are doubtless answers here already)
Good luck!
I've done this in asp and asp.net but never had to do it with php (that is sending mail with attachments from the server).
The thing to understand is that when you submit the form, the data is being sent to be processed somewhere, lets say: FormProcessor which may be in a separate file or in the php page itself.
So when the FormProcessor receives the data, you can combine it or format it in anyway you like.
You would need access to the filesystem to create the file on the server.
Let's say that the function for sending email is in the FormProcessor scope.
You can use email headers to add the attachment when you define the email object.
This is one of my send email funcitons in php which I've modified to use as a sample here:
function FormProcessor_SendEmail($v){ // $v is an array containing the data to use for sending the email
// parameters = $v[0] = user email, $v[1] = business name,
// $v[2] = address, $v[3] = city, $v[4] = state, $v[5] = zip code,
// $v[6] = phone, $v[7] = message, $v[8] = service area
$eol = "\r\n";
$tb = "\t";
$stb = "\t\t";
// notify new registrant
$to = $v[0];
$subject = "This is the subject text";
$message = "Date : " . $this->prepare_new_timestamp() . ".<br /><br />" . $eol;
$message .= "Thank you for requesting more information about " . $this->get_sitename() . "<br /><br />" . $eol;
$message .= "We will be contacting you as soon as possible<br />" . $eol;
$message .= "with information that is tailored to your needs and interests.<br /><br />" . $eol;
$message .= "We have received the following information from you:<br /><br />" . $eol;
$message .= "Your Business Name: " . $v[1] . "<br />" . $eol;
$message .= "Business Address: " . $v[2] . "<br />" . $eol;
$message .= "City: " . $v[3] . "<br />" . $eol;
$message .= "State: " . $v[4] . "<br />" . $eol;
$message .= "Zip Code: " . $v[5] . "<br />" . $eol;
$message .= "Phone: " . $v[6] . "<br />" . $eol;
$message .= "Service Area: " . $v[8] . "<br />" . $eol;
$message .= "Message: <br />" . $v[7] . "<br /><br />" . $eol;
$message .= "If you have additional questions, please address them to: " . $this->get_support_email() . "<br />" . $eol;
$message .= "or by phone at: " . $this->get_support_phone() . "<br /><br />" . $eol;
$message .= "If you did not submit this request, please contact us and let us know<br />" . $eol;
$message .= "so that we may take the proper actions necessary.<br /><br />" . $eol;
$message .= "Sincerely,<br />" . $eol;
$message .= "The Team at " . $this->get_sitename() . "<br />" . $eol;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: sitename <' . $this->get_webmaster_email() . '>' . "\r\n";
$headers .= 'Cc: webmaster <' . $this->get_webmaster_email() . '>' . "\r\n";
mail($to,$subject,$message,$headers);
return 1;
}
It doesn't send an attachment, but I'm sure someone else on this site can help you find a better way.
Hope it helps.

PHP mail() - HTML shows up as an attachment once a file attachment is added

Had finally gotten all the bugs out of this and now they said "Oh, we'll need to add attachments..." So, this sends an html mail with a plaintext version and was doing just swell. Now that I have the attachments arriving the mail clients are showing the plaintext version inline and the html version as another attachment and then a seemingly empty 93 byte file with a name like ATT00248.txt.
Can anyone either bash me over the head from behind or tell me where I am going wrong? I want the HTML inline where available in the mail user interface, the plain text version where HTML is not available, and the single attachment as an attachment.
Any help?
<?php
$template = $_SERVER['DOCUMENT_ROOT'] . '/leads/templates/'.$_SESSION['templateFile'];
ob_start();
include($template);
$html = ob_get_contents();
ob_end_clean();
if (strlen($html) == 0) {
echo "The template at $template did not load.";
exit;
}
$email = $_SESSION['user']->email;
$name = $_SESSION['user']->first_name . ' ' . $_SESSION['user']->last_name;
$from = "$name <$email>";
$subject = unslash($_SESSION['subject']);
$TextMessage = strip_tags(unslash($_SESSION['message']));
$notice_text = "This is a multi-part message in MIME format.";
$plain_text = str_replace(' ',' ', $TextMessage);
if ($_SESSION['attachment']) {
$fileatt = 'files/' . $_SESSION['attachment'];
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$data = chunk_split(base64_encode($data));
$mailtype = 'mixed';
$fileatt_type = "application/octet-stream";
$fileatt_name = $_SESSION['attachment'];
} else {
$mailtype = 'alternative';
}
$semi_rand = md5(time());
$mime_boundary = "==MULTIPART_BOUNDARY_$semi_rand";
$mime_boundary_header = chr(34) . $mime_boundary . chr(34);
$body = "$notice_text
--$mime_boundary
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
$plain_text
--$mime_boundary
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit
$html
--$mime_boundary
";
$body .= "Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Disposition: attachment;\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--$mime_boundary\n";
// #1 //
if ($to = $_SESSION['recipients'][0]) {
mail($to, $subject, $body,
"From: " . $from . "\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/$mailtype;\n" .
" boundary=" . $mime_boundary_header);
echo "Email sent to " . htmlentities($to) . ".<br />";
}
// #2 //
if ($to = $_SESSION['recipients'][1]) {
mail($to, $subject, $body,
"From: " . $from . "\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/$mailtype;\n" .
" boundary=" . $mime_boundary_header);
echo "Email sent to " . htmlentities($to) . ".<br />";
}
// #3 //
if ($to = $_SESSION['recipients'][2]) {
mail($to, $subject, $body,
"From: " . $from . "\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/$mailtype;\n" .
" boundary=" . $mime_boundary_header);
echo "Email sent to " . htmlentities($to) . ".<br />";
}
// #4 //
if ($to = $_SESSION['recipients'][3]) {
mail($to, $subject, $body,
"From: " . $from . "\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/$mailtype;\n" .
" boundary=" . $mime_boundary_header);
echo "Email sent to " . htmlentities($to) . ".<br />";
}
// #5 //
if ($to = $_SESSION['recipients'][4]) {
mail($to, $subject, $body,
"From: " . $from . "\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/$mailtype;\n" .
" boundary=" . $mime_boundary_header);
echo "Email sent to " . htmlentities($to) . ".<br />";
}
// CC self? //
if ($_SESSION['cc_me']) {
mail($from, $subject, $body,
"From: " . $from . "\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/$mailtype;\n" .
" boundary=" . $mime_boundary_header);
echo "Email sent to " . htmlentities($from) . ".<br />";
}
if ($fileatt) {
unlink($fileatt);
}
echo "<a href='email_start.php'>Click here</a> to send another email.";
list($_SESSION['email'], $_SESSION['subject'], $_SESSION['bullets'], $_SESSION['message'],
$_SESSION['templateFile'], $_SESSION['template'], $_SESSION['cc_me'], $_SESSION['recipients']) = '';
?>
Pekka had it right - It was simple and robust to use Swiftmailer. http://swiftmailer.org
I'd post this as a comment, but it's too long.
// #1 //
if ($to = $_SESSION['recipients'][0]) {
mail($to, $subject, $body,
"From: " . $from . "\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/$mailtype;\n" .
" boundary=" . $mime_boundary_header);
echo "Email sent to " . htmlentities($to) . ".<br />";
}
// #2 ... #3 ... #4 ... #5
Will end up executing all blocks, since ($to = $_SESSION['recipients'][0]) will be always true. It will also display the "Email sent to ..." even when mail() fails.
What you want is:
if (in_array($to, $_SESSION['recipients'])) {
if (mail($to, $subject, $body,
"From: " . $from . "\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/$mailtype;\n" .
" boundary=" . $mime_boundary_header)) {
echo "Email sent to " . htmlentities($to) . ".<br />";
}
}
Or, if you really want to mail everyone, or
foreach ($_SESSION['recipients'] as $to ) {
if (mail($to, $subject, $body,
"From: " . $from . "\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/$mailtype;\n" .
" boundary=" . $mime_boundary_header)) {
echo "Email sent to " . htmlentities($to) . ".<br />";
}
}

Categories