Uploading an image from contact form and send as email attachement - php

I am trying to add a new field in the contact us form field, but I am stumped on how to properly do this. I simply need to have the uploaded file be sent as an attachment of the contact us email. Thanks in advance Rahul
Here is my PHP code:
<?php
$submitted = FALSE;
if ($_POST['contact_form']) {
$submitted = TRUE; // The form has been submitted and everything is ok so far…
$name = htmlspecialchars($_POST['name'], ENT_QUOTES);
$email = htmlspecialchars($_POST['email'], ENT_QUOTES);
$country = htmlspecialchars($_POST['country'], ENT_QUOTES);
$message = htmlspecialchars($_POST['message'], ENT_QUOTES);
if ($name == "") {
// if the name is blank… give error notice.
echo "<p>Please enter your name.</p>";
$submitted = FALSE; // Set this to FALSE so that it the message is not sent.
}
if ($email == "") {
// if the email is blank… give error notice.
echo "<p>Please enter your e-mail address so that we can reply to you.</p>";
$submitted = FALSE; // Set this to FALSE so that it the message is not sent.
}
if ($country == "") {
// if the country is blank… give error notice.
echo "<p>Please enter your country.</p>";
$submitted = FALSE; // Set this to FALSE so that it the message is not sent.
}
if ($message == "") {
// if the message is blank… give error notice.
echo "<p>Please enter a question.</p>";
$submitted = FALSE; // Set this to FALSE so that it the message is not sent.
}
if ($_POST['email'] != "" && (!strstr($_POST['email'],"#") || !strstr($_POST['email'],".")))
{
// if the string does not contain "#" OR the string does not contain "." then…
// supply a different error notice.
echo "<p>Please enter a valid e-mail address.</p>";
$submitted = FALSE; // Set this to FALSE so that it the message is not sent.
}
$problemIn = '';
$ip = $_SERVER['REMOTE_ADDR'];
$url = (!empty($_SERVER['HTTPS']))
? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
: "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$to = "rahul#test.com"; // Set the target email address.
$header = "From: $email";
$attention = "Someone has sent you question from your webpage!";
$message = "Name: $name \n Country: $country \n Question: $message \n IP Address: $ip \n Link: $url \n";
if ($submitted == TRUE)
{
mail($to, $attention, $message, $header);
echo '<script type="text/javascript">alert("Thank you. Your question has been sent.");</script>';
}
}
?>
Here is my HTML code:
<form method="post" name="frmmail" id="frmmail" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" onSubmit="javascript: return validation();" eenctype="multipart/form-data">
<input name="name" id="txtname" value="" placeholder="Name" onfocus="if(this.value == 'Name')" class="usericon" />
<input name="email" id="txtmail" value="" placeholder="Email" onfocus="if(this.value == 'Email')" class="emailicon" />
<input name="country" id="txtcountry" value="" placeholder="Country" onfocus="if(this.value == 'Country')" style="margin:0" class="countryicon" />
<textarea name="message" id="txtmsg" placeholder="Your Comment/Question" onfocus="if(this.value == 'Your Question')" class="msgicon"></textarea>
<input type="file" name="file" class="file" />
<input type="submit" value="Submit" class="button" />
<input type="hidden" name="contact_form" value="submitted" />
</form>

