I have a php site. Here I have form to upload user's resume (must be in a word file), and mail this file and user information to the admin. I have used PHPmailer 5.2.0 mail function. How I will write the php mail function with this attached word file Please reply Thanks in advance
I make one demo for you.
Form
<form name="contactform" method="post" action="sendmail.php" enctype="multipart/form-data">
<table width="100%" border="0">
<tr>
<td id="ta">
<label for="title">Title *</label>
</td>
<td id="ta">
<select name="title">
<option value="0">Title</option>
<option value="1">Mr.</option>
<option value="2">Ms.</option>
<option value="3">Mrs.</option>
</select>
</td>
</tr>
<tr>
<td id="ta">
<label for="first_name">First Name *</label>
</td>
<td id="ta">
<input type="text" name="first_name" maxlength="50" size="30" required="required">
</td>
</tr>
<tr>
<td id="ta">
<label for="last_name">Last Name *</label>
</td>
<td id="ta">
<input type="text" name="last_name" maxlength="50" size="30" required="required">
</td>
</tr>
<tr>
<td id="ta">
<label for="email">Email Address *</label>
</td>
<td id="ta">
<input type="text" name="email" maxlength="80" size="30" required="required">
</td>
</tr>
<tr>
<td id="ta">
<label for="telephone">Telephone Number *</label>
</td>
<td id="ta">
<input type="text" name="telephone" maxlength="30" size="30" required="required">
</td>
</tr>
<tr>
<td id="ta">
<label for="comments">Details</label>
</td>
<td id="ta">
<textarea name="comments" maxlength="100000" cols="25" rows="6"></textarea>
</td>
</tr>
<tr>
<td id="ta">
<label for="file">Or upload a file (only word, excel or pdf)</label>
</td>
<td id="ta">
<input type="file" name="file">
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center" id="ta">
<input type="submit" value="Submit">
</td>
</tr>
</table>
</form>
Here is the sendmail.php file
<?php
require('PHPMailer/class.phpmailer.php');
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
//$email_to = "hidden";
//$email_subject = "Request for Portfolio check up from ".$first_name." ".$last_name;
$title = array('Title', 'Mr.', 'Ms.', 'Mrs.');
$selected_key = $_POST['title'];
$selected_val = $title[$_POST['title']];
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
if(($selected_key==0))
echo "<script> alert('Please enter your title')</script>";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message = "";
$email_message .="Title: ".$selected_val."\n";
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
$allowedExts = array("doc", "docx", "xls", "xlsx", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword")
|| ($_FILES["file"]["type"] == "application/excel")
|| ($_FILES["file"]["type"] == "application/vnd.ms-excel")
|| ($_FILES["file"]["type"] == "application/x-excel")
|| ($_FILES["file"]["type"] == "application/x-msexcel")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "<script>alert('Error: " . $_FILES["file"]["error"]."')</script>";
}
else
{
$d='upload/';
$de=$d . basename($_FILES['file']['name']);
move_uploaded_file($_FILES["file"]["tmp_name"], $de);
$fileName = $_FILES['file']['name'];
$filePath = $_FILES['file']['tmp_name'];
//add only if the file is an upload
}
}
else
{
echo "<script>alert('Invalid file')</script>";
}
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->IsSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "hidden";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "hidden";
//Password to use for SMTP authentication
$mail->Password = "hidden";
//Set who the message is to be sent from
$mail->SetFrom($email_from, $first_name.' '.$last_name);
//Set an alternative reply-to address
//$mail->AddReplyTo('replyto#example.com','First Last');
//Set who the message is to be sent to
$mail->AddAddress('hidden', 'hidden');
//Set the subject line
$mail->Subject = 'Request for Profile Check up';
//Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body
$mail->body($email_message);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->AddAttachment($file);
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
//Send the message, check for errors
if(!$mail->Send()) {
echo "<script>alert('Mailer Error: " . $mail->ErrorInfo."')</script>";
} else {
echo "<script>alert('Your request has been submitted. We will contact you soon.')</script>";
Header('Location: main.php');
}
}
?>
**You need Phpmailer library in you root folder**
Related
I have a problem with my contact form
Filling in the form is OK etc, but when I send the message, I only receive the telephone nr.
This is PHP code from sendmail.
<?php
if (isset($_POST["submit"])) {
// Checking For Blank Fields..
if ($_POST["name"] == "" || $_POST["email"] == "" || $_POST["tel"] == "") {
echo "Fill All Fields..";
} else {
// Check if the "Sender's Email" input field is filled out
$email = $_POST['email'];
// Sanitize E-mail Address
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email) {
echo "Invalid Sender's Email";
} else {
$subject = 'neuen Kontakt';
$message = $_POST['name'];
$message = $_POST['email'];
$message = $_POST['tel'];
$headers = 'From:' . $email2 . "\r\n"; // Sender's Email
$headers .= 'Cc:' . $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
//$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("mymail#gmail.com", $subject, $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
}
}
?>
and this is the html form
<form action="index.php" method="post" name="contactus" id="contactus" onsubmit="return ValidateForm();">
<table width="260" border="0" cellspacing="0" cellpadding="0" align="center" style="color:#FFF">
<tr>
<td height="25px" style="font-family:Arial; font-size:13px; color:#575757; padding:0 0 0 10px;">Name<span style="color:#F00">*</span>
</td>
</tr>
<tr>
<td style="padding:0 0 0 10px;">
<input name="name" type="text" class="input" id="name" onFocus="inputFocus(this)" onBlur="inputBlur(this)" value="" />
</td>
</tr>
<tr>
<td height="27px" style="font-family:Arial; font-size:13px; color:#575757; padding:0 0 0 10px;">Telefonnummer<span style="color:#F00">*</span>
</td>
</tr>
<tr>
<td class="td_style1">
<input name="tel" type="text" class="input" id="email" onFocus="inputFocus(this)" onBlur="inputBlur(this)" value="" />
</td>
</tr>
<tr>
<td height="25px" style="font-family:Arial; font-size:13px; color:#575757; padding:0 0 0 10px;">E-mail<span style="color:#F00">*</span>
</td>
</tr>
<tr>
<td style="padding:0 0 0 10px;">
<input name="email" type="text" class="input" id="email" onFocus="inputFocus(this)" onBlur="inputBlur(this)" value="email#gmail.com" />
</td>
</tr>
<tr>
<td style="padding:10px 28px 0 0;" align="right">
<input name="submit" type="submit" value="SUBMIT" class="submit" />
</td>
</tr>
<tr>
<td height="20px" style="font-family:Arial; font-size:11px; color:#575757; padding:3px 27px 0 0px; float:right;"><span style="color:#F00">*</span> sind Pflichtfelder</td>
</tr>
</table>
You overwrite the $message with each field so you will get only the last one (tel). You need to concatenate all the fields using . like this:
$message = $_POST['name'] . ", ";
$message .= $_POST['email'] . ", " ;
$message .= $_POST['tel'];
Or you can do in one line like this:
$message = $_POST['name'] . ", " . $_POST['email'] . ", " . $_POST['tel'];
Also you can add a comma or something like that between the fields so will not be glued together.
You are replacing value of $message everytime with new value , and at end it is assigned to telephone so u only recieve telephone no
Replace
$message = $_POST['name'];
$message = $_POST['email'];
$message = $_POST['tel'];
With
$message =$_POST['name'];
$message =$message.$_POST['email'];
$message =$message.$_POST['tel'];
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I have a contact us form using a HTML file and a PHP file (sendeamil.php) that is compose by (header.html, footer.html and contentsendemail.php where is my code to send the information to my email.
I have my HTML file with the form:
<form name="htmlform" method="post" action="sendemail.php">
<table width="450px">
</tr>
<tr>
<td valign="top">
<label for="first_name">First Name *</label>
</td>
<td valign="top">
<input type="text" name="first_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top"">
<label for="last_name">Last Name *</label>
</td>
<td valign="top">
<input type="text" name="last_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="email">Email Address *</label>
</td>
<td valign="top">
<input type="text" name="email" maxlength="80" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone">Telephone Number</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="comments">Comments *</label>
</td>
<td valign="top">
<textarea name="comments" maxlength="1000" cols="25" rows="6"> </textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Submit"> ( HTML Form )
</td>
</tr>
</table>
</form>
Then I have my sendemail.php file which is compose by the Header, content and Footer:
<?php
include("templates/header.html");
$action = 'contentsendemail';
$disallowed_paths = array('header', 'footer');
if (!empty($_GET['action'])) {
$tmp_action = basename($_GET['action']);
if (!in_array($tmp_action, $disallowed_paths) && file_exists("templates/{$tmp_action}.php"))
$action = $tmp_action;
}
include("templates/$action.php");
include("templates/footer.html");
?>
And the my contentsendemail.php file:
<?php
if(isset($_POST['email'])) {
// CHANGE THE TWO LINES BELOW
$email_to = "myemail#gmail.com";
$email_subject = "Subject Here";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
Thank you for contacting us.
<?php
}
die();
?>
I have 2 questions or issues:
I'm not getting any email. Is anything I need to do in the server or somewhere to have the emails sent? why I'm not getting the emails?
when I click submit in the contactus.php site and I get the message "Thank you for contacting us." in the sendemail.php I get both the header.html and contentsendemail.php included but not the footer.html.
I have two answers to your two issues which both reside in contentsendemail.php
#mail() does not exist in core PHP (and I'm not even sure its a valid function name), you want mail().
die(); kills the execution of the script at that point, and nothing else is parsed/returned after that line which is executed before the inclusion of the footer.
i have created a form and it doesnt send out emails. I contacted my host and he said I need SMTP authentication. Form needs to send reservation info.
Here is my reservation.php file:
<script>
/////////////////// RESERVATION FORM //////////////////////
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
document.getElementById('submit').disabled=true;
document.getElementById('submit').value='PLEASE WAIT';
$.ajax({
type: "POST",
url: "apartments_reservation_send.php",
data: str,
success: function(msg){
$("#note").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
result = '<div class="notification_ok">Thank you!<br />Your request is successfully sent!</div>';
$("#fields").hide();
}
else
{
document.getElementById('submit').disabled=false;
document.getElementById('submit').value='Send request';
result = msg;
autoReinitialise: true;
}
$(this).html(result);
});
}
});
return false;
});
</script>
<form id="ajax-contact-form" action="javascript:alert('success!');">
<table width="100%" cellpadding="3" cellspacing="3">
<tr>
<td width="50%" align="right" style="text-align: right;">
Arrival Date<span class="REQ">*</span> → <input id="arrivalDate" name="arrivalDate" size="30" type="text" class="date-pick" />
</td>
<td width="50%" align="left" style="text-align: left;">
<input id="departureDate" name="departureDate" size="30" type="text" class="date-pick" />
← <span class="REQ">*</span>Departure Date
</td>
</tr>
<tr>
<td width="50%" align="right" style="text-align: right;">
Adults<span class="REQ">*</span> →
<select id="Adults" name="Adults">
<option value=""></option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td width="50%" align="left" style="text-align: left;">
<select id="Children" name="Children">
<option value=""></option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
← <span class="REQ">*</span>Children
</td>
</tr>
</table>
<table width="100%" cellpadding="3" cellspacing="3">
<tr>
<td width="25%" align="right" valign="middle" style="text-align: right;">Name<span class="REQ">*</span> :</td>
<td width="75%" align="left" style="text-align: left;">
<input type="text" id="name" name="name" value="" size="86" />
</td>
</tr>
<tr>
<td align="right" valign="middle" style="text-align: right;">E-mail<span class="REQ">*</span> :</td>
<td align="left" style="text-align: left;">
<input type="text" id="email" name="email" value="" size="86" />
</td>
</tr>
<tr>
<td align="right" valign="middle" style="text-align: right;">Phone<span class="REQ">*</span> :</td>
<td align="left" style="text-align: left;">
<input type="text" id="phone" name="phone" value="" size="86" />
</td>
</tr>
<tr>
<td align="right" style="text-align: right;">Message :</td>
<td align="left" valign="top" style="text-align: left;">
<textarea id="message" name="message" rows="5" cols="87"></textarea>
</td>
</tr>
<tr>
<td width="100%" align="center" style="text-align: center;" colspan="2">
<input class="button" type="submit" name="submit" id="submit" value="Send request" />
</td>
</tr>
</table>
</form>
and here is my reservarion_send.php:
<?php
$TO_EMAIL = "info#thebunchofgrapesinn.com";
$FROM_EMAIL = "info#thebunchofgrapesinn.com";
$FROM_NAME = "thebunchofgrapes.com";
$SUBJECT = "The Bunch Og Grapes - Apartment Reservation";
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'functions.php';
$ARIVAL_DATE = trim($_POST['arrivalDate']);
$DEPARTURE_DATE = trim($_POST['departureDate']);
$ADULTS = trim($_POST['Adults']);
$CHILDREN = trim($_POST['Children']);
$EMAIL = trim($_POST['email']);
$PHONE = trim($_POST['phone']);
$NAME = stripslashes($_POST['name']);
$MESSAGE = stripslashes($_POST['message']);
$ERROR = '';
if(!$ARIVAL_DATE)
{
$ERROR .= 'Please enter Arrival Date<br />';
}
if(!$DEPARTURE_DATE)
{
$ERROR .= 'Please enter Departure Date<br />';
}
//if(!$ADULTS)
//{
//$ERROR .= 'Please pick number of Adults<br />';
//}
//if(!$CHILDREN)
//{
//$ERROR .= 'Please pick number of Children<br />';
//}
if(!$NAME)
{
$ERROR .= 'Please enter Your Name.<br />';
}
if(!$EMAIL)
{
$ERROR .= 'Please enter Email address.<br />';
}
if($EMAIL && !ValidateEmail($EMAIL))
{
$ERROR .= 'Please enter valid Email address.<br />';
}
if(!$PHONE)
{
$ERROR .= 'Please enter You Phone Number.<br />';
}
//if(!$MESSAGE || strlen($MESSAGE) < 15) {
//$ERROR .= "Molimo unesite poruku. <br />Poruka mora imati najmanje 15 karaktera.<br />";
//}
$FULL_MESSAGE = "ARIVAL DATE = $ARIVAL_DATE\nDEPARTURE DATE = $DEPARTURE_DATE\nADULTS = $ADULTS\nCHILDREN = $CHILDREN\nNAME = $NAME\nEMAIL = $EMAIL\nPHONE = $PHONE\nMESSAGE = $MESSAGE";
if(!$ERROR)
{
$mail = mail($TO_EMAIL, $SUBJECT, $FULL_MESSAGE,
"From: ".$FROM_NAME." <".$FROM_EMAIL.">\r\n"
."Reply-To: ".$FROM_EMAIL."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail) {
echo 'OK';
}
}
else {
echo '<div class="notification_error">'.$ERROR.'</div>';
}
}
?>
and here is the link of the webpage http://thebunchofgrapesinn.com/apartments_reservation
I am not sure how to add SMTP authentication and what is wrong here, can someone help?
The behavior of php's mail() function varies depending on the server OS. Windows doesn't have a built in non-SMTP option like Unix-based servers. mail() is also limited in general without some advanced knowledge of working with headers.
If it's not inappropriate here to recommend a tool for the job, PHPMailer is a convenient enough goto solution for sending email from php. If your server is Unix/Linux based, you can leave out $mail->isSMTP() and the related options and PHPMailer will use the server's sendmail implementation. If you are on Windows or have SMTP details handy, PHPMailer makes that simple enough.
You can use PHPMailer and Swiftmailer, these are common libraries for sending smtp mails. PhpMailer is a little simpler than swift and documentations is easy to understand.
But you can write your own smtp client for this but first you need to learn how to make a socket connection in php. PHPMailers smtp class is a good hint to create one.
If you have administrator rights for your server, you can connect your sendmail mail function to a smtp server, here is a documantation how to. Php has a mail configuration option for smtp though i never used it before.
By the way, php.ini has a sendmail_path option to read your STDOUT data and send mail. If you want, you can change this sendmail_path param with a bash, php, or a python script. But i do not recommend it.
Most of the host have SMTP already configured.In order to debug test mail() function seperately.Just make a file like 'mail.php' and put the below code in to it :
<?php
$email ="PUT EMAIL ID OF USER HERE";
$subject ="Reservation Info";
$headers = "From: " . '<thebunchofgrapesinn.com/>' . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html>
<body>
<p>Its Just A Testing Mail</p>
</body>
</html>";
if(mail($email,$subject, $message, $headers)){
echo 'mail sent';
}
?>
Check weather it works or not.Also prefer to use phpmailer.Here is the link for downloding PHPmailer class it also has example.
I have an HTML form that submits to a PHP file to process and send out emails via PHP mailer.
I have searched and probably spent over a days work reading through possible solutions (tried singleto, starting new mailers, clearing recipients, checking for inappropriate plugins that would cause double submission [such as yslow for firefox] made sure that double submission was not happening, changing formatting to UTF-8 in the PHPmailer and some others.)
After all that I broke my code into bits and tested it bit by bit and found that it was when I stated to make XML files was when the PHP mailer decides to resend the email. (within a second or less).
Any help at all would be greatly appreciated!!
Here is my code (before XML) just switch it around to have your gmail password:
<?php
require 'PHPMailer-master/PHPMailerAutoload.php';
if(isset($_POST['contract_number'])) {
// Who to send email to and subject
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
// TEST EMAIL FIELDS //
$base_recipients = array('test#gmail.com');
$pre_30_cancel_recipients = array('test1#gmail.com');
$not_aa1014_recipients = array('test2#gmail.com');
$aa1014_recipients = array('test3#gmail.com');
// TEST EMAIL FIELDS //
// $base_recipients = array('test5#gmail.com', 'test6#gmail.com', 'test7#gmail.com');
// $pre_30_cancel_recipients = array('test8#gmail.com');
// $not_aa1014_recipients = array('test9#gmail.com');
// $aa1014_recipients = array('test10#gmail.com');
$agent = $_POST['agent'];
$contract_number = $_POST['contract_number'];
$comments = $_POST['comments'];
$affiliate = $_POST['affiliate'];
$email_subject = $_POST['comments'];
$email_message = "Form details below.\n\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
$mailer = new PHPMailer;
$mailer->isSMTP();
$mailer->Host = 'smtp.gmail.com';
$mailer->Port = 587;
$mailer->Username = $agent.'#gmail.com';
$mailer->Password = 'Password';
$mailer->SMTPSecure = 'tls';
$mailer->SMTPAuth = true;
$mailer->From = $agent.'#gmail.com';
$mailer->FromName = $agent;
$final_recipients = array_merge($base_recipients);
if ($affiliate == '(AA1014)') {
$final_recipients = array_merge($final_recipients,$aa1014_recipients);
}
if ($affiliate == '(AA1008)') {
$final_recipients = array_merge($final_recipients,$not_aa1014_recipients);
}
if ($affiliate == '(AA1012)') {
$final_recipients = array_merge($final_recipients,$not_aa1014_recipients);
} else {
$final_recipients = array_merge($final_recipients);
}
foreach ($final_recipients as $rcp) {
echo("Adding ".$rcp." to recipient list.<br />\n");
$mailer->addAddress($rcp);
}
$mailer->Subject = $email_subject;
$mailer->Body = $email_message;
$mailer->isHTML(false);
if(!$mailer->send()) {
echo 'Message could not be sent to Ops. Go back and fix these errors then resubmit.';
echo 'Mailer Error: ' . $mailer->ErrorInfo;
exit;
}
}
?>
HTML:
<form name="contactform" method="post" action="phpseg1.php">
<table width="600px">
<tr>
<td valign="top">
<label for="agent">Agent</label>
</td>
<td valign="top">
<input type="text" name="agent" maxlength="30" size="35">
</td>
</tr>
<tr>
<td valign="top">
<label for="affiliate">Affiliate </label>
</td>
<td valign="top">
<select name="affiliate">
<option value=""></option>
<option value="CORP">CORP</option>
<option value="(AA1008)">(AA1008)</option>
<option value="(AA1012)">(AA1012)</option>
<option value="(AA1014)">(AA1014)</option>
</select>
</td>
</tr>
<tr>
<td valign="top">
<label for="contract_number">Contract Number</label>
</td>
<td valign="top">
<input type="text" name="contract_number" maxlength="30" size="26">
</td>
</tr>
<tr>
<td valign="top">
<label for="comments">Comments </label>
</td>
<td valign="bottom">
<textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Submit">
</td>
</tr>
</tr>
</table>
</form>
<!-- include your own success html here -->
Email sent!
By adding the following before the last curly brace the mailer will send 2 emails (For the test sake make sure you are always selecting "Corp" as affiliate because if you select another then it should send two emails.):
if ($mailer->send()) {
$str = '<?xml version="1.0" encoding="UTF-8"?><entrys></entrys>';
$final_recipients = implode (',', $final_recipients);
$xml = simplexml_load_string($str);
$whensent = date("Y-m-d H:i:s");
$whoto = $final_recipients;
$subject = $email_subject;
$xml->reports = "";
$xml->reports->addChild('whensent', $whensent);
$xml->reports->addChild('whoto', $whoto);
$xml->reports->addChild('subject', $subject);
$xml->reports->addChild('emailmessage', $email_message);
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
$doc->loadXML($xml->asXML(), LIBXML_NOBLANKS);
$path = "Test_Email_notices_sent/NO_NOTICE/NO_NOTICE";
$doc->save("{$path}_test.xml");
}
if(!$mailer->send()) {
echo 'Message could not be sent to Ops. Go back and fix these errors then resubmit.';
echo 'Mailer Error: ' . $mailer->ErrorInfo;
exit;
}else{
//PUT ALL THE file creation code here
}
PLAN B
if(!$mailer->send()) {
echo 'Message could not be sent to Ops. Go back and fix these errors then resubmit.';
echo 'Mailer Error: ' . $mailer->ErrorInfo;
exit;
}else{
$sent=TRUE;
}
then change the
if ($mailer->send()) {
to
if($sent){
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";
}
?>