How to addCC and addReplyTo for multiple email addresses? - php

I'd like to use this send.php script for a contact form. Right now when an email is sent, a user inputs their name, email, and the email of the person to send the email to.
The email is sent from #Email_Placeholder and both #Email_Placeholder, $email, and #email_2 gets a copy of the email.
I'd like to add the option for an addReplyTo and addCC so that both $email and $email_2 receives an email when either of the 3 parties makes a reply to the original email thread.
What is the correct syntax so that $email, and $email_2 are added to the addReplyTo and addCC parameters so that they receive every email in the original thread?
//Lines to edit. Goal add $email and $email_2 to addReplyTo and addCC
$mail->addReplyTo('#Email_Placeholder', 'Information');
$mail->addCC('#Email_Placeholder'); //should be changed to the name of the app owner's email
Send.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING); //sanitize data
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$email_2 = filter_var($_POST['email_2'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
/*added line of code*/
if(empty($name)){
header("location: index.php?nouser");
exit();
}
if(empty($email)){
header("location: index.php?noemail");
exit();
}
if(empty($message)){
header("location: index.php?noemail");
exit();
}
/*if(empty($message)){
header("location: index.php?nomessage");
exit();
}//end validation*/
//added line; 'honeypot'
if(empty($_POST['phone2'])){
//Information that needs to be filled out to be able to send an email through phpmailer
//Will use an SMTP service. SMTP is basically like a mail server to send mail
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 1;
//$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = false;
$mail->Host = 'relay-hosting.secureserver.net';
$mail->Port = "25";
$mail->Username = "#Email_Placeholder";
$mail->Password = "Password";
$mail->SetFrom("#Email_Placeholder");
$mail->setFrom('#Email_Placeholder', 'Greeting');
// Add a recipient : used to also send to name
//This sends an email to both $email and $email_2
$mail->addAddress($email);
$mail->addAddress($email_2);
//This makes it so that #Email_Placeholder receives a copy of the emails
$mail->addReplyTo('#Email_Placeholder', 'Information');
$mail->addCC('email#gmail.com');
/*$mail->addBCC('bcc#example.com');*/
//Body content
$body = "<p><strong>Hello, </strong>" . $email . " How are you?
<br>
<b> Please Notice: </b><br>
<br> <br> Your message was Delivered: " . $message . ". Hello" . $name2 .
"</p>";
$mail->isHTML(true);
//subject line of email
$mail->Subject = $name;
//for html email
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
//the email gets sent
header("Location: http://www.test-domain.com");
$mail->send();
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
?>

Related

This ite can't be reached (PHP mailer)

When I try to submit the completed form it must redirect me to a success page to indicate that the email has been sent successfully. But unfortunately, this appears and the email doesn't come
image site
This is the code
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';
// Instantiation and passing [ICODE]true[/ICODE] enables exceptions
$mail = new PHPMailer(true);
try {
function get_ip() {
if(isset($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
}
elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
return (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '');
}
}
//Server settings
$ip=get_ip();
$query=#unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isMail(); // Set mailer to use SMTP
$mail->Host = 'smtp.office365.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '//'; // SMTP username
$mail->Password = '///'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, [ICODE]ssl[/ICODE] also accepted
$mail->Port = 587; // TCP port to connect to
$ips=$_SERVER['REMOTE_ADDR'];
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$landline = $_POST['landline'];
$date = $_POST['date'];
$people = $_POST['people'];
$lunch = $_POST['lunch'];
$enquiry = $_POST['enquiry'];
$questions = $_POST['questions'];
//Recipients
$mail->setFrom($email, $name);
$mail->addAddress('bookings#rios.com.au', 'Rios bookings'); // Name is optional
$mail->addAddress($email, $name); // Add a recipient
$mail->addReplyTo('bookings#rios.com.au', 'Information from customer');
// $mail->addCC('cc#example.com');
// $mail->addBCC('bcc#example.com');
// // Attachments
// $mail->addAttachment('/home/cpanelusername/attachment.txt'); // Add attachments
// $mail->addAttachment('/home/cpanelusername/image.jpg', 'new.jpg'); // Optional name
// Content
// $mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Rio E-mail from Website / Contact Us Form';
$mail->Body = "
New Message from Rio Contact Form
Name: {$name}
Email: {$email}
Mobile: {$mobile}
Landline: {$landline}
Date: {$date}
People: {$people}
Lunch or Dinner: {$lunch}
Enquiry or booking: {$enquiry}
Questions: {$questions}
{$ips} {$query['city']} {$query['regionName']} {$query['zip']} {$query['timezone']}
";
header('location:success.html');
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
This is how I have organized the files
files
....................................................................................
This is not a good pattern:
header('location:success.html');
$mail->send();
echo 'Message has been sent';
You don't know that sending has succeeded until after calling send(), and any content you output after setting the header will either be lost (because it redirects away before it can be seen), or it will prevent the redirect from happening (because content is already sent). This should be enough, in this order:
$mail->send();
header('location:success.html');
exit; //Do nothing else after issuing the redirect
Strictly speaking, redirects should use absolute URLs, so perhaps add that into the destination address.
You're also doing this:
$email = $_POST['email'];
...
$mail->setFrom($email, $name);
That's forgery and will probably end up getting your message blocked, bounced, or spam filtered. Do this instead:
$mail->setFrom('bookings#rios.com.au', $name);
$mail->addAddress('bookings#rios.com.au', 'Rios bookings');
$mail->addReplyTo($email, $name);
This way the message is sent from you, to you, but replies will go to the submitter's address.
One other tip — learn how to use composer.

PHPMailer ismail not working in bluehost

I am usng bluehost as server of my domain. I am using below code for sending mail using PHPMailer. The code does not through error and confirms that the mail has gone. But actually the mail does not go to recipient. can anyone suggest what is wrong here?
$Recpnt1='abc#gmail.com';
$emailfrom = 'xyz#AlphaBeta.com';
require_once 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;
//From email address and name
$mail->From = $emailfrom;
$mail->FromName = "AlphaBeta";
//To address and name
$mail->addAddress($Recpnt1);
//Send HTML or Plain Text email
$mail->isHTML(true);
// Your subject
$mail->Subject = "Your confirmation link here";
$message='ABCD';
$mail->Body = $message;
if($mail->send())
{
$error = $error . "Confirmation link Has Been Sent To Your Email Address.";
}
else
{
$error = $error . 'Cannot send Confirmation link to your e-mail address';
}

Two versions of same email to two different recipients using class.phpmailer.php

I'm trying to send two versions of the same email to two recipients using phpMailer
Depending on the email I need to send one version or another.
At the moment I'm able to send only the same version to both email address
<?php
require_once('class.phpmailer.php');
if(isset($_POST['Submit'])) {
$fname = $_POST['fname'];
$maileremail = $_POST['maileremail'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$mail = new PHPMailer();
$text = 'The person that contacted you is '.$fname.' E-mail: '.$maileremail.' Subject: '.$subject.' Message: '.$message.' :';
$body = eregi_replace("[\]",'',$text);
$text2 = 'The person that contacted you is '.$fname.' E-mail: REMOVED - To get email address you must login Subject: '.$subject.' Message: '.$message.' :';
$body2 = eregi_replace("[\]",'',$text2);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "xxxxx.xxxxx.xxx"; // SMTP server
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent
$mail->Host = "xxxxx.xxxxx.xxx"; // sets the SMTP server
$mail->Port = XXXXXXXX; // set the SMTP port for the GMAIL server
$mail->Username = "xxxxx#xxxxx.xxx"; // SMTP account username
$mail->Password = "XXXXXXXX"; // SMTP account password
$mail->SetFrom('xxxxx#xxxxx.xxx', 'XXXXXXXX');
$mail->Subject = $subject;
$add = array("first#email.xxx", "second#email.xxx");
foreach($add as $address) {
if($address == "first#email.xxx") {
$mail->AddAddress($address, "xxxxxxxxx");
$mail->Body = $body;
}
elseif($address == "second#email.xxx") {
$mail->AddAddress($address, "xxxxxxxxx");
$mail->Body = $body2;
}
}
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "<h3><b>Message sent!</b></h3>";
}}?>
If you're looking to do all the setup once for minimal repetition, simply clone your $mail object in your foreach($add) loop:
foreach ( $add as $address ) {
$current = clone $mail;
if ( $address == 'first#mail.com' ) {
$current->AddAddress($address, "xxxxxxxxx");
$current->Body = $body;
$current->send();
} elseif....
This creates a separate clone of your $mail object for every loop, allowing you to add different email bodies, subjects, etc. without having to rewrite all connection settings.
I think you want to seach the $maileremail inside $add and send the desired email.
$add = array("first#email.xxx", "second#email.xxx");
$mail->AddAddress($maileremail, "xxxxxxxxx");
if($maileremail === $add[0])
$mail->Body = $body;
if($maileremail === $add[1])
$mail->Body = $body2;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "<h3><b>Message sent!</b></h3>";
}
EDITED:
I misunderstood the question. Brian is right.

How to Code phpMailer to prevent sending email if hidden field is filled in contact form

I like phpMailer but when I used a previous mailer it had an anti spam code.
You added a hidden field in the contact form and the mail.php script was coded that if the hidden field was filled in (i.e. only a spam robot would do that) the mail wouldnt send
How would I add that to this script?
This is my mail.php code as follows
<?php
// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$address = $_REQUEST['address'] ;
$postcode = $_REQUEST['postcode'] ;
$service = $_REQUEST['service'] ;
$height = $_REQUEST['height'] ;
$how = $_REQUEST['how'] ;
$website = $_REQUEST['website'] ;
$mail_intro ="The following enquiry came from your web site:";
// When we unzipped PHPMailer, it unzipped to
// public_html/PHPMailer_5.2.0
require("class.phpmailer.php");
$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 = "localhost"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "franchise#website.co.uk"; // SMTP username
$mail->Password = "passowrd"; // SMTP password
$mail->From = "noreply#website.co.uk";
$mail->FromName = "B";
$mail->AddReplyTo($email,$name);
$mail->AddAddress("franchise#website.co.uk", "B");
$mail->AddBCC("joseph#website.co.uk", "Joseph");
$response="$mail_intro\n<br />Name: $name\n<br />Email: $email\n<br />Phone: $phone\n<br />Address: $address\n<br /> Comments:\n$message\n<br /> Website: $website\n";
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "Enquiry";
// $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 = $response;
$mail->AltBody = $message;
//Autoresponder
$mailto="$email";
$subject="Franchisee Enquiry";
$body.="Thanks for your enquiry, the message below has been sent. \n";
$body.="If due to an unknown technical error you do not receive a response within 4 hours please phone \n";
$body.="or email us directly at info#website.co.uk where we will be only too happy to help.\n";
$body.="$mail_intro\n";
$body.="Name: $name\n";
$body.="Email: $email\n";
$body.="Phone: $phone\n";
$body.="Postcode: $postcode\n";
$body.="Service Required: $service\n";
$body.="How found: $how\n";
$body.="Comments:\n$message\n";
mail($mailto,$subject,$body,"From: noreply#website.co.uk\n");
if(!$mail->Send())
{
header("Location: http://website.co.uk/error.php");
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
header("Location: http://website.co.uk/thankyou.php");
?>
In your HTML, add:
<input type="text" name="fooBarBaz" style="display: none">
And in your PHP:
if ( !empty($_REQUEST['fooBarBaz']) )
{
// hidden field was filled out, do something about it
}
else
{
$email = $_REQUEST['email'];
...
}

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