Here is HTML Form
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email Attachment Without Upload - Excellent Web World</title>
<style>
body{ font-family:Arial, Helvetica, sans-serif; font-size:13px;}
th{ background:#999999; text-align:right; vertical-align:top;}
input{ width:181px;}
</style>
</head>
<body>
<form action="emailSend.php" method="post" name="mainform" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="5" cellspacing="5">
<tr>
<th>Your Name</th>
<td><input name="fieldFormName" type="text"></td>
</tr>
<tr>
<tr>
<th>Your Email</th>
<td><input name="fieldFormEmail" type="text"></td>
</tr>
<tr>
<th>To Email</th>
<td><input name="toEmail" type="text"></td>
</tr>
<tr>
<th>Subject</th>
<td><input name="fieldSubject" type="text" id="fieldSubject"></td>
</tr>
<tr>
<th>Comments</th>
<td><textarea name="fieldDescription" cols="20" rows="4" id="fieldDescription"></textarea></td>
</tr>
<tr>
<th>Attach Your File</th>
<td><input name="attachment" type="file"></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="submit" name="Submit" value="Send"><input type="reset" name="Reset" value="Reset"></td>
</tr>
</table>
</form>
PHP Code
<?php
$to = $_POST['toEmail'];
$fromEmail = $_POST['fieldFormEmail'];
$fromName = $_POST['fieldFormName'];
$subject = $_POST['fieldSubject'];
$message = $_POST['fieldDescription'];
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Start of headers */
$headers = "From: $fromName";
if (file($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
echo "A email has been sent to: $to";
}
else{
echo "Error in Email sending";
}
?>

Related

Adding a captcha to a form

I'm working on creating a php contact form with a captcha but am not able to figure out how to actually get the captcha image to show. So far it just shows an close button x with the words CAPTCHA image in place of the real image. I also want to split the name field up into 2 fields First Name and Last Name on the same line. Any help is greatly appreciated. Here is both the html code and then the php code:
<!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>Formify</title>
<link href="style/default.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/ajaxfileupload.js" type="text/javascript"></script>
<script src="js/formify.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<!-- header start -->
<div id="header">
<a href="#">
<img src="images/logo.png" style="display: none" alt="Formify Logo" /></a>
</div>
<!-- header end -->
<!-- content start -->
<form action="" method="POST" enctype="multipart/form-data">
<div id="content">
<div class="switcher">
<select name="form-types" id="form-types">
<option value="none">Select Form Type</option>
<option value="question-form" selected="true">Ask a Question Form</option>
<option value="contact-form">Contact Form</option>
<option value="feedback-form">Feedback Form</option>
</select>
</div>
<form>
<div class="form-fields">
<!-- Ask a Question Form -->
<div id="question-form" class="form">
<h1>
Ask a Question Form</h1>
<table cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="text" id="qf-full-name" value="Full Name" class="required" title="Full Name" />
</td>
</tr>
<tr>
<td>
<input type="text" id="qf-email-address" value="Email Address" class="email-address"
title="Email Address" />
</td>
</tr>
<tr>
<td>
<input type="text" id="qf-subject" value="Subject" title="Subject" />
</td>
</tr>
<tr>
<td>
<input type="file" id="attachment" name="attachment" />
<img src="images/sending.gif" alt="uploading..." id="uploading" />
</td>
</tr>
<tr>
<td>
<textarea rows="7" id="qf-message"></textarea>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="qf-cc" />
CC this message to yourself
</td>
</tr>
</table>
</div>
<!-- Contact Form -->
<div id="contact-form" class="form hidden">
<h1>
Contact Form</h1>
<table cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="text" id="cf-full-name" value="Full Name" title="Full Name" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-email-address" value="Email Address" class="email-address"
title="Email Address" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-telephone" value="Telephone" class="telephone" title="Telephone" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-website" value="Website" title="Website" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-subject" value="Subject" title="Subject" />
</td>
</tr>
<tr>
<td>
<textarea rows="7" id="cf-message"></textarea>
</td>
</tr>
</table>
</div>
<!-- Feedback Form -->
<div id="feedback-form" class="form hidden">
<h1>
Feedback Form</h1>
<table cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="text" id="ff-full-name" value="Full Name" title="Full Name" />
</td>
</tr>
<tr>
<td>
<input type="text" id="ff-email-address" value="Email Address" class="email-address"
title="Email Address" />
</td>
</tr>
<tr>
<td>
<input type="text" id="ff-telephone" value="Telephone" class="telephone" title="Telephone" />
</td>
</tr>
<tr>
<td>
<select id="ff-options">
<option>I have a suggestion</option>
<option>I want to register a complain</option>
<option>I am not satisfied</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="ff-other" />
</td>
</tr>
<tr>
<td>
<input type="text" id="ff-subject" value="Subject" title="Subject" />
</td>
</tr>
<tr>
<td>
<textarea rows="7" id="ff-message"></textarea>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="ff-keep-anonymous" />
Keep anonymous
</td>
</tr>
</table>
</div>
<table>
<tr>
<td>
<img id="siimage" style="border: 1px solid #000; margin-right: 15px" src="securimage/securimage_show.php?sid=<?php echo md5(uniqid()) ?>"
alt="CAPTCHA Image" align="left">
<object type="application/x-shockwave-flash" data="securimage/securimage_play.swf?audio_file=securimage/securimage_play.php&bgColor1=#fff&bgColor2=#fff&iconColor=#777&borderWidth=1&borderColor=#000"
height="32" width="32">
<param name="movie" value="securimage/securimage_play.swf?audio_file=securimage/securimage_play.php&bgColor1=#fff&bgColor2=#fff&iconColor=#777&borderWidth=1&borderColor=#000">
</object>
<a tabindex="-1" style="border-style: none;" href="#" title="Refresh Image"
onclick="document.getElementById('siimage').src = 'securimage/securimage_show.php?sid=' + Math.random(); this.blur(); return false">
<img src="securimage/images/refresh.png" id="refresh-captcha" alt="Reload Image"
onclick="this.blur()" align="bottom" border="0"></a><br />
<strong>Enter Code*:</strong><br />
<input type="text" id="captcha" size="12" maxlength="8" autocomplete='off' />
</td>
</tr>
<tr>
<td>
<input type="submit" class="large button green" value="Send Message" />
<label class="submit-message">
</label>
<img class="submit-sending" src="images/sending.gif" alt="sending..." />
</td>
</tr>
</table>
</div>
</form>
<!-- content end -->
</div>
</form>
</div>
</body>
</html>
<?php
require("class.phpmailer.php");
//Variables Declaration
$name = "the Submitter";
$email_subject = "Feed Back";
$Email_msg ="A visitor submitted the following :\n";
$Email_to = "you#yourSite.com"; // the one that recieves the email
$email_from = "someone#someone.net";
$dir = "uploads/$filename";
chmod("uploads",0777);
$attachments = array();
checkType();
//------Check TYPE------\\
function checkType() {
while(list($key,$value) = each($_FILES[attachment][type])){
strtolower($value);
if($value != "image/jpeg" AND $value != "image/pjpeg" AND $value != "") {
exit('Sorry , current format is <b>'.($value).'</b> ,only Jpeg or jpg are allowed.') ;
}
}
checkSize();
}
//-------END OF Check TYPE--------\\
//---CheckSizeFunction ---\\
function checkSize(){
global $result, $MV ,$errors,$BackLink;
while(list($key,$value) = each($_FILES[attachment][size]))
{
$maxSize = 5000000;
if(!empty($value)){
if ($value > $maxSize) {
echo"Sorry this is a very big file .. max file size is $maxSize Bytes = 5 MB";
exit();
}
else {
$result = "File size is ok :)<br>";
}
}
}
uploadFile();
}
//-------END OF Check Size--------\\
//==============upload File Function============\\
function uploadFile() {
global $attachments;
while(list($key,$value) = each($_FILES[attachment][name]))
{
if(!empty($value))
{
$filename = $value;
array_push($attachments, $filename);
$dir = "uploads/$filename";
chmod("uploads",0777);
$success = copy($_FILES[attachment][tmp_name][$key], $dir);
}
}
if ($success) {
echo " Files Uploaded Successfully<BR>";
SendIt();
}else {
exit("Sorry the server was unable to upload the files...");
}
}
//======================================================================== PHP Mailer With ATtachment Func ===============================\\
function readMailSettings()
{
global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
$file = fopen('mail.config','r');
while(!feof($file))
{
$setting = explode(':',fgets($file));
//print_r($setting);
switch($setting[0])
{
case 'SMTPSERVER':
$SMPTSERVER = $setting[1];
break;
case 'SMTPPORT':
$SMTPPORT = $setting[1];
break;
case 'SMTPUSER':
$SMPTUSER = $setting[1];
break;
case 'SMTPPASSWORD':
$SMTPPASSWORD = $setting[1];
break;
case 'ADMINEMAIL':
$ADMINEMAIL = $setting[1];
break;
case 'ADMINNAME':
$ADMINNAME = $setting[1];
break;
}
}
}
function SendIt() {
global $attachments,$name,$Email_to,$Email_msg,$email_subject,$email_from;
$mail = new PHPMailer();
$mail->IsSMTP();// send via SMTP
$mail->Host = "localhost"; // SMTP servers
$mail->SMTPAuth = false; // turn on/off SMTP authentication
$mail->From = $email_from;
$mail->FromName = $name;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
foreach($attachments as $key => $value) { //loop the Attachments to be added ...
$mail->AddAttachment("uploads"."/".$value);
}
$mail->Body = $Email_msg."Name : ".$name."\n";
$mail->IsHTML(false);// send as HTML
$mail->Subject = $email_subject;
if(!$mail->Send())
{
echo "Message was not sent <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
// after mail is sent with attachments , delete the images on server ...
foreach($attachments as $key => $value) {//remove the uploaded files ..
unlink("uploads"."/".$value);
}
}
?>
<?php
$error = "";
$msg = "";
$fileElementName = 'attachment';
chmod("uploads",0777);
if(!empty($_FILES[$fileElementName]['error']))
{
switch($_FILES[$fileElementName]['error'])
{
case '1':
$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case '2':
$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case '3':
$error = 'The uploaded file was only partially uploaded';
break;
case '4':
$error = 'No file was uploaded.';
break;
case '6':
$error = 'Missing a temporary folder';
break;
case '7':
$error = 'Failed to write file to disk';
break;
case '8':
$error = 'File upload stopped by extension';
break;
case '999':
default:
$error = 'No error code avaiable';
}
}elseif(empty($_FILES['attachment']['tmp_name']) || $_FILES['attachment']['tmp_name'] == 'none')
{
$error = 'No file was uploaded..';
}else
{
if (file_exists("uploads/" . $_FILES["attachment"]["name"]))
{
//echo $_FILES["attachment"]["name"] . " already exists. ";
#unlink("uploads"."/".$_FILES["attachment"]["name"]);
}
$msg = $_FILES["attachment"]["name"];
move_uploaded_file($_FILES["attachment"]["tmp_name"],
"uploads/" . $_FILES["attachment"]["name"]);
}
echo "{";
echo "error: '" . $error . "',\n";
echo "attachment: '" . $msg . "'\n";
echo "}";
?>
<?php
session_start();
require_once('phpmailer/class.phpmailer.php');
$SMTPSERVER='';
$SMTPPORT='';
$SMTPUSER='';
$SMTPPASSWORD='';
$ADMINEMAIL='';
$ADMINNAME='';
$from = $_POST['email'];
$fullName= $_POST['from'];
$subject= $_POST['subject'];
$message= $_POST['message'];
$cc = $_POST['cc'];
$anonymous = $_POST['anonymous'];
$attachment = $_POST['attachment'];
$_SESSION['ctform'] = array(); // re-initialize the form session data
$errors = array(); // initialize empty error array
// Only try to validate the captcha if the form has no errors
// This is especially important for ajax calls
$captcha = $_POST['code'];
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered<br />';
}
//echo 'Incorrect security code entered<br />';
}
if (sizeof($errors) == 0) {
echo smtpmailer($from,$fullName,$subject,$message,$anonymous,$attachment);
}
else
{
echo $errors['captcha_error'];
}
function smtpmailer($from, $from_name, $subject, $body,$anonymous,$attachment) {
global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
global $cc;
global $error;
readMailSettings();
$to = $ADMINEMAIL;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->IsMail();//enable email through php mail();
//$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
//$mail->SMTPAuth = true; // authentication enabled
//$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
//$mail->Host = $SMTPSERVER;
//$mail->Port = $SMTPPORT;
//$mail->Username = $SMTPUSER;
//$mail->Password = $SMTPPASSWORD;
$mail->IsHTML(true);
if($anonymous == 'true')
{
$from= $to;
$from_name = 'Anonymous';
}
$mail->SetFrom($from, $from_name);
$body .= "Is Anonymous: " . $anonymous;
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
$attachmentFailed = false;
$attachmentPath = "uploads"."/".$attachment;
if(!empty($attachment))
{
chmod("uploads",0777);
if(file_exists($attachmentPath))
$mail->AddAttachment($attachmentPath, $attachment);
else
{
echo "Attachement failed";
$attachmentFailed = true;
}
}
if(!$attachmentFailed)
{
if(!empty($cc))
$mail->AddCC($from);
if(!$mail->Send()) {
if(!empty($attachment))
//echo 'Mail attachment error: '.$mail->ErrorInfo;
echo "Unable to attach your file at the moment, please try again later.";
else
return false;
} else {
if(!empty($attachment))
unlink($attachmentPath);
return true;
}
}
}
function readMailSettings()
{
global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
$file = fopen('mail.config','r');
while(!feof($file))
{
$setting = explode(':',fgets($file));
//print_r($setting);
switch($setting[0])
{
case 'SMTPSERVER':
$SMPTSERVER = $setting[1];
break;
case 'SMTPPORT':
$SMTPPORT = $setting[1];
break;
case 'SMTPUSER':
$SMPTUSER = $setting[1];
break;
case 'SMTPPASSWORD':
$SMTPPASSWORD = $setting[1];
break;
case 'ADMINEMAIL':
$ADMINEMAIL = $setting[1];
break;
case 'ADMINNAME':
$ADMINNAME = $setting[1];
break;
}
}
}
?>
<?php
function multi_attach_mail($to, $files, $sendermail){
// email fields: to, from, subject, and so on
$from = "Files attach <".$sendermail.">";
$subject = date("d.M H:i")." F=".count($files);
$message = date("Y.m.d H:i:s")."\n".count($files)." attachments";
$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/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// preparing attachments
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;
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){ return $i; } else { return 0; }
}
?>
The image is probably not appearing because the path to the captcha image is securimage/securimage_show.php which may be incorrect relative to the location of your form.
Something like /securimage/securimage_show.php may be more appropriate. Also check to make sure the captcha image displays correctly and works on your system by going to securimage/example_form.php.
Securimage also provides a method which will render the captcha html for you which may work better. In that case try:
<?php
// show captcha HTML using Securimage::getCaptchaHtml()
require_once 'securimage.php'; // CHANGE THIS TO THE CORRECT PATH
$options = array();
echo Securimage::getCaptchaHtml($options);
?>

