SMTP email not working in PHP - php

code:
<?php
include 'library.php';
include "classes/class.phpmailer.php";
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$sql = "select email from login where email='".$email."'";
$results = mysqli_query($con,$sql);
$fetch = mysqli_num_rows($results);
if($fetch > 0)
{
echo "<p id='red'>Email already exist. Please register with different email id.</p>";
}
else
{
$query = "insert into student_login(email)values('$email')";
$result = mysqli_query($con,$query);
if($result==true)
{
$information="hello everyone";
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = 'example.com';
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = 'cpanel-username';
$mail->Password = 'cpanel-password';
$mail->AddReplyTo($email);
$mail->SetFrom("info#example.com", $email);
$mail->Subject = "Account Activation Link #Example";
$mail->AddAddress($email);
$mail->MsgHTML($information);
$send = $mail->Send();
if($send)
{
echo "<p id='green'>To activate your account. Please login your email and click on link.</p>";
}
else
{
echo "<p id='red'>Your message not sent.</p>";
}
}
else
{
echo "<p id='red'>Error!</p>";
}
}
}
?>
In this code I am using smtp mail function to sent an email quickly. But here what happen when I click on submit button. It show me successfull message but can't receive an email. I do't know where am I doing wrong. How can I fix this issue ?Please help me.
Thank You

