I am struggling to send email using SMTP PHP. I am using gmail SMTP. Can anyone tell me where is the problem with this code? I am trying this code in cpanel, i cant find where is the problem in this code. There is no PHP error message in cpanel error logs.
<?php
require "config/config.php"; //include config file
// GOOGLE GOODNESS
ini_set('display_errors', 1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$userIP = $_SERVER["REMOTE_ADDR"];
$recaptchaResponse = $_POST['g-recaptcha-response'];
$secretKey = $yoursecretkey;
$request = file_get_contents("https://www.google.com/recaptcha /api/siteverify?secret={$secretKey}&response={$recaptchaResponse}&remoteip={$userIP}");
if (!strstr($request, "true")) {
echo '<div class="alert alert-danger" role="alert"><strong>Error!</strong>There was a problem with the Captcha, you lied to us! you are a robot! or you just didnt click it :)</div>';
} else {
// echo "WORKS MOTHERFUCKER CONGRATS!";
if (isset($_POST['submit'])) {
$message = 'Full Name: ' . $_POST['fullname'] . '<br />
Subject: ' . $_POST['subject'] . '<br />
Phone: ' . $_POST['phone'] . '<br />
Email: ' . $_POST['emailid'] . '<br />
Comments: ' . $_POST['comments'] . '
';
require "PHPMailer-master/class.phpmailer.php"; //include phpmailer class
// Instantiate Class
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Host = "smtp.gmail.com"; //Gmail SMTP server address
$mail->Port = 465; //Gmail SMTP port
$mail->Encoding = '7bit';
// Authentication
$mail->Username = "xxxxxxx"; // Your full Gmail address
$mail->Password = "xxxxxxx"; // Your Gmail password
// Compose
$mail->SetFrom($_POST['emailid'], $_POST['fullname']);
$mail->AddReplyTo($_POST['emailid'], $_POST['fullname']);
$mail->Subject = "New Contact Form Enquiry"; // Subject (which isn't required)
$mail->MsgHTML($message);
// Send To
$mail->AddAddress("xxxxxxx", "xxxxxxx"); // Where to send it - Recipient
$result = $mail->Send(); // Send!
$message = $result ? '<div class="alert alert-success" role="alert"><strong>Success! </strong>Message Sent Successfully!</div>' : '<div class="alert alert-danger" role="alert"> <strong>Error!</strong>There was a problem delivering the message.</div>';
unset($mail);
}
}
}
?>
The only error i get is: There was a problem delivering the message on contact form. class.phpmailer.php is included in PHPMailer-master folder. I will appreciate your assistance.
strong text
Thanks guys, i used my web hosting email address,SMTP Host and SMTP Port. It works. I don't understand why it does not send using gmail SMTP.
Related
I'm making a contact us form on my website, I've used PHPMailer to handle sending the form to my email, everything was working fine on my local host and on a free online host (Heroku) that I was using to test the website. The issue started when the company published the website, the form won't submit when we attach a file which is not already in the uploads folder(or not with the same name of a file in the uploads folder).
Did this problem happen with anyone before, is it an issue with the code or the server or what ?
This is my code :
$path = 'upload/' . $_FILES["personalCV"]["name"];
move_uploaded_file($_FILES["personalCV"]["tmp_name"], $path);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
//Server settings
// $mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username =// <SMTP username>
$mail->Password =// <SMTP password>
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;
//Recipients
$mail->setFrom(<email>, <AS Website>);
$mail->addAddress(<address>, <name>);
$mail->addAddress(<address>, <name>); // Add a recipient
// Attachments
$mail->AddAttachment($path);
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New Job Application From The AS Website ( '.$position.' )';
$msg = '<p> Name : '.$firstName.' '.$lastName.'</p>
<p>Email Address: '.$email.'
</p> <p>Phone Number: '.$phoneNum.'</p>
<p>Position Appling For: '.$position.'</p>
<p> Message: '.$message.'</p>';
$mail->Body = $msg;
$mail->send();
$successMsg = '<div class="alert alert-success" role="alert">
Message successfully sent
</div>';
} catch (Exception $e) {
$failMsg = '<div class="alert alert-danger" role="alert">
Message not successfully sent, please try again
</div>';
}
}
The problem is solved, it was an issue with the server's configuration.
Hi i am using smtp latest files and check all the solution availble on net, My SMTP php mail working on localhost not working on server my server's web mail working Fine.First of all i am inserting data into my database then those data i want to sent admin email id my data are inserting in database also mail sending working fine on localhost but given error on server it give's failed to connect with server. i contact with my hosting server support forum but they are saying this your code problem
Here is my PHP Code
<?php
if(isset($_POST['Isubmit'])){
$rname= $_POST['Iname'];
$remail= $_POST['Iemail'];
$rcontact= $_POST['Icontact'];
$rmessage= $_POST['Icomment'];
$rcourse= $_POST['Icourse'];
$date=date("Y-m-d");
$sql=mysqli_query($connect,"INSERT INTO enquiry(`NAME`,`EMAIL_ID`,`MOBILE_NO`,`COMMENT`,`SUBJECT`,`IS_DELETED`,`DATE`)VALUES('".$rname."','".$remail."','".$rcontact."','".$rmessage."','".$rcourse."','1','".$date."')");
//Mail Send Code
$ToEmail = 'admin#gmail.com';
$EmailSubject = 'Site contact form';
$MESSAGE_BODY = "Dear Sir/Mam,"."\n" ."\n"."New Contact Details are - "."\n"."\n";
$MESSAGE_BODY .= "Full Name: ".$rname."\n"."\n";
$MESSAGE_BODY .= "Email: ".$remail."\n"."\n";
$MESSAGE_BODY .= "Phone: ".$rcontact."\n"."\n";
$MESSAGE_BODY .= "Message: ".$rmessage."\n"."\n";
$MESSAGE_BODY .= "Course: ".$rcourse."\n"."\n";
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don'thave access to that date_default_timezone_set('Etc/UTC');
require 'PHPMailer-master/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging // 0 = off (for production use)
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 465;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'ssl';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "username#gmail.com";//"lino.cspace#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";//"lino#123";
//Set who the message is to be sent from
$mail->setFrom('admin#gmail.com', 'Admin');
$mail->addAddress($ToEmail);
//Set the subject line
$mail->Subject = 'Enquiry Mail';
$mail->Body = $MESSAGE_BODY;//'this is test msg on 25-jun.';
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!<br>";
}
}
Enable smtp debugging
$mail->SMTPDebug = 1;
OR
$mail->SMTPDebug = 2;
Then the error info will give you more info on the error
if (!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message sent!<br>";
}
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I am using mail() function to sent mails when an event happening. But it is not working as I expected. I tried to get the return of the function also. Some one please suggst what may be the issue.
$msg = "Your password has been changed.is'".$data['password']."'";
$to = $data['email'];
$subject = "password changed";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: info#hia.com';
$send = mail($to, $subject, $msg, $headers);
if($send){
echo "successful";
}
else{
echo "error";
}
Problems arising from the php setting. Closing function for security by some service provider. You must send mail with SMTP.
Example several SMTP class on github;
hujuice/smtp - snipworks/php-smtp - PHPMailer/PHPMailer
Example code a PHPMailer according to your code;
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info#hia.com'; // SMTP username
$mail->Password = 'yourmailpassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('info#hia.com', 'Mailer');
$mail->addAddress($data['email']); // Name is optional
$mail->addReplyTo('info#hia.com', 'Information');
$mail->addCC('cc#hia.com');
$mail->addBCC('bcc#hia.com');
$mail->CharSet = 'ISO-8859-1';
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'password changed';
$mail->Body = 'Your password has been changed.is "'.$data['password'].'"';
if(!$mail->send()) {
echo 'error';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'successful';
}
Don't use simple mail(), i prefer for PHPmailer function.
Here is a Example.
First - download phpmailer in your project directory.
second - create send_mail.php in your directory(you can change you name).
send_mail.php file code.
require_once "PHPMailer/PHPMailerAutoload.php";
$mail = new PHPMailer(true);
if (!isset($_POST['send'])) {
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the enquiry form!";
die;
}
$to="abc#xyz.com";
$senderName = "xyz";
//send the mail
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$zcode = $_POST["zcode"];
$email = $_POST["email"];
$phone = $_POST["phone"];
//Enable SMTP debugging.
$mail->SMTPDebug = 0;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.gmail.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "abc#xyz.com";
$mail->Password = "########";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "ssl";
//Set TCP port to connect to
$mail->Port = 465;
$mail->From = $to;
$mail->FromName = $senderName;
$mail->addAddress($to, $senderName);
$mail->addReplyTo($email, $name);
$mail->isHTML(true);
$mail->Subject = "bfuiebfiaif";
$mail->Body = "as per your needs";
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
die;
}
header('Location: index.php');
die;
I want to send email to users who click on forgot password link on my website from no-reply#mycompanmysname.com.
I am able to send mail through my companys mail server but I do not want my companys email address to be displayed.
Can anybody suggest how is that done?
I am using phpmailer and this is my code:
$from = "companyname#yahoo.com";
$mail = new PHPMailer();
$body = $messageBody;
$mail->SMTPSecure = 'tls'; //added
$mail->SMTPAuth = true;
$mail->IsSMTP(); // telling the class to use SMTP
//$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->Host = "smtp server name";
$mail->Port = 587;
$mail->Username = "********";
$mail->Password = "******";
$mail->From("$name");
//$mail->SetFrom("$from");
$mail->MsgHTML($body);
$mail->AddAddress("$toEmail");
$mail->Subject = "".$subject."";$mail->Body = $headers . "<br>" . $messageBody . "<br>" . $confidential;
$mail->WordWrap = 50;
$mail->MsgHTML($mail->Body);
if(!$mail->Send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
print "<p class='Error'>Error in sending email.Please try again.</p>";
} else {
print "<p class='success'>An email is sent to you with the access information.</p>";
}
Taking an example from their docs, you can do something like this:
//Set who the message is to be sent from
$mail->setFrom('from#example.com', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('replyto#example.com', 'First Last');
From personal experience, you can do this and it works, but in some mail clients, such as Gmail, you'll get something along the lines of From: email#website.com via otherdomain.com. I'm not sure if there's a way outside of this other than adding some DNS settings. Not sure if you have access to that.
I'm a game developer so I do not have any PHP/network/back end web development knowledge. I've been stuck with this problem all week with no luck online. Before PHPMailer, I tried using the mail() function in PHP but I was getting confused with all the .ini files. I found PHPMailer on this site in one of the answers and I have gotten much further. I followed this tutorial https://www.youtube.com/watch?v=FtWD_ZH9lnE&authuser=0 exactly, but the email will not send and debug is not printing out anything. My code always returns false and displays my "can't send email" message.
<?php session_start();
require_once 'PHPMailer/PHPMailerAutoLoad.php';
require_once 'PHPMailer/class.phpmailer.php';
$errors=[];
if(isset($_POST['name'], $_POST['twitterHandle'], $_POST['email'], $_POST['description'])) {
$fields = [
'name' => $_POST['name'],
'twitterHandle' => $_POST['twitterHandle'],
'email' => $_POST['email'],
'description' => $_POST['description']
];
foreach($fields as $field => $data){
if(empty($data)){
$errors[] = 'The ' . $field . ' field is required';
}
}
//mail connection if all fields are ! empty
if(empty($errors)){
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPDebug = 1;
$mail->Host = 'smtp.gmail.com';
$mail->Username = '#gmail.com';
$mail->Password = 'pass';
$mail->SMTPSecure = 'ssl';
$mail->Port = 25;
$mail->isHTML;
$mail->Subject = 'subject';
$mail->Body = 'From: ' . $fields['name'] . ' (' . $fields['email'] . ')<p>' . $fields['description'] . '</p>';
$mail->FromName = 'Contact';
$mail->addReplyTo($fields['email'], $fields['name']);
$mail->addAddress('#gmail.com', 'name');
//send email
if($mail->send()){
header('Location: index.php');
die();
}else{
//cannot send
$errors[] = "Sorry, but I could not process your submission. Please try again.";
}
}
} else{
$errors[] = 'Something went wrong';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: index.php');
?>
I have tried SSL on port 465 and 25 and also TLS on 587. I forwarded 465 and 25 on my network but 587 wont open. IMAP is also enabled on my gmail.
1). Keep using tls.
2). Most probably you've enabled 2Factor Authentication, you need to go to your gmail settings dashboard and allow your app to authenticate with google. I too had the same problem, which only got resolved when I fixed this setting on google.
Also, have a look at this answer :- send email using Gmail SMTP server through PHP Mailer