Php form upload and email

I have the following code, ideally, it is expected that the user shall upload a file(image/video) when submitting the form, but it is not compulsory though.
<?php
$to = "someone#example.com";
$fromEmail = $_POST['fieldFormEmail'];
$fromName = $_POST['fieldFormName'];
$subject = $_POST['fieldSubject'];
$message = $_POST['fieldDescription'];
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Start of headers */
$headers = "From: $fromName";
if (file($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
echo "A email has been sent to: $to";
}
else{
echo "Error in Email sending";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email Attachment Without Upload - Excellent Web World</title>
<style>
body{ font-family:Arial, Helvetica, sans-serif; font-size:13px;}
th{ background:#999999; text-align:right; vertical-align:top;}
input{ width:181px;}
</style>
</head>
<body>
<form action="Contact.php" method="post" name="mainform" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="5" cellspacing="5">
<tr>
<th>Your Name</th>
<td><input name="fieldFormName" type="text"></td>
</tr>
<tr>
<tr>
<th>Your Email</th>
<td><input name="fieldFormEmail" type="text"></td>
</tr>
<tr>
<th>Subject</th>
<td><input name="fieldSubject" type="text" id="fieldSubject"></td>
</tr>
<tr>
<th>Comments</th>
<td><textarea name="fieldDescription" cols="20" rows="4" id="fieldDescription"></textarea></td>
</tr>
<tr>
<th>Attach Your File</th>
<td><input name="attachment" type="file"></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="submit" name="Submit" value="Send"><input type="reset" name="Reset" value="Reset"></td>
</tr>
</table>
</form>
</body>
<html>
The problem that i am facing is,
it runs on page load, and
if file has not been uploaded, it throws a warning.
I tried putting the file upload part under "if filename exists" condition, but then the email does not send the attachment
Please help.
This file name is Contact.php
it runs on page load
enclose mail send feature in
if(isset($_POST['Submit']) && ($_POST['Submit']) == 'Send' )
{
/* process only when submit button whose name='Submit'
and value= 'Send' is pressed
entire PHP code */
}
if file has not been uploaded, it throws a warning.
check before attaching it in PHP
if((empty($_POST['attachment'])) || (empty($_FILES['attachment']))){
//file is not attached, show error
}else{
//file is attached, process it and send via mail
}

How do i add attach file to my online emailer PHP?

I hope you will help me with my question, because i really need it for my site.
How do i add the possibility to attach a file to a online emailer I've written in PHP? :)
Here is the code that i would like to add it to:
<?php
session_start();
if( isset($_POST['submit']))
{
if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) )
{
$to=$_POST["to"];
$from=$_POST["from"];
$name=$_POST["name"];
$subject=$_POST["subject"];
$message=$_POST["message"];
$message=$message."\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
$head="From: ".$from."\r\n".'Reply-To: '.$From."\r\n";
$her=$head.' < '.$from.' >';
$techomag=mail($to, $subject, $message, $her);
echo "Your Message Has been send successfully...:)..";
unset($_SESSION['security_code']);
echo( 'Click here to send another email' );
}
else
{
echo 'Sorry, you have provided an invalid captcha security code :(...';
echo( 'Click here to Go back and try once more' );
}
}
else
{
?>
<?php
?>
<div style="height:10px; clear:both"></div>
<form action="index.php" method="post">
<table border="1"><tbody>
<tr><td>To Email :</td><td><input name="to" type="text" /></td></tr>
<tr><td>From Email :</td><td><input name="from" type="text" /></td></tr>
<tr><td>From Name :</td><td><input name="name" type="text" /></td></tr>
<tr><td>Subject :</td><td><input name="subject" type="text" /></td></tr>
<tr><td>Message :</td><td><textarea cols="30" rows="10" name="message"></textarea></td></tr>
<tr><td><img src="CaptchaSecurityImages.php?width=100&height=40&characters=5" /><br />
<label for="security_code">Security Code: </label><input id="security_code" name="security_code" type="text" />
<input type="submit" name="submit" value="Send Email!" /></td></tr>
</tbody></table>
</form>
<?php
}
?>
Well for complex emailing with PHP checkout the PHPMailer class.
It is much easier to send complex emails (e.g. with attachment) with the functions in PHPMailer.
<?php
$filename = "form.txt"; //attach filename
$to = "abc#mail.ru"; //To
$from = "def#gmail.com"; //From
$subject = "Test"; //Subj
$message = "Текстовое сообщение"; //Message
$boundary = "---"; //Delimitter
/* Headers */
$headers = "From: $from\nReply-To: $from\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";
$body = "--$boundary\n";
/* Text message */
$body .= "Content-type: text/html; charset='utf-8'\n";
$body .= "Content-Transfer-Encoding: quoted-printablenn";
$body .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode($filename)."?=\n\n";
$body .= $message."\n";
$body .= "--$boundary\n";
$file = fopen($filename, "r"); //Открываем файл
$text = fread($file, filesize($filename)); //Считываем весь файл
fclose($file); //Закрываем файл
/* ADD attach */
$body .= "Content-Type: application/octet-stream; name==?utf-8?B?".base64_encode($filename)."?=\n";
$body .= "Content-Transfer-Encoding: base64\n";
$body .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode($filename)."?=\n\n";
$body .= chunk_split(base64_encode($text))."\n";
$body .= "--".$boundary ."--\n";
mail($to, $subject, $body, $headers); //SEND
?>

contact form not sending to email cakephp

i'm new in php..i would like to sent contact form to my gmail account..
everything just going fine whrn i click the submit button,but my problem is this form not sending me the email..
this is my html code
<form action="kontact-sent" onSubmit="return validate_form(this)" method="post">
<table width="415" border="0" cellspacing="1" cellpadding="5" class="t1">
<tr>
<td align="left" valign="top" bgcolor="#efefef">First name:<br /><input name="FirstName" type="text" id="FirstName" style="width:300px;" /></td>
</tr>
<tr>
<td align="left" valign="top" bgcolor="#efefef">Email address<br /><input type="text" name="EmailAddress" id="EmailAddress" style="width:300px;" />
<input name="Email_Confirmation" class="Email_Confirmation2"/></td>
</tr>
<tr>
<td align="left" valign="top" bgcolor="#efefef">Message<br /><textarea name="Inquiry" id="Inquiry" style="width:300px; height:100px;"></textarea></td>
</tr>
<tr>
<td align="left" valign="top" bgcolor="#efefef"><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
function validate_EmailAddress(field,alerttxt){
with (field)
{
apos=value.indexOf("#");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(FirstName,"Please enter your First Name.")==false)
{FirstName.focus();return false;}
if (validate_EmailAddress(EmailAddress,"Please enter a valid Email Address.")==false)
{EmailAddress.focus();return false;}
if (validate_Inquiry(Inquiry,"Please enter your Inquiry.")==false)
{Inquiry.focus();return false;}
}
}
this is my .php
<?php
// if the Email_Confirmation field is empty
if(isset($_POST['Email_Confirmation']) && $_POST['Email_Confirmation'] == ''){
// put your email address here scott.langley.ngfa#statefarm.com, slangleys#yahoo.com
$youremail = 'afiqrashid91#gmail.com';
// prepare a "pretty" version of the message
$body .= "Thank You for contacting us! We will get back with you soon.";
$body .= "\r\n";
$body .= "\r\n";
foreach ($_POST as $Field=>$Value) {
$body .= "$Field: $Value\r\n";
$body .= "\r\n";
}
$CCUser = $_POST['EmailAddress'];
// Use the submitters email if they supplied one
// (and it isn't trying to hack your form).
// Otherwise send from your email address.
if( $_POST['EmailAddress'] && !preg_match( "/[\r\n]/", $_POST['EmailAddress']) ) {
$headers = "From: $_POST[EmailAddress]";
} else {
$headers = "From: $youremail";
}
// finally, send the message
mail($youremail, 'Form request', $body, $headers, $CCUser );
}
// otherwise, let the spammer think that they got their message through
?>
Thank You for contacting us! We will get back with you soon.
i hope that anyone can help me..thanks in advance..
$headers = "From: $_POST[EmailAddress]";
Should be:
$headers = "From: $_POST['EmailAddress']";
Also, email messages shouldn't exceed 70 characters per line. You'll want to fix this by adding:
$body = wordwrap($body, 70);