I think that two things will help you in diagnosing such problems:
Use try-catch syntax. If something is wrong then you can catch this in block
use SMTP Debug for phpmailer
this is example how you can use mailer:
<?php
require('./vendor/autoload.php');
use PHPMailer\PHPMailer\PHPMailer;
class Mailer {
public $phpmailer;
public function __construct($addresses)
{
$this->phpmailer = new PHPMailer(true);
$this->phpmailer->SMTPDebug = 3; // here you can debug
$this->phpmailer->isSMTP();
$this->phpmailer->Host = 'SMTP.host.example.blabla';
$this->phpmailer->SMTPAuth = true;
$this->phpmailer->Port = 587;
$this->phpmailer->Username = 'username';
$this->phpmailer->Password = 'password';
$this->phpmailer->SetFrom('username', 'subject');
$this->phpmailer->CharSet = "UTF-8";
foreach ($addresses as $address) {
$this->phpmailer->AddAddress($address);
}
}
public function send($messageTemplate) {
try {
$this->phpmailer->MsgHTML($messageTemplate);
$this->phpmailer->Subject = 'subject';
$this->phpmailer->Send();
return true;
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
}
}
and use it:
$mail = new Mailer(array('test#test.com'));
if ($mail->send('some message')) {
echo "mail send";
}

omkara
A good idea is take test by parts, so:
First of all, ensure that there are no problems with sending emails, and then check your code!
1 - Can You send a e-mail using the web server (whitout use php)?
2 - Check if mail() function is enabled on your server, here's how to do it.
3 - After try run your code check the php logs in the server.

Related

Made a function to send mail using PHPmailer. but it is not working

i made a php function to send mail using phpmailer. but, there is a problem in the function. it neither send mail nor shows error. please help me out. i'm fetching mail body and some other details from other functions and its working fine except it doesn't send mail and i think there must be some problem with the host,port,username,etc.
please help me out.
thanks
my funciton:
public static function sendEmail($data) {
$r_error = 1;
$r_message = "";
$r_data = array();
$q = "select * from config where type='email_detail'";
$r = self::DBrunQuery($q);
$row = self::DBfetchRow($r);
$detail = json_decode($row['value'], true);
include "phpmailer/PHPMailerAutoload.php";
if (!empty($data['email'])) {
foreach ($data as $var) {
$work_email = 'fahadansari12feb#gmail.com'; //$var['email_id'];
$name = 'fahad'; //$var['name'];
$subject = $var['subject'];
$body = $var['body'];
$cc = $var['cc_detail'];
$bcc = $var['bcc_detail'];
$file_upload = $var['upload_file'];
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = '5.9.144.226'; //$detail['host'];
$mail->Port = '2222'; //$detail['port'];
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = 'fahadansari12feb#gmail.com'; //$detail['username']; //sender email address
$mail->Password = 'mypassword'; //$detail['password']; // sender email password
$mail->setFrom('hr#excellencetechnologies.in', 'Excellence Technologies'); // name and email address from which email is send
$mail->addReplyTo('hr#excellencetechnologies.in', 'Excellence Technologies'); // reply email address with name
$mail->addAddress($work_email, $name); // name and address to whome mail is to send
if (sizeof($cc) > 0) {
foreach ($cc as $d) {
$mail->addCC($d[0], $d[1]);
}
}
if (sizeof($bcc) > 0) {
foreach ($bcc as $d2) {
$mail->addBCC($d2[0], $d2[1]);
}
}
$mail->Subject = $subject; // subject of email message
$mail->msgHTML($body); // main message
// $mail->AltBody = 'This is a plain-text message body';
//Attach an image file
if (sizeof($file_upload) > 0) {
foreach ($file_upload as $d3) {
$mail->addAttachment($d3);
}
}
//send the message, check for errors
if (!$mail->send()) {
$row3 = $mail->ErrorInfo;
} else {
$row3 = "Message sent";
}
}
}
if ($row3 != "Message sent") {
$r_error = 1;
$r_message = $row3;
$r_data['message'] = $r_message;
} else {
$r_error = 0;
$r_message = "Message Sent";
$r_data['message'] = $r_message;
}
$return = array();
$return['error'] = $r_error;
$return['data'] = $r_data;
return $return;
}
You've not posted enough info, but I'm going to guess your problem. You're enabling TLS, but you're connecting to an IP address rather than a host name, so your host name will never match the name on the certificate and you will get a TLS validation failure on SMTP connections.
Connect to a named host with a valid certificate, or disable certificate checks (see PHPMailer docs for how to do that), though that's not recommended.
You're also using an old version of PHPMailer, so upgrade.

PHPMailer does not give error message?

Im creating a little Email Script at the Moment with PHPMailer + SMTP Authentication. I tried now sending an E-Mail using a wrong Passwort - but it still gives back "true" for success... anyone have any idea?`
Here is My Function, that i use to call sendmail:
$erfolg_email = true;
foreach($empfaenger as $value)
{
$response = $this->sendMail($smtp, $value, $content, $files);
if($response != true)
{
return $response;
$erfolg_email = false;
}
}
And here is my PHPMailer Function
function sendMail($smtp, $empfaenger, $content, $attachements)
{
$mail = new PHPMailer(true);
try{
$mail->IsSMTP();
$mail->Host = $smtp['SMTP'];
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Port = $smtp['Port'];
$mail->SMTPSecure = 'tls';
if($smtp['Domain'] != '')
{
$username = $smtp['Username']."#".$smtp['Domain'];
}else
{
$username = $smtp['Username'];
}
$mail->Username = $username; // SMTP username
$mail->Password = $smtp['Password']; // SMTP password
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->From = $smtp['Email_Address'];
$mail->AddAddress($empfaenger);
$mail->WordWrap = 50;
$mail->isHTML(true);
foreach($attachements as $value)
{
$mail->AddAttachment($value);
}
$mail->Subject = "Mahnung";
$mail->Body = $content;
$mail->AltBody = "Sie haben offene Posten";
if($mail->Send() == true)
{
echo $mail->ErrorInfo;
return $mail->ErrorInfo;
}else
{
return $mail->ErrorInfo;
}
} catch (phpmailerException $e) {
return $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
return $e->getMessage(); //Boring error messages from anything else!
}
}
$smtp contains an array with all the SMTP INformation, Email address, Signature, Smtp Server, Port, Username, Password and SSL Usage...
I am pretty sure, I am using the wrong username and password, as no Email is getting through - but i still get "true" as a result of the send mail function... its not even echoing the error. I did even try to give an Error Message, when sending is successfull... But nothing
Any help is apreciated!
Cheers
Your function sendMail doesn't return a boolean. Since it's an array / object the result is always true in this case. Try printing $response before your if statement and you will see the error.
In your php mailer function file itself you can add this coding at the last:
$send = $mail->Send(); //Send the mails
if($send){
echo '<center><h3>Mail sent successfully</h3></center>';
}
else{
echo '<center><h3>Mail error: </h3></center>'.$mail->ErrorInfo;
}
}

Page not redirecting

An Excel file is uploaded from a html form the regno and email information are read from the excel file.Each user is then sent an email along with a message.The regno and email are inserted in the database.
gmail is used for sending emails $frmid is the from email address and $password is the password for it.
Here is the code.
<?php
require_once("function/PHPExcel/Classes/PHPExcel/IOFactory.php");
require_once("function/Mail/class.phpmailer.php");
require_once("function/connection.php");
if($_SERVER['REQUEST_METHOD']=='POST' && is_uploaded_file($_FILES['uploaded_file']['tmp_name'])){
$msg=$_POST['msg'];
$arr=array();
$frmid=htmlspecialchars(trim($_POST['frm_id']),ENT_QUOTES,'UTF-8');
$password=htmlspecialchars(trim($_POST['password']),ENT_QUOTES,'UTF-8');
$subject=htmlspecialchars(trim($_POST['subject']),ENT_QUOTES,'UTF-8');
$name=$_FILES['uploaded_file']['tmp_name'];
try {
$inputFileType = PHPExcel_IOFactory::identify($name);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($name);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
for ($row = 1; $row <= $highestRow; $row++){
$email = $sheet->getCell('B'.$row )->getValue();
$regno = strtoupper($sheet->getCell('A'.$row )->getValue());
$arr[]=array($regno,$email);
$message=$msg;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->IsHTML(true);
$mail->Username = $frmid;
$mail->Password = $password;
$mail->SetFrom($frmid);
$mail->Subject = $subject;
$mail->MsgHTML($msg);
$mail->AddAddress($email);
if(!$mail->Send()){
die("Failed to send to Email Id ".$email."\n<br/>");
}
}
} catch(Exception $e) {
die('Server Error');
}
$db=connection();
$query="INSERT INTO table(regno,email) VALUES ";
$query=buildinsert($query,$highestRow);
$stmt=$db->prepare($query);
$result=$stmt->execute($arr);
if($stmt->rowCount()==$highestRow){
redirect("page.php?result=1");
}else{
redirect("page.php?result=0");
}
}
?>
The functions used are
<?php
function buildinsert($query,$rows){
$placeholder=array();
for($i=0;$i<$rows;$i++){
$placeholder[]="(?,?)";
}
return($query.implode(",",$placeholder));
}
function connection(){
try{
return (new PDO("mysql:host=localhost;dbname=dbms,","root","passwd"));
}catch(Exception $e){
die( "An error occured".$e->getMessage());
}
}
function redirect($link){
header("Location:".$link);
}
?>
The problem is I`m not being redirected after the operation completes.The mails are sent successfully and the content is also added but the page does not change.I get same page as before
Found the Problem.The phpmailer,phpexcel are fine the problem was with connection.php
After I added buildinsert function I left a newline,The page was not redirecting because of the newline space between
Thanks Jon!

PHPMailer failing

Ok, I'm guessing this is something simple or I'm using something deprecated that I didn't know about.
I'll remove superfluous bits from my code, but everything removed has been tested.
The original code is based on a very common tutorial script that I've seen everywhere. It is getting to the line:
while ($row = $res->fetch_array()) {
and the php is failing with a common: Call to a member function fetch_array() on a non-object.
Normally this would flag to me that my SQL is failing or returning something unwanted, I'd have a minor fix and then move on with my life. However that doesn't appear to be the case. I've been over and over that SQL and it is returning what I want it to.
I thought it might have something to do with calling the while loop inside the else (but that shouldn't be a problem) or that the mail call is within the while loop.
Original Code:
$email = $link->real_escape_string($_POST["web_forgot_email"]);
$sendemail = 0;
$sql = "SQL to return Name and Email (Tested extensively and works)";
$res = $link->query($sql);
if ($res->num_rows == 0) {
$arr = array("web_forgot_success" => "web no account");
echo json_encode($arr);
} else {
while ($row = $res->fetch_array()) {
$sendemail = $row['CLIENT_EMAIL'];
$name = $row['NAME'];
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "localhost";
$mail->SMTPAuth = true;
$mail->Username = "quizzically#quizzically.co.uk";
$mail->Password = "quizzically01";
$mail->From = "quizzically#quizzically.co.uk";
$mail->FromName = "quizzically";
$mail->AddAddress($sendemail);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = "quizzically password reset confirmation";
$mailer = "Email Message";
$mail->Body = $mailer;
if(!$mail->Send()) {
$arr = array("web_forgot_success" => "web no send");
echo json_encode($arr);
} else {
$arr = array("web_forgot_success" => "web forgot success");
echo json_encode($arr);
}
}
}
So I rejigged code so that it finds variables $sendemail and $name first and then send an email but every time (even though the $sendemail variable is not 0) it skips that if statement and returns the else. I've tested the $sendemail variable by sending it back to myself in the else variable and it is definitely not 0.
Good thing is that the PHP does not fail, bad thing is that something is causing the code to skip the whole if section dealing with sending the email.
Rejigged Code:
$email = $link->real_escape_string($_POST["web_forgot_email"]);
$sendemail = 0;
$sql = "SQL to return Name and Email (Tested extensively and works)";
$res = $link->query($sql);
if ($res->num_rows == 0) {
$arr = array("web_forgot_success" => "web no account");
echo json_encode($arr);
}
while ($row = $res->fetch_array()) {
$sendemail = $row['CLIENT_EMAIL'];
$name = $row['NAME'];
}
if ($sendemail != 0) {
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "localhost";
$mail->SMTPAuth = true;
$mail->Username = "quizzically#quizzically.co.uk";
$mail->Password = "quizzically01";
$mail->From = "quizzically#quizzically.co.uk";
$mail->FromName = "quizzically";
$mail->AddAddress($sendemail);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = "quizzically password reset confirmation";
$mailer = "Email Message";
$mail->Body = $mailer;
if(!$mail->Send()) {
$arr = array("web_forgot_success" => "web no send");
echo json_encode($arr);
} else {
$arr = array("web_forgot_success" => "web forgot success");
echo json_encode($arr);
}
} else {
$arr = array("web_forgot_success" => "web forgot failed");
echo json_encode($arr);
}
I'm hoping that I'm doing something deprecated that I haven't found or whatnot, but any help would be appreciated.
The answer is in my own inability to test fully. I had an issue with the html in the message of the email I was sending. This must have been throwing up and error and then the PHP failed on the while loop.
Error in the HTML fixed (it was an un-escaped double quote) and everything is sending fine with no errors.

PHPMailer - AUTH not accepted

I'm trying to run PHPMailer for an internal contact form and I am getting the error ERROR: AUTH not accepted from server. Here is my current code..
require_once('/includes/class.phpmailer.php');
include("/includes/class.smtp.php");
if (isset($_POST['submit'])) {
$mail = new PHPMailer(true);
$mail->IsSMTP();
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
try {
$mail->Host = "192.168.6.6";
$mail->SMTPDebug = 2;
$mail->SMTPAuth = True;
$mail->Username = 'xxxxx';
$mail->Password = '***';
$mail->Port = 25;
$mail->AddAddress('xxx#xxx.com', 'xxxxx');
$mail->SetFrom($email);
$mail->Subject = 'New message from Contact Form';
$mail->Body = $message;
$mail->Send();
} catch (phpmailerException $e) {
echo $e->errorMessage();
} catch (Exception $e) {
echo $e->getMessage();
}
};
This error basically means that your attempt to authenticate was rejected by the remote server. Different PHPMailer settings (well SMTP settings) are required by different remote mail servers.
This could be caused by
Using the wrong port
Using the wrong host
Incorrect user/pass
Incorrect SMTPSecure
Example SMTP setup:
Gmail: use of phpmailer class
Hotmail: phpmailer with hotmail?
If you are using this internally, you may not need to use SMTP authentication at all, depending on your server settings. Try this and see if it works:
require_once('/includes/class.phpmailer.php');
include("/includes/class.smtp.php");
if (isset($_POST['submit'])) {
$mail = new PHPMailer(true);
$mail->IsSMTP();
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
try {
$mail->Host = "192.168.6.6";
$mail->SMTPDebug = 0;
$mail->SMTPAuth = False;
$mail->Port = 25;
$mail->AddAddress('xxx#xxx.com', 'xxxxx');
$mail->SetFrom($email);
$mail->Subject = 'New message from Contact Form';
$mail->Body = $message;
$mail->Send();
} catch (phpmailerException $e) {
echo $e->errorMessage();
} catch (Exception $e) {
echo $e->getMessage();
}
};

Categories