inserting HTML POST form field data into PHPmailer email body - php

I have tried every hint I have found across the web and here but what I cannot achieve is for the sent email to contain the form data in the html formatted message. The mailing function is working and I get the email properly.
The form is basically:
<form method="post" action="test.php" name="Work Record" autocomplete="off">
<input type="text" name="first_name" id="staff_name2" placeholder="First" required />
<input type="text" name="last_name" id="staff_name" placeholder="Last" required />
<input name="checkbox" type="checkbox" class="head-l" id="checkbox" onChange="this.form.submit()">
And using the latest phpmailer from google the action script is as follows. I have the emailing function working through gmail, I am just not sure what to put where to pull the data from the form and put it into the email body. The code that is pasted in the body now is that we used to use before switching to phpmailer. Thank you!
<?php
require '/home/newnplhftp/nplh.us/smtp/phpmailer/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxxxxxxxxxxxxxx'; // SMTP username
$mail->Password = 'xxxxxxxxx'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->From = 'xxxxxxxxxxxxxx';
$mail->FromName = 'NPLH';
$mail->AddAddress('xxxxxxxxxxxxxxxxxxxxx'); // Name is optional
$mail->AddCC('');
$mail->AddBCC('');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'xxxxxxxxxxxxxxx';
$mail->Body = '
<html>
<h2><b>$first_name $last_name, $license_type</b></h2>
</html>';
$mail->AltBody = '';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Thank you, your message has been sent!';
?>

Please set;
$mail->Body = '
<html>
<h2><b>$first_name $last_name, $license_type</b></h2>
</html>';
to
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$license_type = $_POST['license_type'];
$mail->Body = "
<html>
<h2><b>".$first_name." ".$last_name.", ".$license_type."</b></h2>
</html>";

The variables you are trying to send need to be captured from the the form first. This would happen on test.php since this is where you are posting the values to.
So you would do this
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$license_type = $_POST['license_type'];
Then you can use them inside the mail body.
$mail->Body = "<html><h2><b>$first_name $last_name, $license_type</b></h2></html>";
Though I would highly suggest validating that data in some way first.

Related

PHP mail function won't send mail to the desired email_id

