PHP SMTP Mail script not working - php

I'm coding a php smtp mail script to send a mail to my users when they lose their password. However it's not working.
The processor always returns:
Message could not be sent...
I've tried it with Gmail smtp and I'm getting the same results.
Can you help? There are two files, the form, and the processor.
Below are the codes:
form:
<html>
<head>
<meta name = 'viewport' content = 'width = device-width, initial-scale = 1.0, maximum-scale = 4.0, user-scalable = yes'>
<link rel = 'stylesheet' href = 'style.css' type = 'text/css'>
<title>Reset Password</title>
</head>
<?php
$db = new PDO('mysql:host=host;dbname=db;charset=utf8', 'user', 'pass');
$sql = $db->query('select id from posts order by id desc');
$row = $sql->fetch(PDO::FETCH_ASSOC);
echo "<a href = 'browse.php?page=".$row['id']."'>Browse</a> <a href = 'index.php'>Home</a>";
echo "<hr>";
echo '<form name = "forgot-pass" action = "reset-pass-notif.php" method = "post">
<label><em>Input your registered email address</em></label><br>
<input type = "text" name = "email"><br>
<em>Enter Image Text:</em><img src="captcha.php" /><br />
<input name="captcha" type="text" /><br>
<input type = "submit" name = "submit" value = "Send Reset-Password Link">
</form>
<hr>
Browse Home';
?>
</html>
processor:
<html>
<head>
<meta name = 'viewport' content = 'width = device-width, initial-scale = 1.0, maximum-scale = 4.0, user-scalable = yes'>
<link rel = 'stylesheet' href = 'style.css' type = 'text/css'>
<title>Reset Password Notification</title>
</head>
<?php
error_reporting(E_ALL);
session_start();
$db = new PDO('mysql:host=host;dbname=db;charset=utf8', 'user', 'pass');
$sql0 = $db->query('select id from posts order by id desc limit 1');
$row0 = $sql0->fetch(PDO::FETCH_ASSOC);
echo 'Browse Home';
echo '<hr>';
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$sql = $db->prepare('select * from users where email = :email');
$sql->bindParam(':email', $email);
$sql->execute();
$sql->setFetchMode(PDO::FETCH_ASSOC);
$row = $sql->fetch();
$username = $row['username'];
$user_check = $row['user_hash'];
$subject = 'Reset your Password';
$link = 'http://bquotes.xyz/reset-pass-land.php?username='.$row['username'].'&user_check='.$row['user_hash'].'';
$message = 'Reset your password here: '.$link.' If you cannot click on the link, copy it and paste in your browser address bar';
$sql = $db->prepare('select email from users where email = :email');
$sql->bindParam(':email', $email);
$sql->execute();
$sql->setFetchMode(PDO::FETCH_ASSOC);
$row = $sql->fetch();
//require_once ('class.phpmailer.php');
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.domain.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#domain.com'; // SMTP username
$mail->Password = 'pass'; // SMTP password
//$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('user#domain.com', 'BQuotes Webmaster');
//$mail->addAddress($email); // Add a recipient
/*$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); */ // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
/*if(!$mail->send()) {
//echo '<em>Message could not be sent. Mailer Error:</em> ', "<em>", $mail->ErrorInfo, "</em>";
echo '<span class = "red"><em>Message could not be sent. You have one or more invalid fields.</em></span>';
} else {
echo '<span class = "green"><em>Message has been sent. Please check your Spam folders if not in Inbox by 10 minutes.</em></span>';
}*/
if (($email)&&($username)&&!empty($_POST['captcha'])&&($_POST['captcha']==$_SESSION['code'])&&($mail->send())){
echo '<span class = "green"><em>Message has been sent. Please check your Spam folders if not in Inbox by 10 minutes.</em></span>';
}
else {echo '<span class = "red"><em>Message could not be sent. You have one or more invalid fields.</em></span>';
}
echo "<hr>";
echo 'Browse Home';
?>
</html>
Thanks!

The correct setting for PHPMailer:
<?php
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Username = "user#domain.com";
$mail->Password = "xxxx";
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.domain.com";
$mail->Port = "465";
$mail->setFrom('from#domain.com', 'John Doe');
$mail->addReplyTo('from#domain.com', 'John Doe');
$mail->AddAddress("mailto#otherdomain.com", "Jane Smith");
$mail->CharSet = 'UTF-8';
$mail->IsHTML(true);
$mail->Subject = 'Bla bla or from DB';
$mail->Body = 'Here come the content...';
if (!$mail->send()) {
echo 'Error: ' . $mail->ErrorInfo;
exit;
}
?>

