PHPMailer will not send email - php

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

Related

PHPMailer not working in localhost WAMP anymore

Please help me out here I have tried possible solutions from former threads but it is not working.
My PHPMailer was working fine in localhost WAMP up until yesterday."SMTP() connection failed" There were no errors in my code, my "extension=php_openssl.dll" is uncommented in the php.ini file. I used port 587 and I even tried 465 but it still doesn't work anymore. My GMAIL allows lesser apps access. No typo errors but then all of a sudden i saw an error in my VScode "intelephense undefined type PHPMailer error 1009" and it highlights lines $mail = new PHPMailer(true); and two more instances of PHPMailer. 3 red lines of that error message in total.
<?php
session_start();
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require 'vendor/autoload.php';
if ($_POST['admin_create']) {
$name = $_POST['adm_name'];
$email = $_POST['adm_email'];
$pword = $_POST['adm_pass'];
$tel = $_POST['adm_tel'];
$house = $_POST['adm_house'];
// instantiating and passing 'true' enables exceptions
$mail = new PHPMailer(true);
try {
// enable debug output
$mail->SMTPDebug = 4;
// send mail using SMTP
$mail->isSMTP();
// set SMTP server to send through which mail
$mail->Host = 'smtp.gmail.com';
// Enable SMTP authentication
$mail->SMTPAuth = true;
//SMTP Username or Usermail
$mail->Username = 'davolufuwa#gmail.com';
//SMTP Password
$mail->Password = '*********';
//Enabling TLS encryption
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
//TCP Port number to connect to in PHPmailer is 465 and above
$mail->Port = 587;
//Recipients of the code
$mail->setFrom('davolufuwa#gmail.com', 'THE KAKEBOZZ');
// Adding a recipient
$mail->addAddress($email, $name);
//Setting Email format to HTML
$mail->isHTML(true);
$verification_code = substr(number_format(time() * rand(), 0, '',
''), 0, 6);
$mail->Subject = 'Email Verification';
$mail->Body = '<p> Your Verification Code is : <b style="font-
size:30px;">' . $verification_code . '</b>.<br> This code will
expire in 5 minutes.</p>';
$mail->send();
//echo 'Message has been sent';
//encrypt the password
$hashii = password_hash($pword, PASSWORD_DEFAULT);
// connect to the database
$con = mysqli_connect("Localhost", "root", "", "kakeboss");
$sql = "INSERT INTO users (//i didn't put SQL query cos of question
) VALUES
('$name','$email','$tel','$house','$hashii','$verification_code',
NULL)";
$verify = mysqli_query($con, $sql);
if ($verify) {
$timestamp = $_SERVER["REQUEST_TIME"];
$_SESSION['time'] = $timestamp;
echo "PLEASE VERIFY YOUR EMAIL <a href='email_verification.php?
email=" . $email . "'>FROM HERE </a>";
} else {
echo "THAT WAS UNSUCCESSFUL";
}
} catch (Exception $e) {
echo "message couldn't be sent.Mailer Error : {$mail->ErrorInfo}";
}
}
?>

How to send email using SMTP in PHP?

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.

Bluehost: PHPMailer save sent message in Sent Items