PHP contact form submitting but not receiving email

I realise this question has been asked numerous times before but everyone's code is obviously different and I am quite new to php so just looking to see if someone can give me some help.
I have created a basic contact form for a site but for some reason the information is not being sent to my email address although I believe that the form is submitted?
my PHP code is:
<?php
session_start();
//$to_mail = "architects#palavin.com,t.lavin#palavin.com,12yorkcourt#gmail.com";
$to_mail = "danny#enhance.ie";
//$cc="paul#enhance.ie";
$mail_sent = 0;
if(isset($_POST['submit'])){
//echo "the form was submitted";
$error= array();
$name = trim(strip_tags($_POST['name']));
if($name == "")
$error['name'] = 1;
$email = trim(strip_tags($_POST['email']));
if($email == "")
$error['email'] = 1;
$phone = trim(strip_tags($_POST['phone']));
$address = trim(strip_tags($_POST['address']));
$description = trim(strip_tags($_POST['description']));
$str = trim(strip_tags($_POST['secu']));
if ( isset($_SESSION['code_']) && $_SESSION['code_'] == strtoupper($str)){} else {$error['secu'] = 1;}
if(empty($error)){
$headers = 'From: "Euro Insulation" <no-reply#euroinsulations.ie>'."\r\n";
//$headers .= 'CC: "'.$cc.'" <'.$cc.'>'."\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "";
$subject = "New contact message";
$message = "New Contact message, received from: <br /> \n ";
$message .= "<b>Name</b> ".$name."<br /> \n";
$message .= "<b>Email</b> ".$email."<br /> \n";
$message .= "<b>Phone</b> ".$phone."<br /> \n";
$message .= "<b>Address</b> ".$address."<br /> \n";
$message .= "<b>Description</b> ".$description."<br /> \n";
if(#mail($to_mail,$subject,$message,$headers ))
{
echo "mail sent";
$mail_sent = 1;
}
else echo "mail not sent";
}
}
?>
my html form looks like this:
<table width="100%" border="0" cellspacing="0" cellpadding="10">
<tr>
<td width="65%" valign="top"><p class="header"><br>
Contact US <br>
</p>
<?php if($mail_sent==1){
print "Thank you for your message.";
} else { ?>
<form class="email_sub" method="post" >
<table width="77%" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td><label for="name" class="formtext" <?php if($error['name']==1) echo "style='color:red;'" ?> >Name:</label></td>
<td><input type="text" name="name" id="text" <?php if($name) echo "value='".$name."'" ?> /></td>
</tr>
<tr>
<td><label for="phone" class="formtext">Number:</label></td>
<td><input type="text" name="phone" id="phone"/><tr>
<br />
<tr>
<td><label for="email" class="textarea" <?php if($error['email']==1) echo "style='color:red;'" ?>>Email:</label></td>
<td><input type="text" name="email" id="email" <?php if($email) echo "value='".$email."'" ?> /></td>
</tr>
<tr>
<td><br /></td>
</tr>
<tr><td><label for="address" class="textarea">Address/Location of project:</label></td>
<td><textarea rows="3" cols="20" name="address" id="address" style="width: 400px;"><?php if($address!="") echo $address ?></textarea></td>
</tr>
<tr>
<td><br /></td>
</tr>
<br />
<tr>
<td><label for="description" class="fixedwidth">Enquiry</label></td>
<td><textarea rows="3" cols="20" name="description" id="description" style="width: 400px;"><?php if($description!="") echo $description; ?></textarea></td>
<tr>
<td><br /></td>
</tr>
<!-- form -->
<tr>
<td><label> </label></td>
<td><input type="submit" value="Submit" name="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Am i missing something obvious here?? Any help will really be appreciated thanks!
You have used sessions which is not required here, you can also use flag variable instead of arrays in this simple form, use this updated code.
<?php
//$to_mail = "architects#palavin.com,t.lavin#palavin.com,12yorkcourt#gmail.com";
$to_mail = "danny#enhance.ie";
//$cc="paul#enhance.ie";
$mail_sent = 0;
if(isset($_POST['submit'])){
//echo "the form was submitted";
$name = trim(strip_tags($_POST['name']));
if($name == "")
$error = true;
$email = trim(strip_tags($_POST['email']));
if($email == "")
$error = true;
$phone = trim(strip_tags($_POST['phone']));
$address = trim(strip_tags($_POST['address']));
$description = trim(strip_tags($_POST['description']));
if($error != true){
$headers = 'From: "Euro Insulation" <no-reply#euroinsulations.ie>'."\r\n";
//$headers .= 'CC: "'.$cc.'" <'.$cc.'>'."\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "";
$subject = "New contact message";
$message = "New Contact message, received from: <br /> \n ";
$message .= "<b>Name</b> ".$name."<br /> \n";
$message .= "<b>Email</b> ".$email."<br /> \n";
$message .= "<b>Phone</b> ".$phone."<br /> \n";
$message .= "<b>Address</b> ".$address."<br /> \n";
$message .= "<b>Description</b> ".$description."<br /> \n";
if(#mail($to_mail,$subject,$message,$headers))
{
echo "mail sent";
$mail_sent = 1;
}
else echo "mail not sent";
} else {
echo 'validation error';
}
}
?>
You have also missed out the else statement for your form validation test so no errors getting displayed when you submit form.
Remove the at sign from mail function and see what errors your get. #mail suppresses errors from being displayed.
Comment out the following line: if ( isset($SESSION['code']) && $SESSION['code'] == strtoupper($str)){} else {$error['secu'] = 1;}
You should be able to reach the mail function.

Categories