Please use this code .make sure you have given permission in Mail account from you want to send mail.
My Account->Sign-in & security->Allow less secure apps: OFF
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = false;
$mail->isSMTP();
$mail->Host = 'smtp.live.com';
$mail->SMTPAuth = true;
$mail->Username = 'mail#gmail.com';
$mail->Password = 'Password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom($details['from'], $details['from']);
if(is_array($details['to'])){
foreach ($details['to'] as $key => $value) {
$mail->addAddress($value['email'], $value['name']);
}
}else{
$mail->addAddress($details['to'], isset($details['name'])?:$details['to']);
}
$mail->isHTML(true);
$mail->Subject =$details['subject'];
$mail->Body =$details['body'];
$mail->send();

Are you running this on localhost? Try Putting off your antivirus for some time. Antivirus tends to block email sending from localhost at times

Related

Mail configuration error in amazon hosting using php?

I designed my website and hosted on my amazon ec2 instance and I bought my domain in godaddy (www.mydomain.com).Now I want a mail configuration in my contact form page in website.. Below its my code , I don't know where am I mistake the code?
<?php
if(isset($_REQUEST['submit']))
{
try
{
$name = $_POST['name'];
echo "<script type='text/javascript'>alert('$name')
</script>";
$email = $_POST['email'];
echo "<script type='text/javascript'>alert('$email')
</script>";
$subject = $_POST['subject'];
echo "<script type='text/javascript'>alert('$subject')
</script>";
$message = $_POST['message'];
echo "<script type='text/javascript'>alert('$message')
</script>";
$response ="";
$body = <<<EOD
<div style='font-size:18px'>
<b> Name </b> : $name <br />
<b> Email address </b> : $email <br />
<b>Message </b> : $message <br />
</div>
EOD;
$to = "XXXXX#gmail.com";
require_once($_SERVER['DOCUMENT_ROOT'].'/samplemail/lib/class.phpmailer.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/samplemail/lib/class.smtp.php');
$mail = new PHPMailer(true);
//$mail->Host = "relay-hosting.secureserver.net"; // your SMTP Server
// echo $res;
$mail->IsSMTP();
$mail->Host = "email-smtp.us-east-1.amazonaws.com";
$mail->SMTPDebug=true;
$mail->SMTPAuth = true; // Auth Type
$mail->Port = 25;
$mail->IsSendmail();
//$mail->SMTPSecure = "ssl";
$mail->Username = "support#mydomain.com";
$mail->Password = "******";
$mail->Sender = "supportexample#mydomain.com";
$mail->From = "supportexample#mydomain.com";
$mail->AddReplyTo($email);
$mail->FromName = "Example";
$mail->AddAddress($to);
//$mail->AddAddress("desired recipient no.2 optional");
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body=$body;
$mail->WordWrap = 50;
$mail->Send();
echo "<script type='text/javascript'>alert('Mail Send Successfully')
</script>";
}
catch (phpmailerException $e) {
echo "<script type='text/javascript'>alert('Failed')
</script>";
echo $e->errorMessage();
}
}
?>
It gives an error
Could not execute: /var/qmail/bin/sendmail
Try This One. This Might Helpful. You Have To Use Different Email For From Mail.
Instead Of Using
$mail->From = "support#mydomain.com"
You Have To Use Another Email Here :
$mail->From = "supportexample#mydomain.com";
require_once('phpmailer/class.phpmailer.php');
require_once('phpmailer/class.smtp.php');
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = "email-smtp.us-east-1.amazonaws.com"; // SMTP HOST
$mail->SMTPAuth = true;
$mail->Username = "support#mydomain.com"; // SMTP username
$mail->Password = "********"; // SMTP password
$mail->SMTPSecure = "ssl"; // Enable TLS encryption, `ssl` also accepted
$mail->Port = "465"; // TCP port to connect to 587
$mail->From = "supportexample#mydomain.com";
$mail->FromName = "Domain Example";
$mail->addAddress("XXXX#gmail.com");
$mail->addReplyTo("supportexample#mydomain.com");
$mail->isHTML(true);
$mail->Subject = "Hello Test";
$mail->Body = "Test Message Working With Us";
if($mail->send()){
return true;
}
else{
return $mail->ErrorInfo;
}

PHP Mailer: I'm getting an error "Could not access file" while trying to upload the file through form and sending it as a attachment