I'm trying to send an email with the help of PHPMailer, everything works fine except now I want to have a copy of the send mail in Sent Items.
The website is currently hosted in Bluehost. I tried following the example of PHPMailer - GMail but I'm stuck on which path should I specify.
From the example of PHPMailer - GMail the path for Sent Items is:
{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail
I don't know what path should I specify. Everything works fine in my code, only the path for the sent item is missing.
<?php
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
$username = 'john#mydomain.com';
$password = 'password';
function save_mail( $mail ) {
//path or folder for sent items
$path = "{imap.mydomain.com:993/imap/ssl}[...]/..."; //what exactly is the path for my sent item.
//Tell your server to open an IMAP connection using the same username and password as you used for SMTP
$imapStream = imap_open( $path, $mail->Username, $mail->Password );
$result = imap_append( $imapStream, $path, $mail->getSentMIMEMessage() );
imap_close( $imapStream );
return $result;
}
function send(){
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->Host = 'mail.mydomain.com';
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->SMTPAuth = true;
$mail->Username = $username;
$mail->Password = $password;
$mail->setFrom( $username, 'John Doe' );
$mail->addAddress( 'someone#example.com', 'David Doe' );
$mail->Subject = 'TEST SUBJECT';
$mail->msgHTML('<b>TEST</b>');
$mail->AltBody = 'TEST';
if ( !$mail->send() ) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
if (save_mail($mail)) {
echo "Message saved!";
}
}
}
?>
Thanks to Max for the idea of imap_list function.
This gives me the list of a path for my mail directories.
$host = '{imap.mydomain.com/ssl/novalidate-cert}';
$mail = 'support#mydomain.com';
$pass = 'password';
$mbox = imap_open($host, $mail, $pass, OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$list = imap_list($mbox, $host, "*");
if (is_array($list)) {
foreach ($list as $val) {
echo imap_utf7_decode($val) . "\n";
}
} else {
echo "imap_list failed: " . imap_last_error() . "\n";
}
imap_close($mbox);
?>
using the {imap.mydomain.com} or {imap.mydomain.com:993/imap/ssl}gives me an error of:
can't connect: Certificate failure for imap.mydomain.com: Server
name does not match certificate: /OU=Domain Control
Validated/OU=Hosted by BlueHost.Com, INC/OU=PositiveSSL
Wildcard/CN=*.bluehost.com
Certificate issue, luckily I found this question and I end up using the following host:
{imap.mydomain.com/ssl/novalidate-cert}
and the path I'm looking to forward the sent mail into sent items is:
{imap.mydomain.com/ssl/novalidate-cert}INBOX.Sent

php mail script not working using phpMailer

I am using phpMailer to send emails using PHP.
The mail is being sent but it is not received in inbox/spam or anything.
It is surprising that it was working until few days ago.
I have tested it and almost 500-600 emails were sent and received.
But suddenly it stopped "working".
Here's my Php script:
public static function mailTo($recipients)
{
$f3 = \Base::instance();
$edit = $f3->get('editTrue');
$user = AclHelper::getCurrentUser();
$template= new \Template;
if(isset($edit))
{
$mailBody = $template->render('leave/requestEdit.html');
}
else
{
$mailBody= $template->render('leave/emailTemp.html');
}
// When true, PHPMailer returns exceptions
$mail = new PHPMailer(true);
try {
$mail->isSMTP(); // Set mailer to use SMTP
$mail->isHTML(true);
$mail->addAddress($user['email']);
$mail->addAddress("malakar.rakesh1993#gmail.com");
// foreach($recipients as $recipient){
// $mail->addCC($recipient);
// }
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->Username = "malakar.rakesh1993#gmail.com";
$mail->Password = "abcd";
// $mail->Host = $f3->get('GBD.smtp.host'); // Specify main and backup SMTP servers
$mail->setFrom($user['email']);
$userFullName = trim(ucfirst($user['firstname'])) . " " . trim(ucfirst($user['lastname']));
$mail->FromName = $userFullName;
$mail->Body = $f3->get('message');
$mail->Body .="<br>". $mailBody;
if(isset($edit))
{
$mail->AltBody = '';
}
else
{
$mail->AltBody = 'Hello Team,<br>I would like to request leave for the leave dates specified as follows.
Application Date:' . $f3->get('issuedDate') . '<br>Leave requested from:' . $f3->get('leaveFrom') . '<br>Leave requested to:' . $f3->get('leaveTo') . '<br>Leave Description:' . $f3->get('leaveDescription') . 'Leave Type:' . $f3->get('leaveType').'<br><br>Hoping for a positive response.<br><br> Thank you.';
}
$mail->Subject = 'Updates on leave date applied';
$mailStatus = (boolean)$mail->send();
if ($mailStatus === true) {
return $mail;
}
} catch (phpmailerException $e) {
$response = array(
'status'=>'error',
'message'=>'Got some error while sending emails',
'exceptions'=>$e->getMessage()
);
return $response;
} catch (Exception $e) {
$response = array(
'status'=>'error',
'message'=>'Got some error while sending emails',
'exceptions'=>$e->getMessage()
);
return $response;
}
}
I received a junk email though [only one] that says :
This sender failed our fraud detection checks and may not be who they appear to be. Learn about spoofing
I cannot figure out what's going wrong.
It is working until previously. And I have tons of emails in my inbox.
Could it be that there's some limit of sending emails?? Or could it be that some one reported it as spam or spoofing??
Any help is very much appreciated. Thanks.
Because you're using SMTPSecure = 'ssl' you won't get any debug output with SMTPDebug = 2 because that only shows SMTP-level output; You need SMTPDebug = 3 to show connection-level problems. This is probably caused by out of date CA certificates in your PHP config. There have been lots of reports of this because gmail changed theirs recently (why your script stopped working). It's covered in the troubleshooting guide.
Also, why are you putting HTML tags in your plan-text AltBody? They won't work in there.

SMTP connect() failed PHPmailer - PHP

I am new to PHP. I was trying to send myself a sample e-mail through PHPmailer. I am using gmail's smtp server. I am trying to send a sample mail from my gmail account to my yahoo account. But I am getting the error : Mailer Error: SMTP connect() failed.
Here is the code :
<?php
require "class.phpmailer.php";
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "ssl://smtp.gmail.com";
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "myemail#gmail.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
$webmaster_email = "myemail#gmail.com"; //Reply to this email ID
$email="myyahoomail#yahoo.in"; // Recipients email ID
$name="My Name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->Port = 465;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
I am using WAMP server on a Windows 7 64-bit machine. What could be the prob?
Please help me solve this. Thanks!
The solution of this problem is really very simple. actually Google start using a new authorization mechanism for its User.. you might have seen another line in debug console prompting you to log into your account using any browser.! this is because of new XOAUTH2 authentication mechanism which google start using since 2014.
remember.. do not use the ssl over port 465, instead go for tls over 587. this is just because of XOAUTH2 authentication mechanism. if you use ssl over 465, your request will be bounced back.
what you really need to do is .. log into your google account and open up following address
https://www.google.com/settings/security/lesssecureapps
and check turn on . you have to do this for letting you to connect with the google SMTP because according to new authentication mechanism google bounce back all the requests from all those applications which does not follow any standard encryption technique.. after checking turn on.. you are good to go..
here is the code which worked fine for me..
require_once 'C:\xampp\htdocs\email\vendor\autoload.php';
define ('GUSER','youremail#gmail.com');
define ('GPWD','your password');
// make a separate file and include this file in that. call this function in that file.
function smtpmailer($to, $from, $from_name, $subject, $body) {
global $error;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->SMTPAutoTLS = false;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}
You need to add the Host parameter
$mail->Host = "ssl://smtp.gmail.com";
Also, check if you have open_ssl enabled.
<?php
echo !extension_loaded('openssl')?"Not Available":"Available";
Solved an almost identical problem, by adding these lines to the standard PHPMailer configuration. Works like a charm.
$mail->SMTPKeepAlive = true;
$mail->Mailer = “smtp”; // don't change the quotes!
Came across this code (from Simon Chen) while researching a solution here, https://webolio.wordpress.com/2008/03/02/phpmailer-and-smtp-on-1and1-shared-hosting/#comment-89
Troubleshooting
You have add this code:
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
And Enabling Allow less secure apps:
"will usually solve the problem for PHPMailer, and it does not really make your app significantly less secure. Reportedly, changing this setting may take an hour or more to take effect, so don't expect an immediate fix"
This work for me!
$mail->SMTPKeepAlive = true;
$mail->isSendMail(); // instead of isSMTP();
On shared hosting, your mail server may occasionally experience connection issues.
Here I found solution
[Edit]
Here is the link content, in case the link stop working for some reason (it happens)
PHPMailer and SMTP on 1and1 shared hosting
I use PHPMailer on my 1and1 shared hosting account. Recently, I could not send email anymore.
I tried debugging and this is the error that PHPMailer throws:
Language string failed to load: connect_host
After googling for a solution and trying different SMTP servers, accounts and SMTP ports, I decided to switch to sendmail and it worked like a charm! All I needed to do was to replace $mail->isSmtp() with:
$mail->isSendMail()
sendMail is located in its default location on 1and1 servers : /usr/sbin/sendmail, so no change of settings was required.
Conclusion:
1and1 probably closed its outgoing SMTP ports on its shared hosting servers. Consequently, if you use PHPMailer, don’t use SMTP mode anymore.
If anyone is still unable to solve the issue, please check following thread and follow callmebob's answer.
PHPMailer - SMTP ERROR: Password command failed when send mail from my server
I fixed it ...
https://github.com/PHPMailer/PHPMailer/tree/5.2-stable
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // 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 = 'm7#gmail.com'; // SMTP username
$mail->Password = 'pass'; // SMTP password
//$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25; // TCP port to connect to
$mail->setFrom('m7#gmail.com', 'Mailer');
$mail->addAddress('dot#gmail.com', 'User'); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
Turn on access and enjoy..! That is on Gmail account setting.
You are missing the directive that states the connection uses SSL
require ("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true; // turn of SMTP authentication
$mail->Username = "YAHOO ACCOUNT"; // SMTP username
$mail->Password = "YAHOO ACCOUNT PASSWORD"; // SMTP password
$mail->SMTPSecure = "ssl";
$mail->Host = "YAHOO HOST"; // SMTP host
$mail->Port = 465;
Then add in the other parts
$webmaster_email = "myemail#gmail.com"; //Reply to this email ID
$email="myyahoomail#yahoo.in"; // Recipients email ID
$name="My Name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
As a side note, I have had trouble using Body + AltBody together although they are supposed to work. As a result, I wrote the following wrapper function which works perfectly.
<?php
require ("class.phpmailer.php");
// Setup Configuration for Mail Server Settings
$email['host'] = 'smtp.email.com';
$email['port'] = 366;
$email['user'] = 'from#email.com';
$email['pass'] = 'from password';
$email['from'] = 'From Name';
$email['reply'] = 'replyto#email.com';
$email['replyname'] = 'Reply To Name';
$addresses_to_mail_to = 'email1#email.com;email2#email.com';
$email_subject = 'My Subject';
$email_body = '<html>Code Here</html>';
$who_is_receiving_name = 'John Smith';
$result = sendmail(
$email_body,
$email_subject,
$addresses_to_mail_to,
$who_is_receiving_name
);
var_export($result);
function sendmail($body, $subject, $to, $name, $attach = "") {
global $email;
$return = false;
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = $email['host']; // SMTP server
// $mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = $email['host']; // sets the SMTP server
$mail->Port = $email['port']; // set the SMTP port for the GMAIL server
$mail->SMTPSecure = "tls";
$mail->Username = $email['user']; // SMTP account username
$mail->Password = $email['pass']; // SMTP account password
$mail->AddReplyTo($email['reply'], $email['replyname']);
if(stristr($to,';')) {
$totmp = explode(';',$to);
foreach($totmp as $destto) {
if(trim($destto) != "") {
$mail->AddAddress(trim($destto), $name);
}
}
} else {
$mail->AddAddress($to, $name);
}
$mail->SetFrom($email['user'], $email['from']);
$mail->Subject = $subject;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
if(is_array($attach)) {
foreach($attach as $attach_f) {
if($attach_f != "") {
$mail->AddAttachment($attach_f); // attachment
}
}
} else {
if($attach != "") {
$mail->AddAttachment($attach); // attachment
}
}
$mail->Send();
} catch (phpmailerException $e) {
$return = $e->errorMessage();
} catch (Exception $e) {
$return = $e->errorMessage();
}
return $return;
}
if everything fails then for gmail you must turn on access to 3rd party apps to connect to ur gmail account.
https://www.google.com/settings/security/lesssecureapps // turn it
on
Just make sure you passed the right parameters
eg. the correct outgoing server host, username, and password
$mail->SMTPDebug = false;
$mail->Host = 'email_smtp_host'
$mail->SMTPAuth = false
$mail->Username = 'username'
$mail->Password = 'password'
$mail->SMTPSecure 'tls'
$mail->Port = '587'
If you're using VPS and with httpd service, please check if your httpd_can_sendmail is on.
getsebool -a | grep mail
to set on
setsebool -P httpd_can_sendmail on
Try adding this line to your script. This worked for me!
$mail->Mailer = “smtp”;
This is usually a result of the server not accepting SSLv2 or SSLv3 connections which is a standard for cPanel/WHM in favor of TLS only connections. You can check this by going to WHM>>Service Configuration>>Exim Configuration Manager -> Options for OpenSSL
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once "PHPMailer/src/Exception.php";
require_once "PHPMailer/src/PHPMailer.php";
require_once "PHPMailer/src/SMTP.php";
$mail = new PHPMailer();
$mail ->isSMTP();
$mail ->Host ="smtp.gmail.com";
$mail -> SMTPAuth = true;
$mail ->Username = 'youremail#gmail.com';
$mail ->Password = 'password';
//$mail ->SMTPSecure=PHPMailer::ENCRYPTION_STARTTLS;
$mail ->Port = '587';
$mail ->SMTPSecure ='tls';
$mail ->isHTML(true);
$mail ->setFrom('youremail#gmail.com','email send name');
$mail ->addAddress('receiver#gmail.com');
$mail ->Subject = 'HelloWorld';
$mail ->Body = 'a test email';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
if ($mail->send()){
echo "Message has been sent successfully";
}else{
echo "Mailer Error: " . $mail->ErrorInfo;
}
?>
make sure that you configure less secure app settings in gmail using this link https://www.google.com/settings/security/lesssecureapps and make sure you downloaded PHPMailer-master.zip from github
working fine with MAMP server locally :)
After days of searching, I found out that the protocol name needs to be in lowercase.
$mail->SMTPSecure = "ssl"; # lowercase
find the "class.smtp.php" file
original:
$this->smtp_conn =fsockopen(
$host,
$port,
$errno,
$errstr,
$timeout
);
change to:
$this->smtp_conn = #stream_socket_client(
$host,
$port,
$errno,
$errstr,
$timeout
);

Categories