I have following piece of code. It returns message "send successfully " but we won't receive email at given gmail, Is this code right or have I missed something?
<?php
require("mailer/PHPMailerAutoload.php");
require("mailer/class.smtp.php");
require("mailer/class.phpmailer.php");
$name=$_POST['Your_Name'];
$email=$_POST['Your_Email'];
$message=$_POST['Your_Msg'];
echo $name ;
$mail = new PHPMailer();
// set mailer to use SMTP
//$mail->IsSMTP();
// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "smtp.gmail.com"; // specify main and backup server
$mail->Port = "465";
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "mandarpatil0003#gmail.com"; // SMTP username
$mail->Password = "Con#Soumitra1"; // SMTP password
// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
$mail->From = $email;
// below we want to set the email address we will be sending our email to.
$mail->AddAddress("mandarpatil0003#gmail.com", "Mandar");
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "You have received feedback from your website!";
// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body = $message;
$mail->AltBody ="Name : {$name}\n\nEmail : {$email}\n\nMessage : {$message}";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
else
{
echo "Thank you for contacting us. We will be in touch with you very soon.";
}
?>
Does this code have any problems or do I have to try a different approach?
<?php
include 'library.php'; // include the library file
include "classes/class.phpmailer.php"; // include the class name
include "classes/class.smtp.php";
if(isset($_POST["send"])){
$email = $_POST["email"];
$mail = new PHPMailer; // call the class
$mail->IsSMTP();
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com"; //Hostname of the mail server
$mail->Port = 465; //Port of the SMTP like to be 25, 80, 465 or 587
$mail->SMTPDebug = 1;
//$mail->SMTPAuth = false; //Whether to use SMTP authentication
$mail->Username = "****#gmail.com"; //Username for SMTP authentication any valid email created in your domain
$mail->Password = "****"; //Password for SMTP authentication
$mail->AddReplyTo("****#gmail.com", "Reply name"); //reply-to address
$mail->SetFrom("****#gmail.com", "Your Name"); //From address of the mail
// put your while loop here like below,
$mail->Subject = "Your SMTP Mail"; //Subject od your mail
$mail->AddAddress($email, "Asif18"); //To address who will receive this email
$mail->MsgHTML("<b>Hi, your first SMTP mail has been received."); //Put your body of the message you can place html code here
//Attach a file here if any or comment this line,
$send = $mail->Send(); //Send the mails
if($send){
echo '<center><h3 style="color:#009933;">Mail sent successfully</h3></center>';
}
else{
echo '<center><h3 style="color:#FF3300;">Mail error: </h3></center>'.$mail->ErrorInfo;
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Send mails using SMTP and PHP in PHP Mailer using our own server or gmail server by Asif18</title>
<meta name="keywords" content="send mails using smpt in php, php mailer for send emails in smtp, use gmail for smtp in php, gmail smtp server name"/>
<meta name="description" content="Send mails using SMTP and PHP in PHP Mailer using our own server or gmail server"/>
<style>
.as_wrapper{
font-family:Arial;
color:#333;
font-size:14px;
}
.mytable{
padding:20px;
border:2px dashed #17A3F7;
width:100%;
}
</style>
<body>
<div class="as_wrapper">
<h1>Send mails using SMTP and PHP in PHP Mailer using our own server or gmail server</h1>
<form action="" method="post">
<table class="mytable">
<tr>
<td><input type="email" placeholder="Email" name="email" /></td>
</tr>
<tr>
<td><input type="submit" name="send" value="Send via SMTP" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>

attachment is not sent with phpmailer

I'm trying to send an attachment with the phpMailer script.
Everything is working correctly since my email is sent correctly, however I do have a problem with an attachment that is not sent.
HTML part:
<p>
<label>Attachment :</label>
<input name="doc" type="file">
</p>
PHP:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = '*****';
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->Username = '*****';
$mail->Password = '*****';
$mail->SMTPSecure = 'ssl';
$mail->From = $_POST["name"];
$mail->FromName = 'Your Name';
$mail->Subject = 'Message Subject';
$mail->addAddress('*****');
$mail->addAttachment($_FILES["doc"]);
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = "You got a new message from your website :
Name: $_POST[name]
Company: $_POST[company]
Phone: $_POST[phone]
Email: $_POST[email]
Message: $_POST[message]";
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<p> <img src="img/correct.png" alt="icon" style=" margin-right: 10px;">Thank you! We will get back to you soon.</p>
</body>
</html>
Try:
if (isset($_FILES['doc']) &&
$_FILES['doc']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['doc']['tmp_name'],
$_FILES['doc']['name']);
}
Basic example can also be found [here](https://code.google.com/a/apache-extras.org/p/phpmailer/wiki/AdvancedMail).
The function definition for `AddAttachment` is:
public function AddAttachment($path,
$name = '',
$encoding = 'base64',
$type = 'application/octet-stream')
Please have a look about how PHP file uploads work. This array key:
$_FILES["doc"]
... will never contain a file. At most, it'll contain an array with information about where to find the file.
Untested solution, but should work:
change
$mail->addAttachment($_FILES["doc"]);
to
$mail->addAttachment($_FILES["doc"]["tmp_name"], $_FILES["doc"]["name"], "base64", $_FILES["doc"]["tmp_type"]);
However, please consider learning php upload file handling as already commented by others. Don't use user input without validation. Never!

Send email with attachment via PHPMailer

I'm preparing to create a form page for a website that will require many fields for the user to fill out and that will be sent to a specified email.
So far I've created a dummy php email page that gets your Message, 1 attachment, and Recipient Email address using Google's SMTP.
Here's my code for uploadtest.html:
<body>
<h1>Test Upload</h1>
<form action="email.php" method="get">
Message: <input type="text" name="message">
Email: <input type="text" name="email"><br>
Attach File: <input type="file" name="file" id="file">
<input type="submit">
</form>
</body>
uploadtest.html is what the user will see
Here's the code for email.php:
<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$recipiant = $_GET["email"];
$message = $_GET["message"];
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // SMTP authentication
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Port = 465; // SMTP Port
$mail->SMTPSecure = 'ssl';
$mail->Username = "xxxxx#gmail.com"; // SMTP account username
$mail->Password = "xxxxxxxx"; // SMTP account password
$mail->AddAttachment($_FILES['tmp_name']); //****HERE'S MY MAIN PROBLEM!!!
$mail->SetFrom('cinicraftmatt#gmail.com', 'CiniCraft.com'); // FROM
$mail->AddReplyTo('cinicraftmatt#gmail.com', 'Dom'); // Reply TO
$mail->AddAddress($recipiant, 'Dominik Andrzejczuk'); // recipient email
$mail->Subject = "First SMTP Message"; // email subject
$mail->Body = $message;
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
?>
So from what I can tell here, PHPMailer's AddAttachment() method takes as a parameter the URL of the file DIRECTORY you want attached. And this is where my main problem is.
What would the name of the variable be that would get the location of my file (dir/upload.jpg) that I've uploaded so I could use it as a parameter in the AddAttachment() method?
No, it doesn't take URLs, or directories. It takes a direct path to a FILE.
e.g.
$mailer->AddAttachment(
'/path/to/file/on/your/server.txt',
'name_of_file_in_email',
'base64',
'mime/type'
);
The path is self-explanatory. The name_of_file_in_email allows you to "rename" the file, so that you might loaded a file named "foo.exe" on your server, it can appear as "bar.jpg" in the email the client receives.
Your problem is that you're trying to attach an uploaded file, but using the wrong source. It should be
<input type="file" name="thefile" />
^^^^^^^
$_FILES['thefile']['tmp_name']
^^^^^^^
Note the field name relationship to $_FILES.
This will be send like this through PHPMailer Class
$mail->AddAttachment($_FILES['tmp_name'],$_FILES['name']); //****HERE'S MY MAIN PROBLEM!!! So you would have to give file name also.
please try with this
include "phpMailerClass.php";
$email = new PHPMailer();
$email->From = $to;
$email->FromName = $_POST['name'];
$email->Subject = $subject;
$email->Body = $EmailText;
$email->AddAddress( 'shafiq2626#hotmail.com' );
$email->IsHTML(true);
$file_to_attach = $_FILES['file']['tmp_name'];
$filename=$_FILES['file']['name'];
$email->AddAttachment( $file_to_attach , $filename );
$email->Send();
This is code is working fine.
Your <form> tag should specify the enctype attribute like so :
<form ... enctype="multipart/form-data">
...
</form>
Use the following code:
$objectMailers->AddAttachment("file.extension");
tested on PHP 7 and using PHPMailer 5.3

reply to email not populating corerectly

when I hit the reply button I want to be able to reply to the user that sent the email using the $email NOT the email I used to send the form (someone#gmail.com). the name is correct just not the email
http://oi50.tinypic.com/1z3auc0.jpg
now i thought that these bits of code should work but they are not! what am I doing wrong?
$mail->From = $email;
$mail->FromName = $name;
$mail->SetFrom($email, $name);
here is the mailer in full.
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->Host = 'smtp.gmail.com'; // Specify main and backup server
$mail->Port = 465; // specify port
$mail->Username = 'someone#gmail.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->WordWrap = 50; // Set word wrap to 50
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'Quick Comment';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
// gets info from form
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$phone = $_POST['phone'] ;
$message = $_POST['message'] ;
// defines how message looks in email
$mail->Body="
Name: $name<br>
Telephone: $phone<br>
Email: $email<br>
-------------------<br>
Message:<br>
$message";
// makes email reply to user
$mail->From = $email;
$mail->FromName = $name;
$mail->SetFrom($email, $name);
$mail->AddAddress('someone#gmail.com'); // send to
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
?>
I think this post will be usefull for you:
phpmailer: Reply using only "Reply To" address
I think the AddReplyTo() function is the function you need.
Something like $mail->AddReplyTo('example#example.com', 'Reply to name');
Most mail servers will not allow you to lie in the "From" header. This is a good thing, because spam filters react to lying. They either force your mail address into the "From" header no matter what you do, or will reject sending it out, or other crazy stuff.
The "Reply-to" header seems to be correctly set in your screen shot. And it is the only header that is valid for making the reply to an email go to a different address than the one it was originally sent from.

PHP Mailer shows no errors but doesn't send the email

I'm creating a booking form as a favour but have decided to send mail via the domain, not the server. This is mainly for better security and less limits in responses and data transfers.
I've been working on this for the last few days and trying to teach myself how to get it to work. I now have a very simple working example which can be seen here below.
This is the simple booking form:
<form method="post" name="process.php" action="process.php">
<p>Name:</p><br><input type="text" name="name"><br><br>
<p>Email Address:</p><br><input type="email" name="email"><br><br>
<br>
<input type="submit" name="submit" value="Send Email">
Then in process.php I have this working code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['submit']))
{
// Values need to be santiised
$name = $_POST['name']; //Name of the person requesting a booking
$email = $_POST['email']; //Email of the person requesting a booking
require '../vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'test#handler.net';
$mail->Password = '[PASSWORD]';
$mail->setFrom('test#handler.net'); // All emails would be sent from the handler.net domain to the bookings email of the other domain. (Using test to test, will be noreply)
$mail->addAddress('bookings#salon.com'); // Recipient of the email should be the bookings address, this won't change.
$mail->addReplyTo($email); // The reply to address will be the email address of the user who submitted the booking enquiry.
$mail->addBCC('outbox#handler.net'); // This is to keep a record of all emails that have been sent. Responses will also be saved to a CSV file.
$mail->Subject = 'Booking Request'; // Subject of the email sent to bookings#salon.com that the form responses will be contained within.
$mail->isHTML(TRUE);
$mail->Body = 'Booking request from '.$name.' with email '.$email; // Shows the salon the form response via the email and when they reply a new thread should start in order to compose a new email to reply to the email of the form submitter.
if(!$mail->send()) { // Send the email.
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
}
?>
The code above works and sends the emails from the right address, to the right address. That was on a site in public_html/testing and has been moved to a different site in public_html/booking so the relative paths will be the same. The only files within this directory are index.php (the form) and send.php (the process file with confirmation message)
For some reason this new code with all of the form values will not send. I'm honestly not too sure as to why it won't work now so any pointers at all would be massively appreciated.
<?php
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['submit']))
{
// Values need to be santiised
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$service = $_POST['service'];
$date = $_POST['date'];
$time = $_POST['time'];
require '../vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'noreply#handler.net';
$mail->Password = '[PASSWORD]';
$mail->setFrom('Handler | Bookings'); // Emails sent via Noreply.
$mail->addAddress('bookings#salon.com'); // Email form responses sent to bookings#salon.com
$mail->addReplyTo($email); // Reply to the user who submitted the form.
$mail->addBCC('outbox#handler.net'); // Store record of all emails sent via the system.
$mail->Subject = 'Booking Request'; // Subject of the email sent to bookings#salon.com that the form responses will be contained within.
$mail->isHTML(TRUE);
$mail->Body = '
Booking request from '.$forename.' with email '.$email;'
Test Values: $forename $surname $email $phone $service $date $time
if(!$mail->send()) { // Send the email.
echo '';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo '';
}
}
?>
I don't need the echo statements at the end, I just need the email to send following this sort of format:
<img src="https://via.placeholder.com/300x150" width="15%">
<p><b>Name:</b> $forename $surname</p>
<p><b>Email:</b> $email</p>
<p><b>Phone:</b> $phone</p>
<p><b>Service:</b> $service</p>
<p><b>Date:</b> $date</p>
<p><b>Time:</b> $time</p>
I'm just not sure why the emails now will not send when they have done before. Any pointers would be appreciated.
UPDATE
Here's the updated code with the progress made with thanks to Mr Perfect
<?php
mail("bookings#salon.com", "test", "message");
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['submit']))
{
// Values need to be santiised
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$service = $_POST['service'];
$date = $_POST['date'];
$time = $_POST['time'];
$message = <<<DELIMETER
<img src="https://via.placeholder.com/300x150" width="15%">
<p><b>Name:</b> {$forename} {$surname}</p>
<p><b>Email:</b> {$email}</p>
<p><b>Phone:</b> {$phone}</p>
<p><b>Service:</b> {$service}</p>
<p><b>Date:</b> {$date}</p>
<p><b>Time:</b> {$time}</p>
DELIMETER;
require '../vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 3;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'noreply#handler.com';
$mail->Password = '[PASSWORD]';
$mail->setFrom('Handler | Bookings'); // Emails sent via Noreply.
$mail->addAddress('bookings#salon.com','ADMIN'); // Email form responses sent to bookings#salon.com.
$mail->addReplyTo($email); // Reply to the user who submitted the form.
// $mail->addBCC('outbox#handler.net'); // Store record of all emails sent via the system.
$mail->Subject = 'Booking Request | SUBMISSION'; // Subject of the email sent to bookings#salon.com that the form responses will be contained within.
$mail->isHTML(TRUE);
$mail->Body = $message;
$mail->AltBody = $message;
if(!$mail->send()) { // Send the email.
echo '';
echo '' . $mail->ErrorInfo; // I don't need to echo any errors because the submission page has the text above already.
} else {
echo '';
}
}
?>
You should look at your $mail->addAdress, $mail->addBCC and $mail->addReplyTo fields and follow the correct syntax for those fields.
Test the code below.
<?php
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['submit']))
{
// Values need to be santiised
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$service = $_POST['service'];
$date = $_POST['date'];
$time = $_POST['time'];
require '../vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'test#handler.net';
$mail->Password = '[PASSWORD]';
$mail->setFrom('test#handler.net','Bookings'); // Emails sent via Noreply.
$mail->addAddress('bookings#salon.com',''); // Email form responses sent to bookings#salon.com
$mail->addReplyTo($email,$forename.' '.$surname); // Reply to the user who submitted the form.
$mail->addBCC('outbox#handler.net',''); // Store record of all emails sent via the system.
$mail->Subject = 'Booking Request'; // Subject of the email sent to admin#handler.net that the form responses will be contained within.
$mail->isHTML(TRUE);
$mail->Body = <<<EOD
Booking request from {$forename} with email {$email}.<br />
Contact details: <br />
Full name: {$forename} {$surname}<br />
Email: {$email} <br />
Phone number: {$phone} <br />
Service: {$service} <br />
Date: {$date} {$time}
EOD;
if(!$mail->send()) { // Send the email.
echo '';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo '';
}
}
?>
This block of code is wrong, some quotes are missing
$mail->Body = '
Booking request from '.$forename.' with email '.$email;'
Test Values: $forename $surname $email $phone $service $date $time
To enable variable replacement on a string use double quotes, and you won't need to concatenate variables with dot(.), also this make possible to use escaped caracters like \n, try to adjust your code like this:
$mail->Body = "Booking request from $forename with email $email\n" .
"Test Values: $forename $surname $email $phone $service $date $time";
Firstly we have to view the error so therefore you have to set
$mail->SMTPDebug = 0;
into
$mail->SMTPDebug = 3;
So you can get that error to post against that error.

Categories