Here's The PHP Code
I'm able to send the mail. If I comment out the $_FILES['attachment']['name'];
$conn = new mysqli($servername, $username, $password, $dbname);
$category = $_POST['category'];
$attachment = $_FILES['attachment']['name'];
$query = "select Name, email, status, category from mailer where status='subscribed' and category='$category'";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
$name = $row['Name'];
$email = $row['email'];
$status = $row['status'];
$category1 = $row['category'];
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
//send code
//Recipients
$mail->addAddress($email);
$mail->AddAttachment($attachment);
Change $attachment = $_FILES['attachment']['name']; to $attachment = $_FILES['attachment']['tmp_name']; as name refers to the original file name and tmp_name to the (temporary) file path on the server. And you need to specify the file on the server in AddAttachment() call.
$message = 'This for sending an attachment by using php mailer';
$Sender = 'youremail#xyz.com';
$subject = "Attachment Test";
$Recipiant = 'recipient#xyz.com';
$subject = $subject;
$host= "yourdomain.com"; // sets GMAIL as the SMTP server
$port=465; // set the SMTP port for the GMAIL server
$username="info#yourdomain.com"; // GMAIL username
$pwd="domain mail password";
include 'phpmailer/class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->IsMail();
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = $host; // sets GMAIL as the SMTP server
$mail->Port = $port; // set the SMTP port for the GMAIL server
$mail->Username = $username; // GMAIL username
$mail->Password = $pwd; // GMAIL password
$mail->AddReplyTo($Sender,"");
$mail->From = $Sender;
$mail->FromName = $SenderName;
$mail->Sender = $Sender;
$mail->Subject = $subject;
$FileName = 'PRO1158.pdf';
$mail->Body = "<br>".$message."<br>";
if($FileName!=""){
$mail->AddAttachment("Invoices/".$FileName); // attach files
}
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap = 50; // set word wrap
//$mail->MsgHTML($body);
$mail->AddAddress("$Recipiant","");
$mail->IsHTML(true); // send as HTML
$mail->Send();
$mail->ClearAddresses();
First you need to upload the file into a folder then place the file path in
$mail->AddAttachment();
exapmle :
$attachment="D:\uploads\img.jpg"
$mail->AddAttachment($attachment);

How to use phpMailer isSMTP on Bluehost?

It's taken me days to get the right settings so I thought I would post a php script that works on Bluehost. In initial tests using isSMTP is faster than isMAIL.
<?php
require_once '../includes/phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "box1311.bluehost.com"; // specify bluehost as outgoing server
$mail->SMTPSecure = "tls"; // sets the prefix to the server do not use ssl
$mail->SMTPDebug = 3; // comment out if you don't need debug info
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "USER#EXAMPLE.COM"; // SMTP username (your email account)
$mail->Password = "PASSWORD"; // SMTP password
$mail->Port = 25;
$mail->From = 'USER#EXAMPLE.COM';
$mail->FromName = "USER#EXAMPLE.COM";
$mail->AddAddress('CLIENT#gmail.com');
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = 'test message';
$body = '<!DOCTYPE html>
<html><header>
</header>
<body lang=EN-US>
<div style="text-align:center">
<h2>this is a test</h2>
</div>
</body>
</html>';
$mail->Body = $body;
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send()){
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo '<h1>message sent</h1>';
}
?>
This code work for me.
include "phpmailer/class.phpmailer.php";
include "phpmailer/class.smtp.php";
$email_user = "email#host.com";
$email_password = "pass123";
$the_subject = "Title";
$from_name = "Sender";
$phpmailer = new PHPMailer();
// ---------- datos de la cuenta de correo -----------------------------
$phpmailer->Username = $email_user;
$phpmailer->Password = $email_password;
//---------------------------------------------------------------------
$phpmailer->SMTPSecure = 'tls';
$phpmailer->Host = "box6171.bluehost.com";
$phpmailer->Port = 26;
//$phpmailer->SMTPDebug = 2;
$phpmailer->IsSMTP();
$phpmailer->SMTPAuth = true;
$phpmailer->setFrom($phpmailer->Username,$from_name);
$phpmailer->AddAddress("to#host.com");
$phpmailer->Subject = $the_subject;
$phpmailer->Body .="<h1 style='color:#3498db;'>Attachment:</h1>";
$phpmailer->Body .= "<h3>".$attach1."</h3>";
$phpmailer->AddAttachment($attach, "attach1");
$phpmailer->AddBCC("hidecopy#host.com", "bcc1");
$phpmailer->IsHTML(true);
$enviado = $phpmailer->Send();
if($enviado) {
echo 'email send successful';
}
2022 update
$phpmailer->Host = [your fully qualified domain]
$phpmailer->Port = 465
$phpmailer->SMTPSecure = 'ssl'
Important that $phpmailer->From and $phpmailer->Username must be the same.

