Mail send with PHPMailer doesn't work - php

So I'm trying to use PHPMailer to handle the email form on my website.
I wrote the code here based on a tutorial I found.
<?php
error_reporting(E_ALL);
require_once("class.phpmailer.php");
include("class.smtp.php");
$email = new PHPMailer();
//
// Set server details for send
//
$email->IsSMTP();
$email->Host = "mail.loganyoung.za.net";
$email->Port = 25;
$email-SMTPAuth = true;
$email->Username = "<my email>";
$email->Password = "<my password>";
//
// Send mail from the contact form
//
$to = "<my email>";
$from = $_POST["from"];
$name = $_POST["name"];
$subject = "From web: ".$_POST["subject"];
$message = $_POST["message"];
$body = "<p>Hi Logan,</p>";
$body .= "<p>You have received a new query on your website.<br />Please see below:</p>";
$body .= "<p>";
$body .= str_replace("\r\n", "<br />", $message);
$body .= "</p>";
$email->SetFrom($from, $name);
$email->AddReplyTo($from, $name);
$email->AddAddress($to, "LoganYoung.za.net");
$email->Subject = $subject;
$email->Body = $body;
$email->IsHTML = true;
session_start();
if(!$email->Send()) {
$_SESSION["mailresult"] = "success";
echo "success";
} else {
echo "<p>Failed:</p><p>".$email->ErrorInfo."</p>";
$_SESSION["mailresult"] = "failed";
$_SESSION["mailerror"] = $email->ErrorInfo;
}
?>
I figure possible reasons for it not sending could be...
Incorrect SMTP details (possibly send without SMTP auth to resolve?)
Handler isn't getting POST data (the ajax that sends it seems to work fine though)
Some problem with this code that I'm not able to identify...
As a means of eliminating possibilities, can anyone spot anything wrong with the code here? If so, what's wrong, and how do I fix it?
Thanks in advance!

$email-SMTPAuth = true;
Isn't that supposed to be:
$email->SMTPAuth = true;

Related

cannot send email to multiple recepients using phpmailer

I'm trying to send an email to multiple recipients using phpmailer and getting the emails list from my table in the database, however, whenever I make a request only one recipient, the first one on the list gets the email. *I know this might be marked as duplicate but I couldn't find a similar example using mysql
<?php
if (isset($_POST['submit'])) {
if (empty($errors)) {
$thisType = mysql_prep($_POST["partner_type"]);
$content = $_POST["content"];
$header = $_POST["header"];
$query = "SELECT * FROM partners_list WHERE partner_type = '$thisType' ";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result)){
require_once("phpMailer/class.phpmailer.php");
require_once("phpMailer/class.smtp.php");
require_once("phpMailer/language/phpmailer.lang-uk.php");
$to_name = "Order";
$subject = $header;
$message = $content;
$message = wordwrap($message,70);
$from_name = "thisCompany";
$from = "noreply#thicCompany.com";
$mail = new PHPMailer();
$mail->AddAddress($row['email'], "Test Message"); // add each DB entry to list of recipients
$mail->FromName = $from_name;
$mail->From = $from;
$mail->Subject = $subject;
$mail->Body = $message;
$result = $mail->Send();
// Success
$_SESSION["message"] = "e-mail successfully sent.";
redirect_to("successpage.php");
}
}
} else {
}
?>

How to add form validation to phpmailer?

