I've been searching all day and have not found the code that works. I'm trying, after submitting form,
Validate - This works
Check to see if record exists - This works
Insert record - This works
Attach a CSV that has the form variables - This does not work
This is a scaled down version
<?php
$to = "email#email.com";
if(isset($_POST['submit']))
{
// VALIDATION
if(empty($_POST['address']))
{
"First Name Required";
}
if(empty($_POST['email']))
{
"Last Name Required";
}
if(empty($error))
{
$subject = 'The Form';
$headers = "MIME-Version: 1.0 \r\n";
$headers .= "Content-Type: text/html; \r\n" ;
$headers .= "From: from#theemailaddress.com\r\n"."Reply-to: {$_POST['email']}\r\n";
$msg .="<html>
<head></head>
<body>
<table>
<tr><td>
<table>
<tr><td>This is the email sent.</td></tr>
</table>
</body>
</html>";
include('con.php');
$con = mysqli_connect($host,$user,$pass,$dbName);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"thetable");
$email= mysqli_real_escape_string($con, $_POST['email']);
$address= mysqli_real_escape_string($con, $_POST['address']);
$sql = "SELECT * FROM thetable WHERE `email` = '{$email}' OR `address` = '{$address}'";
$result = mysqli_query($con,$sql);
if(($result->num_rows)>= 1)
{
$theerror = "You exist";
}
else
{
$sql="INSERT INTO thetable(email, address) VALUES ('$_POST[email]','$_POST[address]'";
$success = "Sent ... Insert it!!!";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
//The Attachment
$cr = "\n";
$data = "Email" . ',' . "address" . ',' . $cr;
$data .= "$email" . ',' . "$address" . $cr;
$fp = fopen('diploma_apprenticeship_form_sub.csv','a');
fwrite($fp,$data);
fclose($fp);
$attachments[] = Array(
'data' => $data,
'name' => 'diploma_apprenticeship_form_sub.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" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
//Add a multipart boundary above the plain message
$msg= "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'];
$msg.= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" ;
}
$msg.= "--{$mime_boundary}--\n";
$result = #mail($to, $subject, $msg, $headers);
}
mysqli_close($con);
{
}
}
}
?>
Try this,
$f = fopen('path to file', 'w'); //path such as __DIR__./file.csv'; write mode.
fputcsv( $f, $data);
//data is an array of data ie array('one', 'two'); is one,two in the file ~ make a loop
//around this and write as many lines as you need, like array(header, header1); then
//array(data, data1) etc...
fclose($f); //close the file when done
http://phpmailer.worxware.com/
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->From = 'from#example.com';
$mail->addAddress('joe#example.net', 'Joe User');
$mail->addAttachment( __DIR__.'/file.csv');
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->send();
unlink( __DIR__.'/file.csv' ); //remove the file
Oh and get rid of all that header stuff, let php mailer do its job, which as you mentioned is not to validate your data. Work up a process flow.
Input
Validate
Calculate ( assign values )
Output ( send your email )
Clean up ( remove any files, etc.. )
etc..
AS An update
$msg .="<html>
<head></head>
<body>
<table>
<tr><td>
<table>
<tr><td>This is the email sent.</td></tr>
</table>
</body>
</html>";
... and then latter
$msg= "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";
Also your likely to get a warning for the first message as you are not defining the variable before using the concant on it.
$msg .= 'something';
Should be
$msg = 'something';
Or
$msg = '';
$msg .= 'something';
Related
I am creating pdf using FPDF . Pdf is generating perfectly and also pdf is available with email. But i want to send body message also. I have tried with body message. Example Fine text message This is text message from shohag But only pdf attachment is available and body is empty. Here is my code.
function send_pdf_to_user(){
if($_REQUEST['action'] == 'pdf_invoice' ){
require('html2pdf.php');
$pdf=new PDF_HTML();
$pdf->SetFont('Arial','',11);
$pdf->AddPage();
$text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
if(ini_get('magic_quotes_gpc')=='1')
$text=stripslashes($text);
$pdf->WriteHTML($text);
//documentation for Output method here: http://www.fpdf.org/en/doc/output.htm
$attach_pdf_multipart = chunk_split( base64_encode( $pdf->Output( '', 'S' ) ) );
//define the receiver of the email
$to = 'monirulmask#gmail.com';
//define the subject of the email
$subject = 'Test Invoice';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#test.ch\r\nReply-To: webmaster#test.ch";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$msg .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
$msg .= "Content-Transfer-Encoding: base64\r\n";
$msg .= "Content-Disposition: attachment\r\n";
$msg .= $attach_pdf_multipart . "\r\n";
$msg .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n";
$msg .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$msg .= "<p>This is text message from shohag</p>\r\n\r\n";
global $message;
$message = '';
$mail_sent = #mail( $to, $subject, $msg, $headers );
//#mail( $to1, $subject, $msg, $headers );
if(!empty($mail_sent)):
$message = "Invoice sent succuessfully";
else:
$message = "Error occured. Please try again.";
endif;
}
}
Please check my code and let me know further possibility. Thanks in advance.
You can use PHPMailer with FPDF . It works properly without any hassle. You need to change parameter for $pdf->Output . Download and copy class.phpmailer.php and PHPMailerAutoload.php to your work folder. Attach class.phpmailer.php below or above require('html2pdf.php'); . I have done this before so this will work. According to your code this should work.
function send_pdf_to_user(){
if($_REQUEST['action'] == 'pdf_invoice' ){
require('html2pdf.php');
require_once('class.phpmailer.php');
$pdf=new PDF_HTML();
$pdf->SetFont('Arial','',11);
$pdf->AddPage();
$text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
if(ini_get('magic_quotes_gpc')=='1')
$text=stripslashes($text);
$pdf->WriteHTML($text);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = "This is test mail by monirul";
$mail->AddReplyTo("webmaster#test.ch","Test Lernt");
$mail->SetFrom('webmaster#test.ch', 'Test Lernt');
$address = "monirulmask#gmail.com";
$mail->AddAddress($address, "Abdul Kuddos");
$mail->Subject = "Test Invoice";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
//documentation for Output method here: http://www.fpdf.org/en/doc/output.htm
$pdf->Output("Test Invoice.pdf","F");
$path = "Walter Lernt Invoice.pdf";
$mail->AddAttachment($path, '', $encoding = 'base64', $type = 'application/pdf');
global $message;
if(!$mail->Send()) {
$message = "Invoice could not be send. Mailer Error: " . $mail->ErrorInfo;
} else {
$message = "Invoice sent!";
}
}
}
Use this simple code to send email with pdf attachment. Hope this help you. Thanks.
// Settings
$name = "Name goes here";
$email = "someome#anadress.com";
$to = "$name <$email>";
$from = "Gyan-Shah ";
$subject = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$fileatt = "./test.pdf"; //file location
$fileatttype = "application/pdf";
$fileattname = "newname.pdf"; //name that you want to use to send or you can use the same name
$headers = "From: $from";
// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);
// This attaches the file
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$mainMessage . "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
No external libraries are necessary really. Follow this format:
$to = "email1#domain.com, email2#domain.com"; // addresses to email pdf to
$from = "sent_from#domain.com"; // address message is sent from
$subject = "Your PDF email subject"; // email subject
$body = "<p>The PDF is attached.</p>"; // email body
$pdfLocation = "./your-pdf.pdf"; // file location
$pdfName = "pdf-file.pdf"; // pdf file name recipient will get
$filetype = "application/pdf"; // type
// create headers and mime boundry
$eol = PHP_EOL;
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers = "From: $from$eol" .
"MIME-Version: 1.0$eol" .
"Content-Type: multipart/mixed;$eol" .
" boundary=\"$mime_boundary\"";
// add html message body
$message = "--$mime_boundary$eol" .
"Content-Type: text/html; charset=\"iso-8859-1\"$eol" .
"Content-Transfer-Encoding: 7bit$eol$eol" .
$body . $eol;
// fetch pdf
$file = fopen($pdfLocation, 'rb');
$data = fread($file, filesize($pdfLocation));
fclose($file);
$pdf = chunk_split(base64_encode($data));
// attach pdf to email
$message .= "--$mime_boundary$eol" .
"Content-Type: $filetype;$eol" .
" name=\"$pdfName\"$eol" .
"Content-Disposition: attachment;$eol" .
" filename=\"$pdfName\"$eol" .
"Content-Transfer-Encoding: base64$eol$eol" .
$pdf . $eol .
"--$mime_boundary--";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
change this:
$msg .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
To this:
$msg = "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
I have get value from html form and send via email with multiple attachments. Attachments are not necessary.
I have got some piece of code to send multiple attachments through mail function in php But my mail sending fails and i dont know why. My attachments are not necessary. This is my code:
<?php
function multi_attach_mail($to, $subject, $message, $senderMail, $senderName, $files){
$from = $senderName." <".$senderMail.">";
$headers = "Siuntėjęs: $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; }
}
if($_SERVER['REQUEST_METHOD'] == 'POST'
&& !empty($_POST['namecontact'])
&& !empty($_POST['namecarinfo']) ) {
$contacts = array(
//"autoperka.info#gmail.com",
//"automobiliukas24#gmail.com",
// "ruslanneviadomskij#gmail.com",
"gabriele.giniot#gmail.com"
);
foreach($contacts as $contact) {
$to = $contact; // this is your Email address
$from = $_POST['namecontact']; // this is the sender's Email address
$carinformation = $_POST['namecarinfo'];
$coment = $_POST['namecoment'];
$subject = $from . " SupirkimasPlius.lt";
$from_name = $_POST['namecontact'];
//$headers = "Siuntėjas:" . $from;
//attachment files path array
$file_tmp_name = $_FILES['namephoto']['tmp_name'];
$fileName = $_FILES['namephoto']['name'];
$fileType = $_FILES['namephoto']['type'];
$files = $fileType;
// Message
$html_content = '<br>
<h3>Automobilio pasiūlymas:</h3>
<br>Marke: '.$carinformation.'
<br>Kontaktai: '.$from.'
<br>Komentaras: '.$coment.
'<br>Nuotraukų kiekis'.count($files);
//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
}
$myfile = fopen("success.php", "r") or die(fopen("index.php", "r"));
echo fread($myfile,filesize("success.php"));
fclose($myfile);
//mail('gabriele.giniot#gmail.com',$subject,$message,$headers);
//mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
} else {
$myfile = fopen("failed.php", "r") or die(fopen("index.php", "r"));
echo fread($myfile,filesize("failed.php"));
fclose($myfile);
}
?>
please help me :)
I am creating pdf using FPDF . Pdf is generating perfectly and also pdf is available with email. But i want to send body message also. I have tried with body message. Example Fine text message This is text message from shohag But only pdf attachment is available and body is empty. Here is my code.
function send_pdf_to_user(){
if($_REQUEST['action'] == 'pdf_invoice' ){
require('html2pdf.php');
$pdf=new PDF_HTML();
$pdf->SetFont('Arial','',11);
$pdf->AddPage();
$text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
if(ini_get('magic_quotes_gpc')=='1')
$text=stripslashes($text);
$pdf->WriteHTML($text);
//documentation for Output method here: http://www.fpdf.org/en/doc/output.htm
$attach_pdf_multipart = chunk_split( base64_encode( $pdf->Output( '', 'S' ) ) );
//define the receiver of the email
$to = 'monirulmask#gmail.com';
//define the subject of the email
$subject = 'Test Invoice';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#test.ch\r\nReply-To: webmaster#test.ch";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$msg .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
$msg .= "Content-Transfer-Encoding: base64\r\n";
$msg .= "Content-Disposition: attachment\r\n";
$msg .= $attach_pdf_multipart . "\r\n";
$msg .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n";
$msg .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$msg .= "<p>This is text message from shohag</p>\r\n\r\n";
global $message;
$message = '';
$mail_sent = #mail( $to, $subject, $msg, $headers );
//#mail( $to1, $subject, $msg, $headers );
if(!empty($mail_sent)):
$message = "Invoice sent succuessfully";
else:
$message = "Error occured. Please try again.";
endif;
}
}
Please check my code and let me know further possibility. Thanks in advance.
You can use PHPMailer with FPDF . It works properly without any hassle. You need to change parameter for $pdf->Output . Download and copy class.phpmailer.php and PHPMailerAutoload.php to your work folder. Attach class.phpmailer.php below or above require('html2pdf.php'); . I have done this before so this will work. According to your code this should work.
function send_pdf_to_user(){
if($_REQUEST['action'] == 'pdf_invoice' ){
require('html2pdf.php');
require_once('class.phpmailer.php');
$pdf=new PDF_HTML();
$pdf->SetFont('Arial','',11);
$pdf->AddPage();
$text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
if(ini_get('magic_quotes_gpc')=='1')
$text=stripslashes($text);
$pdf->WriteHTML($text);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = "This is test mail by monirul";
$mail->AddReplyTo("webmaster#test.ch","Test Lernt");
$mail->SetFrom('webmaster#test.ch', 'Test Lernt');
$address = "monirulmask#gmail.com";
$mail->AddAddress($address, "Abdul Kuddos");
$mail->Subject = "Test Invoice";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
//documentation for Output method here: http://www.fpdf.org/en/doc/output.htm
$pdf->Output("Test Invoice.pdf","F");
$path = "Walter Lernt Invoice.pdf";
$mail->AddAttachment($path, '', $encoding = 'base64', $type = 'application/pdf');
global $message;
if(!$mail->Send()) {
$message = "Invoice could not be send. Mailer Error: " . $mail->ErrorInfo;
} else {
$message = "Invoice sent!";
}
}
}
Use this simple code to send email with pdf attachment. Hope this help you. Thanks.
// Settings
$name = "Name goes here";
$email = "someome#anadress.com";
$to = "$name <$email>";
$from = "Gyan-Shah ";
$subject = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$fileatt = "./test.pdf"; //file location
$fileatttype = "application/pdf";
$fileattname = "newname.pdf"; //name that you want to use to send or you can use the same name
$headers = "From: $from";
// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);
// This attaches the file
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$mainMessage . "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
No external libraries are necessary really. Follow this format:
$to = "email1#domain.com, email2#domain.com"; // addresses to email pdf to
$from = "sent_from#domain.com"; // address message is sent from
$subject = "Your PDF email subject"; // email subject
$body = "<p>The PDF is attached.</p>"; // email body
$pdfLocation = "./your-pdf.pdf"; // file location
$pdfName = "pdf-file.pdf"; // pdf file name recipient will get
$filetype = "application/pdf"; // type
// create headers and mime boundry
$eol = PHP_EOL;
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers = "From: $from$eol" .
"MIME-Version: 1.0$eol" .
"Content-Type: multipart/mixed;$eol" .
" boundary=\"$mime_boundary\"";
// add html message body
$message = "--$mime_boundary$eol" .
"Content-Type: text/html; charset=\"iso-8859-1\"$eol" .
"Content-Transfer-Encoding: 7bit$eol$eol" .
$body . $eol;
// fetch pdf
$file = fopen($pdfLocation, 'rb');
$data = fread($file, filesize($pdfLocation));
fclose($file);
$pdf = chunk_split(base64_encode($data));
// attach pdf to email
$message .= "--$mime_boundary$eol" .
"Content-Type: $filetype;$eol" .
" name=\"$pdfName\"$eol" .
"Content-Disposition: attachment;$eol" .
" filename=\"$pdfName\"$eol" .
"Content-Transfer-Encoding: base64$eol$eol" .
$pdf . $eol .
"--$mime_boundary--";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
change this:
$msg .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
To this:
$msg = "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
I am trying to send an image attachment by mail using the code below.
I have a problam in emailClass.php file in line 22 fread(...). I know it because if I echo something before that line, it is echoed successfully, and if i echo something after this line it is not echoed which indicates to me that something is wrong with the fread statement.
The fileatt is ok: I checked it and the full path is printed. I tried with a PNG file and with a 500KB JPG. Then I tried with some text files, but still nothing.
How can I correct this problem?
index.php:
<?php
include "emailClass.php";
$testEmail = new email();
$from = 'someone#gmail.com';
$senfTo = 'someone#gmail.com';
$subject = 'email with attachment';
$bodyHead = 'welcome';
$bodyMain = 'bodyMain writings';
$bodyEnd = 'Thank you';
$filePath = '...';
$fileName = 'check.txt';
if($testEmail->emailWithAttach($from,$sendTo,$subject,$bodyHead,$bodyMain,$bodyEnd,$filePath,$fileName))
{
echo "Email Sent Successfuly";
}
else
{
echo "Failes sending";
}
?>
emailClass.php:
<?php
class email
{
function emailWithAttach($fromaddress,$toAddress,$mailSubject,$mailMessageHead,$mailMessageMain,$mailMessageSign,$filePath,$fileName)
{
$fileatt_name = $fileName;
$fileatt = $filePath.$fileName;
$fileatt_type = "application/octet-stream";
$email_from = $fromAddress;
$email_subject = $mailSubject;
$email_message = $mailMessageHead."<br>";
$email_message .= $mailMessageMain."<br>";
$email_message .= $mailMessageSign;
$email_to = $toAddress;
$headers = "From: ".$email_from;
$file = fopen($fileatt,"rb");
echo $fileatt; //prints ok the correct pathname!!
$data = fread($file,$filesize($fileatt));
echo "check"; //not printing which means something's wrong with line 22 the fread..
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_X{$semi_rand}X";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_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" .
$email_message .= "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data .= "\n\n" .
"--{$mime_boundary}--\n";
if (#mail($email_to, $email_subject, $email_message, $headers))
{
return true;
}
}
}
?>
I am a novice in Web designing. I need to create a form in HTML such that it asks the user to enter several fields and upload his/her resume. When he submits the form, his submissions should be email to me with his resume as the attachment with the email.
I have used PHP for sending the email. Everything works fine, except that the file is not getting attached with the sent email.
I am posting both the HTML and the PHP code, please help me..
HTML Code: FileName: Careers.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Form</title>
</head>
<body>
<form action="Careers.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="cf_name"><br>
E-mail<br>
<input type="text" name="cf_email"><br>
Date of Birth<br>
<input type="text" name="db_name"><br>
Contact Number<br>
<input type="text" name="db_cntct"><br>
Class 12 Marks/CGPA/Percentage<br>
<input type="text" name="cf_board"><br>
Graduation Marks/CGPA/Percentage<br>
<input type="text" name="db_grad"><br>
Post-Graduation Marks/CGPA/Percentage<br>
<input type="text" name="cf_pgrad"><br>
Present Employer<br>
<input type="text" name="db_emplyr"><br>
Date of Joining<br>
<input type="text" name="cf_doj"><br>
Designation<br>
<input type="text" name="db_desg"><br>
Current CTC<br>
<input type="text" name="db_ctc"><br>
Upload your Resume<br>
<input type="file" name="attachment" size="40"><br>
Message<br>
<textarea name="cf_message"></textarea><br><br>
<input type="submit" value="Send">
<input type="reset" value="Clear">
</form>
</body>
</html>
PHP Code: FileName: Careers.php
<?php
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_dob = $_POST['db_name'];
$field_contact = $_POST['db_cntct'];
$field_board = $_POST['cf_board'];
$field_grad = $_POST['db_grad'];
$field_pgrad = $_POST['cf_pgrad'];
$field_emplyr = $_POST['db_emplyr'];
$field_doj = $_POST['cf_doj'];
$field_desg = $_POST['db_desg'];
$field_ctc = $_POST['db_ctc'];
$field_message = $_POST['cf_message'];
$mail_to = 'sachinrocksus#gmail.com';
$subject = 'Job Application from a site visitor '.$field_name;
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Date of Birth: '.$field_dob."\n";
$body_message .= 'Contact Number: '.$field_contact."\n";
$body_message .= 'Class 12 Marks/CGPA/Percentage: '.$field_board."\n";
$body_message .= 'Graduation Marks/CGPA/Percentage: '.$field_grad."\n";
$body_message .= 'Post-Graduation Marks/CGPA/Percentage: '.$field_pgrad."\n";
$body_message .= 'Present Employer: '.$field_emplyr."\n";
$body_message .= 'Date of Joining: '.$field_doj."\n";
$body_message .= 'Designation: '.$field_desg."\n";
$body_message .= 'Current CTC: '.$field_ctc."\n";
$body_message .= 'Message: '.$field_message."\n";
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Your Job Application has been recieved. We will contact you shortly.');
window.location = 'Careers.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed');
window.location = 'Careers.html';
</script>
<?php
}
?>
You are passing nothing as an attachment
Here i am pasting a snippet hope this will help you
<?php
$fileatt = "mypdffile.pdf"; // Path to the file
$fileatt_type = "application/pdf"; // File Type
$fileatt_name = "mypdffile.pdf"; // Filename that will be used for the file as the attachment
$email_from = "sales#mysite.com"; // Who the email is from
$email_subject = "Your attached file"; // The Subject of the email
$email_message = "Thanks for visiting mysite.com! Here is your free file.
";
$email_message .= "Thanks for visiting.
"; // Message that the email has in it
$email_to = $_POST['email']; // Who the email is to
$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_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" .
$email_message .= "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data .= "\n\n" .
"--{$mime_boundary}--\n";
$ok = #mail($email_to, $email_subject, $email_message, $headers);
if($ok) {
echo "You file has been sent
to the email address you specified.
Make sure to check your junk mail!
Click here to return to mysite.com.";
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
?>
This function send upload file as attachment.Please refer the tutorial for html code and step by step explanation.
http://www.pearlbells.co.uk/send-upload-file-email-attachment-php/
function pepareAttachment( $filename ,$fileorgname) {
$attachContent = '';
$file = fopen($filename,"rb");
$data = fread($file,filesize($filename));
fclose($file);
$cvData = chunk_split(base64_encode($data));
$attachContent .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$fileorgname\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$fileorgname\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $cvData . "\n\n";
$attachContent .= "--{$mime_boundary}\n";
return $attachContent;
}
function sendMailAsAttachment( $filename, $fileorgname, $formData ) {
$emailData = prepareEmail( $formData );
$attachContent = prepareAttachment( $filename,$fileorgname );
$message = $emailData['message'].$attachContent;
$ok = #mail($emailData['to'], $emailData['subject'], $message, $emailData['headers']);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
Thanks for sharing such a piece of good code:
Just little modification then this is the real working code.
MAKE A HTML FILE:
Upload File and send as email attachment
Name:
Email:
Select A File To Upload:
Same folder make a php file called mail_sender.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$name_of_uploaded_file =basename($_FILES['uploaded_file']['name']);
$formData = $_POST;
getFile( $name_of_uploaded_file, $formData );
function getFile( $filename , $formData ) {
$allowedExts = array("csv","pdf","jpg","png","JPG","PNG","jpeg","JPEG");
$temp = explode(".", $_FILES["uploaded_file"]["name"]);
$extension = end($temp);
$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv','application/jpg','image/jpg', 'image/jpeg', 'image/png','image/gif');
if (in_array($_FILES['uploaded_file']['type'],$mimes )
&& ($_FILES["uploaded_file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["uploaded_file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["uploaded_file"]["error"] . "<br>";
}
else
{
sendMailAsAttachment($_FILES["uploaded_file"]["tmp_name"],$_FILES["uploaded_file"]["name"],$formData);
}
}
else
{
echo "Invalid file " . $extension . " {} " . $_FILES['uploaded_file']['type'];
//echo in_array($_FILES['uploaded_file']['type'],$mimes );
}
}
//This function accepts post data on form submissions and prepare the email message from the form data.
function prepareEmail( $formData ) {
// email fields: to, from, subject, and so on
$to = "solimankhulna#gmail.com";
$from = "solimankhulna#solimankhulna.com";
$subject ="";
$message = "Uploaded File\n";
$message .= "Name :". $formData['name']."\n";
$message .= "Email Address :". $formData['email']."\n";
$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";
$emailData = array (
'to' => $to,
'from' => $from,
'subject' => $subject,
'headers' => $headers,
'message' => $message
);
return $emailData;
}
function prepareAttachment( $filename ,$fileorgname) {
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$attachContent = '';
$file = fopen($filename,"rb");
$data = fread($file,filesize($filename));
fclose($file);
$cvData = chunk_split(base64_encode($data));
$attachContent .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$fileorgname\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$fileorgname\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $cvData . "\n\n";
$attachContent .= "--{$mime_boundary}\n";
return $attachContent;
}
function sendMailAsAttachment( $filename, $fileorgname, $formData ) {
$emailData = prepareEmail( $formData );
$attachContent = prepareAttachment( $filename,$fileorgname );
$message = $emailData['message'].$attachContent;
$ok = #mail($emailData['to'], $emailData['subject'], $message, $emailData['headers']);
if ($ok) {
echo "<p>mail sent to " . $emailData['to'] . "!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
?>
As said above, you're not getting any attachment processed in your PHP part.
This tutorial might help you walk through the steps one by one.