Why cannot the image attachment be transferred properly via google smtp?

I'm trying to send a picture that I have as a string in base64 on e-mail. This is the code I'm using. The message is sent successfully, however I cannot open/preview the picture, neither in browser, nor when I download it.
When I use online image preview-ers that transform base64 to images and pass them the content of $qr_base64 variable, they show the picture I need. What could be the issue? Thanks in advance.
$mail = new PHPMailer(true);
try
{
//Tell PHPMailer to use SMTP
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Username = "username#gmail.com";
$mail->Password = "pass";
$mail->setFrom('username#gmail.com', 'First Last');
$mail->addAddress("$mailto", 'John Doe');
$mail->Subject = 'PHPMailer SMTP test';
$mail->msgHTML("asdf");
$mail->AltBody = 'This is a plain-text message body';
$mail->AddStringAttachment($qr_base64, "Filename.png");
$mail->send();
} catch (phpmailerException $e) {
echo $e->errorMessage();
} catch (Exception $e) {
echo $e->getMessage();
}
try this
<!DOCTYPE html>
<html>
<body>
<div class="class">
<form action="sendmail.php" method="post" enctype="multipart/form-data">
Email:<input type="email" placeholder="Email" name="emailfrom" /><br><br>
Image: <input type="file" placeholder="Image Upload" name="smtpimg" />
<input type="submit" name="smtp" value="Send SMTP" />
</form>
</div>
</body>
</html>
<?php
include "PHPMailer_5.2.4/class.phpmailer.php";
if(isset($_POST["smtp"])){
$email = $_POST["emailfrom"];
$target_dir = "smtpimg/";
$target_file= $target_dir .time().basename($_FILES['smtpimg']['name']);
$movefile=move_uploaded_file($_FILES['smtpimg']['tmp_name'], $target_file);
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = "username#gmail.com";
$mail->Password = "pass";
$mail->AddReplyTo("reply#yourdomain.com", "Reply name");
$mail->AddAddress($email,'ashu');
$mail->Subject = "SMTP Receivced";
$mail->Body = "<b>Succesfully SMTP Receivced</b>";
$mail->AddAttachment($target_file);
$text = 'Text version of email';
$html = '<html><body>HTML version of email</body></html>';
$file = 'index.php';
$crlf = "\n";
$hdrs = array(
'From' => 'you#yourdomain.com',
'Subject' => 'Test mime message'
);
if($mail->send($hdrs))
{
echo "<script> alert('Successfully Mailed');window.location = '';</script>";
}
else{
echo "Mailed Error: " . $mail->ErrorInfo;
}
}
?>

How to retrieve more than one data in email?

I have a table named 'laptop' and a column inside the table named 'Lap_War_Expiry'. I need to send an email to user when the warranty of the laptop is going to expire soon. For your information, there is more than one warranty that will expired in a day. But the code below is only send the same data from table 'laptop'. Why is that happened and what I have to add in the code so that the email send will retrieve two or more data from database ?
This is my coding for sending the email :
<?php
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com'; // "ssl://smtp.gmail.com" didn't worked
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
// ======== get database data ==================
$link = mysql_connect("localhost","root","");
$database="master_inventory";
mysql_select_db ($database,$link) OR die ("Could not open $database" );
$query = 'SELECT Lap_PC_Name, Lap_War_Expiry FROM laptop'; //xyz is id of desired user
name.
$result1 = mysql_query($query);
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
}
$mail->Username = "email#gmail.com";
$mail->Password = "somepassword";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true;
$mail->From = "email#gmail.com";
$mail->FromName = "AMS";
$mail->addAddress("emailaddress","AMS");
$mail->Subject = "Notification on warranty expiry";
$mail->Body = "Dear Madam,<br/><br />The licensed for the following PC will expired
in less than one month.<br /><br /> PC Name : ".$Lap_PC_Name. "<br />Date of expired :"
.$Lap_War_Expiry;
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
?>
You need to move everything from below your while loop into it.
EDIT
Change
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
}
to
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
$mail->Username = "email#gmail.com";
$mail->Password = "somepassword";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true;
$mail->From = "email#gmail.com";
$mail->FromName = "AMS";
$mail->addAddress("emailaddress","AMS");
$mail->Subject = "Notification on warranty expiry";
$mail->Body = "Dear Madam,<br/><br />The licensed for the following PC will expired
in less than one month.<br /><br /> PC Name : ".$Lap_PC_Name. "<br />Date of expired :"
.$Lap_War_Expiry;
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
}

Categories