I am a newbie to PHP, and I am currently using phpmailer to let my clients send emails to me, but a bot is apparently taking advantage of it and sends 3 emails at exactly the same time everyday. So I've been trying to add validation to the form using PHP as javascript can be stopped to avoid validation.. Could you guys please help me add validation to this? I just need to validate name and email. Thank you so much in advance.
PS. I removed some parts of the code for privacy.
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$proptypes = $_POST['proptypes'];
$units = $_POST['units'];
$purchaseOrRefi = $_POST['purchase'];
$loans = $_POST['loans'];
$income = $_POST['income'];
$apt = $_POST['apartment'];
$message = $_POST['message'];
$body = "<b>[From]</b><br>$name<br><br> <b>[E-Mail]</b><br>$email<br><br> <b>[Phone #]</b><br>$phone<br><br> <b>[Address]</b><br>$address<br><br> <b>[Type of Property]</b><br>$proptypes<br><br> <b>[# of Units]</b><br>$units<br><br> <b>[Purchase or Refi?]</b><br>$purchaseOrRefi<br><br> <b>[Amnt of Loans Requested]</b><br>$loans<br><br> <b>[Total Income]</b><br>$income<br><br> <b>[Total Apt Expense]</b><br>$apt<br><br> <b>[Message]</b><br>$message<br><br>";
$mail->Subject = 'Someone wants to hear more about your mortgage programs!';
$mail->Body = $body;
$mail->From = '';
$mail->FromName = '';
// Add a recipient
$mail->addAddress('');
$mail->addAddress('');
$mail->addAddress('');
$mail->addAttachment($_FILES['attachment']['tmp_name'], $_FILES['attachment']['name'], 'base64', $_FILES['attachment']['type']); // Add attachments
$mail->isHTML(true);
if(!$mail->send()) {
echo 'Message could not be sent. Please try again.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Your message has been sent! We will get back to you soon!';
}
?>

Send mail via SMTP?

I have a form on my website where people can join events. The code behind it works in this way:
All info is saved in a database. This part works fine.
The second part of the code send out an email to me and to the user with the info he entered (same info as saved in the database)
The issue is that these emails are sent unauthenticated through a default email on the hosting account. I had to modify the script to force SMTP authentication with a valid email under my hosting account to fix the error. Right now the script sends out the email but it ends in spamfilter with all ISPs so the user never receive the email.
I have no idea of how to do, or create the codes so the script use SMTP authentication. Below is the codes I have so fare. Can someone help me?
<?
// SEND OUT EMAIL PART
// COPY SEND TO MY SELF
$to = "my#email.com";
$from = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$headers = "From: $from";
$subject = "Thanks!";
$fields = array();
$fields{"name"} = "Name";
$fields{"address"} = "Address";
$fields{"phone"} = "Phone";
$fields{"email"} = "E-mail addesse";
$body = "INFO:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
// SEND TO THE USER
$headers2 = "From: my#email.com";
$subject2 = "THANKS!";
$fields2 = array();
$from = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$headers = "From: $from";
$subject = "Thanks!";
$body2 = "
TEXT TO EMAIL RECEIVER
\n\n"; foreach ($fields2 as $a => $b){ $body2 .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
// ERROR MESSAGES
if($from == '') {print "MISSING EMAIL ADDRESS.";}
else {
if($name == '') {print "MISSING NAME";}
else {
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $body2, $headers2);
if($send)
{header( "Location: http://mysite/send.php" );}
else
{print "MISSING EMAIL ADDRESS ALL FILDS MUST BE FILLED!"; }
}
}
?>
Best if you use a dedicated script for sending emails. Such as PHPMailer which gives you various config options including SMTP:
// Send Mail
$mail = new PHPMailer(); // initiate
$mail->IsSMTP(); // use SMTP
// SMTP Configuration
$mail->SMTPAuth = true; // set SMTP
$mail->Host = "myhost"; // SMTP server
$mail->Username = "email#email.com";
$mail->Password = "password";
$mail->Port = 465; // change port is required
This is one way to do it. You need to include PHPMailer
#somewhere in code before you call function
include($path_to_PHPMailer."class.smtp.php");
function sendEmail($email,$name,$title,$content,$who=false,$att=array('')){
//VARIABLE $email is email of sender
//VARIABLE $name is name of sender
//VARIABLE $title is title of email
//VARIABLE $content is content of email
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
// DOUBLE $mail->Host = "your email_server"; // SMTP server
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "your email_server"; // sets the SMTP server
$mail->Port = server port; // set the SMTP port for the GMAIL server
$mail->Username = "your username"; // SMTP account username
$mail->Password = "your password"; // SMTP account password
if($who){
$mail->SetFrom($email, $name);
$mail->AddReplyTo($email,$name);
$address = "set your email";//EMAIL OF RECIPENT
} else{
$mail->SetFrom("set your email", "your name (or service name)");
$mail->AddReplyTo("set your email","your name (or service name)");
$address = $email;
}
$content=str_replace("\n", "<br>", $content);
$mail->Subject = $title;
$mail->MsgHTML($content);
$mail->AddAddress($address, $name);
$mail->CharSet='utf-8';
if($att[0]!=''){
foreach ($att as $at){
$mail->AddAttachment($at);
}
}
if(!$mail->Send()) {
return false; //$mail->ErrorInfo;
} else {
return true;
}
}

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.

Replacing mail() script with SMTP script [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
PHP's mail() function has stopped sending my emails. I talked with my service provider and they said I have to use SMTP however i am not professional php developer. They tried to give a little help and they provided me with a script which sends email to me when a user submit a form, but my old form used to send email to me of the clent data as well as a confirmation email email to the client.
The new script i have manged some how to send a confirmation email for the client, but I don't know how send email with this script, can you tell me what I should add to make it work?
if(isset($_POST['submit']))
{
$title = $_POST['title'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$phone = $_POST['phone'];
$visitor_email = $_POST['email'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$state = $_POST['us'];
$details = $_POST['details'];
$reasons = $_POST['re'];
$content = $_POST['message'];
require("class.phpmailer.php");
$mail = new PHPMailer();
//Your SMTP servers details
// set mailer to use SMTP
$mail->IsSMTP();
// specify main and backup server or localhost / your mail server yourmailserver.com
$mail->Host = "xxxxxx.example.com";
// turn on SMTP authentication
$mail->SMTPAuth = true;
// SMTP username
$mail->Username = "me#xxxxx.com";
$mail->Password = "**********"; // SMTP password
//It should be same as that of the SMTP user
$redirect_url = "http://".$_SERVER['SERVER_NAME']; //Redirect URL after submit the form
//$mail->From = $mail->Username; //Default From email same as smtp user
$mail->FromName = "Admin";
//Email address where you wish to receive/collect those emails.
$mail->AddAddress($visitor_email, "");
$mail->WordWrap = 50;// set word wrap to 50 characters
$mail->IsHTML(true);// set email format to HTML
$mail->Subject = 'You have mail from: www.example.com';
// ** Build the Message
$message = "<h4><b>We received your query</b></h4><br/><br/>";
$message .="Thankyou for contacting example.net.<br/>";
$message .="<br>";
$message .="Regards,<br/>";
$message .="admin";
$mail->Body = $message;
//header("Location: thank-you.html");
if(!$mail->Send())
{
header('Location: thank-you.html');
// echo "Message could not be sent. <p>";
// echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
header('Location: thank-you.html');
}
else{
header('Location: contact-us.html');
}
?>
// ******** Second update
<?
ob_start();
if(isset($_POST['submit']))
{
$title = $_POST['title'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$phone = $_POST['phone'];
$visitor_email = $_POST['email'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$state = $_POST['us'];
$details = $_POST['details'];
$reasons = $_POST['re'];
$content = $_POST['message'];
require("class.phpmailer.php");
$mail = new PHPMailer();
//Your SMTP servers details
// set mailer to use SMTP
$mail->IsSMTP();
// specify main and backup server or localhost / your mail server yourmailserver.com
$mail->Host = "xxx.example.net";
// turn on SMTP authentication
$mail->SMTPAuth = true;
// SMTP username
$mail->Username = "*****#example.net";
$mail->Password = "********"; // SMTP password
//It should be same as that of the SMTP user
$redirect_url = "http://".$_SERVER['SERVER_NAME']; //Redirect URL after submit the form
//$mail->From = $mail->Username; //Default From email same as smtp user
$mail->FromName = "Admin vueproperty";
$mail->AddAddress($visitor_email, ""); //Email address where you wish to receive/collect those emails.
//$mail->AddCC($_POST['email']); // ** Client email
$mail->WordWrap = 50;// set word wrap to 50 characters
$mail->IsHTML(true);// set email format to HTML
$mail->Subject = 'You have mail from: www.exmple.net';
// ** Build the Message
$message = "<h4><b>We received your query</b></h4><br/><br/>";
$message .="Thank you for contacting example.net. A property consultant will be in contact with you asap.<br/>";
$message .="<br>";
$message .="Regards,<br/>";
$message .="The example Team";
$mail->Body = $message;
//header("Location: thank-you.html");
if($mail->Send())
{
$body = "Name: $name<br/>";
$body .= "Phone: $phone<br/>";
$body .= "Email: $visitor_email<br/>";
$mail->AddAddress('xphpxmysql#gmail.com', "MINE");
if($mail->Send()){
header('Location: thank-you.html');
exit;
}
}
}
?>
// ******** Third update
<?
ob_start();
if(isset($_POST['submit']))
{
$title = $_POST['title'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$phone = $_POST['phone'];
$visitor_email = $_POST['email'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$state = $_POST['us'];
$details = $_POST['details'];
$reasons = $_POST['re'];
$content = $_POST['message'];
require("class.phpmailer.php");
$mail = new PHPMailer();
//Your SMTP servers details
// set mailer to use SMTP
$mail->IsSMTP();
// specify main and backup server or localhost / your mail server yourmailserver.com
$mail->Host = "xxx.example.net";
// turn on SMTP authentication
$mail->SMTPAuth = true;
// SMTP username
$mail->Username = "*****#example.net";
$mail->Password = "********"; // SMTP password
//It should be same as that of the SMTP user
$redirect_url = "http://".$_SERVER['SERVER_NAME']; //Redirect URL after submit the form
//$mail->From = $mail->Username; //Default From email same as smtp user
$mail->FromName = "Admin vueproperty";
$mail->AddAddress($visitor_email, ""); //Email address where you wish to receive/collect those emails.
//$mail->AddCC($_POST['email']); // ** Client email
$mail->WordWrap = 50;// set word wrap to 50 characters
$mail->IsHTML(true);// set email format to HTML
$mail->Subject = 'You have mail from: www.exmple.net';
// ** Build the Message
$message = "<h4><b>We received your query</b></h4><br/><br/>";
$message .="Thank you for contacting example.net. A property consultant will be in contact with you asap.<br/>";
$message .="<br>";
$message .="Regards,<br/>";
$message .="The example Team";
$mail->Body = $message;
//header("Location: thank-you.html");
if($mail->Send())
{
$body = "Name: " . $name . "<br/>";
$body .= "Phone: " . $phone . "<br/>";
$body .= "Email: ". $visitor_email . "<br/>";
$mail->body = $body;
$mail->AddAddress('xphpxmysql#gmail.com', "MINE");
if($mail->Send())
{
header('Location: thank-you.html');
exit;
}
}
}
?>
//**** The fifth update
<?
ob_start();
if(isset($_POST['submit']))
{
$title = $_POST['title'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$phone = $_POST['phone'];
$visitor_email = $_POST['email'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$state = $_POST['us'];
$details = $_POST['details'];
$reasons = $_POST['re'];
$content = $_POST['message'];
require("class.phpmailer.php");
$mail = new PHPMailer();
//Your SMTP servers details
// set mailer to use SMTP
$mail->IsSMTP();
// specify main and backup server or localhost / your mail server yourmailserver.com
$mail->Host = "xxx.example.net";
// turn on SMTP authentication
$mail->SMTPAuth = true;
// SMTP username
$mail->Username = "*****#example.net";
$mail->Password = "********"; // SMTP password
//It should be same as that of the SMTP user
$redirect_url = "http://".$_SERVER['SERVER_NAME']; //Redirect URL after submit the form
//$mail->From = $mail->Username; //Default From email same as smtp user
$mail->FromName = "Admin vueproperty";
$mail->AddAddress($visitor_email, ""); //Email address where you wish to receive/collect those emails.
//$mail->AddCC($_POST['email']); // ** Client email
$mail->WordWrap = 50;// set word wrap to 50 characters
$mail->IsHTML(true);// set email format to HTML
$mail->Subject = 'You have mail from: www.exmple.net';
// ** Build the Message
$message = "<h4><b>We received your query</b></h4><br/><br/>";
$message .="Thank you for contacting example.net. A property consultant will be in contact with you asap.<br/>";
$message .="<br>";
$message .="Regards,<br/>";
$message .="The example Team";
$mail->Body = $message;
if($mail->Send())
{
$body = "Name: " . $name . "<br/>";
$body .= "Phone: " . $phone . "<br/>";
$body .= "Email: ". $visitor_email . "<br/>";
$mail->Body = $body;
$mail->AddAddress('xphpxmysql#gmail.com', "MINE");
if($mail->Send())
{
header('Location: thank-you.html');
exit;
}
}
}
?>
//// **** Sixth update NOW it's working it's working
<?
ob_start();
if(isset($_POST['submit']))
{
$title = $_POST['title'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$phone = $_POST['phone'];
$visitor_email = $_POST['email'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$state = $_POST['us'];
$details = $_POST['details'];
$reasons = $_POST['re'];
$content = $_POST['message'];
require("class.phpmailer.php");
$mail = new PHPMailer();
//Your SMTP servers details
// set mailer to use SMTP
$mail->IsSMTP();
// specify main and backup server or localhost / your mail server yourmailserver.com
$mail->Host = "xxx.example.net";
// turn on SMTP authentication
$mail->SMTPAuth = true;
// SMTP username
$mail->Username = "*****#example.net";
$mail->Password = "********"; // SMTP password
//It should be same as that of the SMTP user
$redirect_url = "http://".$_SERVER['SERVER_NAME']; //Redirect URL after submit the form
//$mail->From = $mail->Username; //Default From email same as smtp user
$mail->FromName = "Admin vueproperty";
$mail->AddAddress($visitor_email, ""); //Email address where you wish to receive/collect those emails.
//$mail->AddCC($_POST['email']); // ** Client email
$mail->WordWrap = 50;// set word wrap to 50 characters
$mail->IsHTML(true);// set email format to HTML
$mail->Subject = 'You have mail from: www.exmple.net';
// ** Build the Message
$message = "<h4><b>We received your query</b></h4><br/><br/>";
$message .="Thank you for contacting example.net. A property consultant will be in contact with you asap.<br/>";
$message .="<br>";
$message .="Regards,<br/>";
$message .="The example Team";
$mail->Body = $message;
$mail->Send();
$mail->ClearAllRecipients();
$body = "Name: " . $name . "<br/>";
$body .= "Phone: " . $phone . "<br/>";
$body .= "Email: ". $visitor_email . "<br/>";
$mail->Body = $body;
$mail->AddAddress('xphpxmysql#gmail.com', "");
if($mail->Send())
{
$mail->ClearAllRecipients();
header('Location: thank-you.html');
exit;
}
}
if i understand exactly your question. you were able to send the email to your client but you want to send it also to you.
if this the case then. add another receptionist$mail->AddAddress($visitor_email, "MY_CLIENT");
EDIT:
first get red of the second line.
if($mail->Send()){$message = "ALL REQUIRED DATA YOU WANT TO SEND TO YOURSELF";$mail->AddAddress('YOUREMAIL#EXAMPLE.COM', "MINE");if($mail->Send()){header('Location: thank-you.html');exit;}}

Categories