DKIM not verified but dns record match key - phpmailer

Strugglign to get DKIM working. currently this is mail-tster result.
https://www.mail-tester.com/test-38w40jo78
im mainly missing the DKIM here is my dns records.
truebud.ca text = "truebud-64839v5873958h3ddrg._domainkey.truebud.ca k=rsa\; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChKyCHHZEkrYfTdcB2VX0nKL8Vhicb+xQsNswOgo5+IK2ipg97VJb+lKAT+jHMXyk4KPTkUUI/8rwa2IfUKsr/BQXy6csNkmM0Y00H5/+QRAYn+ktoRWO1zXvO2sygzCELgGxcj5pHkOd4xLGhTnTpHh7UAjTp" "/swV5E18dpAubQIDAQAB"
truebud.ca text = "v=DMARC1\; p=none"
truebud.ca text = "v=spf1 a mx ip4:216.221.70.222 ~all"
truebud.ca text = "_domainkey.truebud.ca o=~\; r=info#truebud.ca"
and here is my code for phpmailer
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
//use PHPMailer\PHPMailer\Exception;
require 'vendor/phpmailer/src/Exception.php';
require 'vendor/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/src/SMTP.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
$site = 'truebud.ca';
$sitename = 'Truebud';
try {
//Server settings
//$mail->isSMTP(); // Send using SMTP
$mail->Host = '216.221.70.222'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info#'.$site; // SMTP username
$mail->Password = '[pass]'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('info#'.$site,$sitename);
$mail->addAddress('test-38w40jo78#srv1.mail-tester.com');
$mail->addReplyTo('info#'.$site,$sitename);
$mail->addCC('cc#'.$site);
$mail->addBCC('bcc#'.$site);
// Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Truebud promotion';
$mail->Body = 'wall o' text';
$mail->AltBody = 'wall 'o text';
$mail->AddCustomHeader("List-Unsubscribe: <mailto:unsubscribe#".$site."?subject=Unsubscribe>,<http://".$site."/unsubscribe.php>");
$mail->DKIM_domain = $site;
$mail->DKIM_private = "rsa.private"; //path to file on the disk.
$mail->DKIM_selector = $sitename."-64839v5873958h3ddrg";// change this to whatever you set during step 2
$mail->DKIM_passphrase = "";
$mail->DKIM_identity = $mail->From;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Ive been at this for a week. What am i missing?

Their error says:
We were not able to retrieve your public key.
Please ensure that you inserted your DKIM TXT DNS record on your domain truebud.ca using the selector Truebud-64839v5873958h3ddrg.
I can see what's wrong — your DKIM DNS entry is incorrectly formatted.
# dig txt Truebud-64839v5873958h3ddrg._domainkey.truebud.ca
Truebud-64839v5873958h3ddrg._domainkey.truebud.ca. 120 IN TXT "truebud-64839v5873958h3ddrg._domainkey.truebud.ca v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChKyCHHZEkrYfTdcB2VX0nKL8Vhicb+xQsNswOgo5+IK2ipg97VJb+lKAT+jHMXyk4KPTkUUI/8rwa2IfUKsr/BQXy6csNkmM0Y00H5/+QRAYn+ktoRWO1zXvO2sygzCELgGxcj5pHkOd4xLGhTnT" "pHh7UAjTp/swV5E18dpAubQIDAQAB"
You've got the hostname inside the record value - it should start with v=DKIM1, like:
truebud.ca text = "v=DKIM1; k=rsa\; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChKyCHHZEkrYfTdcB2VX0nKL8Vhicb+xQsNswOgo5+IK2ipg97VJb+lKAT+jHMXyk4KPTkUUI/8rwa2IfUKsr/BQXy6csNkmM0Y00H5/+QRAYn+ktoRWO1zXvO2sygzCELgGxcj5pHkOd4xLGhTnTpHh7UAjTp" "/swV5E18dpAubQIDAQAB"
However, while I was testing that I saw you had changed it, so I guess you spotted the same mistake!

Related

problems with server SMTP PHPMailer

I have a problem with phpmailer, I have the correct SMPT server data and also the username and password, but it still marks me an error in the credentials, this is my code
<?php
include ("class.phpmailer.php");
include ("../vendor/phpmailer/phpmailer/PHPMailer.php");
include ("../vendor/phpmailer/phpmailer/src/SMTP");
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../vendor/phpmailer/phpmailer/src/Exception.php';
require '../vendor/phpmailer/phpmailer/src/PHPMailer.php';
require '../vendor/phpmailer/phpmailer/src/SMTP.php';
require '../vendor/autoload.php';
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Load Composer's autoloader
// Instantiation and passing `true` enables exceptions
$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 = 'admin#ucarolina.mx'; // SMTP username
$mail->Password = '******'; // SMTP password
$mail->SMTPSecure = 'TSL'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('luribe#qvoz.com');
$mail->addAddress($email, $name); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $contact_message;
$mail->AltBody = $contact_message;
$mail->send();
echo "Mensaje enviado";
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
and this is the error that marks me
SMTP Error: Could not authenticate.
Message could not be sent. Mailer Error: SMTP Error: Could not authenticate.
There is a line where SMTPSecure has to be specified. You have that line, but tls has been mistyped as TSL. Let's change that:
Change
$mail->SMTPSecure = 'TSL';
to
$mail->SMTPSecure = 'tls';
Additionally, you should add an if/then surrounding $mail->send(); like so:
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
If the mail is not sent, your if statement will catch that and report the error. See an example of such error handling in PHPMailer example: https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps

AddStringAttachment giving unusual results

I am sending attachments (CSV) which I have been sending for years using mail() but decided to migrate to SMTP for better reliability.
Code 1 (CSV attachment)
$attachment = $this->CSVData; // "Date","Name","Dept" ... \n"2019-03-13","Dave" ...
$encoding = 'base64';
$contentType = 'text/csv';
$filename = $this->createFileName(); //Get FileDate and Name
$recipient = $delivery_email; // xxxxxxx#gmail.com
$subject = $this->emailHeader['subject'] . " CSV Data";
$message = 'Daily Data File';
$mail = new PHPMailer\PHPMailer\PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = SMTP_HOST; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = SMTP_USER; // SMTP username
$mail->Password = SMTP_PASS; // SMTP password
$mail->SMTPSecure = SMTP_AUTH; // Enable TLS encryption, `ssl` also accepted
$mail->Port = SMTP_PORT; // TCP port to connect to
//Recipients
$mail->setFrom($this->fromEmail, $this->fromEmailName); // Add a FROM
$addresses = explode(',', $recipient);
foreach ($addresses as $address) {
$mail->AddAddress(trim($address)); // Add a recipient(s)
}
if ( !empty($this->emailCC) ) $mail->addCC($this->emailCC); // Add a CC
//13-03-2019: Add the attachment to the email
$mail->AddStringAttachment($attachment, $filename, $encoding, $contentType);
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'This email is formatted in HTML';
$mail->send();
$this->fo->printStatus('Email successfully sent to: '. $recipient );
return true;
} catch (Exception $e) {
$this->fo->printStatus( basename(__FILE__) .' '. __LINE__ . ': Message could not be sent. Mailer Error: '. $mail->ErrorInfo );
return false;
}
The email gets delivered to me BUT ...
Problems:
When viewing in Gmail browser - I get message: "
Gmail virus scanners are temporarily unavailable – The attached files haven't been scanned for viruses. Download these files at your own risk."
When viewing in Gmail browser - I cant save/download the file? (clicking the download button does nothing)
When clicking attachment to view in browser, I now get error: "Whoops. There was a problem while previewing this document"
I try "Show Original" and it takes 30+ seconds for the email to load which just shows the base64 encoded data
I tried to open in inbox in Outlook and after 5 minutes of the emails not loading I gave up (thinking the emails are not encoded properly or something causing outlook to get stuck)
It looks like it is working (i.e. the file looks legit based on the gmail icon preview) but I cant do anything else with it and I don't know if it is a Gmail issue or File Issue.
Any advice?
Turns out that Gmail was having issues all yesterday afternoon with attachments. It was a Gmail issue - The timing is unbelievable
https://www.theguardian.com/technology/2019/mar/13/googles-gmail-and-drive-suffer-global-outages

Failed to connect to server: Connection refused (111)

I am using PHPMailer to send the smtp emails. If I use the same setting in a WordPress site, it works fine. But my priority is to use in a custom php page. And there, it is giving the following errors
SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
My Code is here below
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'emails/PHPMailer/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)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//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 - likely to be 25, 465 or 587
$mail->Port = 587;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "mzubim#gmail.com";
$mail->Password = "password";
//Set who the message is to be sent from
$mail->setFrom('mzubim#gmail.com', 'Zubair Mushtaq');
//Set an alternative reply-to address
$mail->addReplyTo('replyto#gmail.com', 'Secure Developer');
//Set who the message is to be sent to
$mail->addAddress('abulogics#gmail.com', 'Abulogicss');
//Set the subject line
$mail->Subject = 'PHPMailer SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML("convert HTML into a basic plain-text alternative body");
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
try this its working fine
<?php
include "emails/PHPMailer/PHPMailerAutoload.php";
//Create a new PHPMailer instance
$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);
//Username to use for SMTP authentication
$mail->Username = "#gmail.com";
$mail->Password = "";
//Set who the message is to be sent from
$mail->setFrom('mzubim#gmail.com', 'Zubair Mushtaq');
//Set an alternative reply-to address
$mail->addReplyTo('replyto#gmail.com', 'Secure Developer');
//Set who the message is to be sent to
$mail->addAddress('abulogics#gmail.com', 'Abulogicss');
//Set the subject line
$mail->Subject = 'PHPMailer SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML("convert HTML into a basic plain-text alternative body");
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
the PHPMailer docs says that if it
-> //TCP port to connect to; use 587 if you have set SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS
And in your case u used ssl.
Consider increasing the debugging whilst you have the problem:
$mail->SMTPDebug = SMTP::DEBUG_LOWLEVEL ;
(see PHPMailer Debug messages)
My issue finally turned out to be the ports on my mail requesting server were not open to even get to the mail server (i.e. fix the firewall).

phpmailer not sending attachments

Does anybody have idea why my phpmailer dont want to send attachments? There are no errors, I tried every possible file location, and i'm still receiving just plain text mails...
require '../phpmailer/PHPMailerAutoload.php';
require '../phpmailer/class.phpmailer.php';
$mail = new PHPMailer;
// Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
// Specify main and backup SMTP servers
$mail->Host = 'serwerxxx.home.pl'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
// SMTP username
$mail->Username = 'my#mail'; // SMTP username // SMTP password
$mail->Password = 'mypass'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->From = 'my#mail.com';
$mail->FromName = 'Mailer';
// Add a recipient
$mail->addAddress('mail#mail'); // Name is optional
// Add attachments
$mail->AddAttachment("c20.jpg", "c20.jpg"); // Optional name // Set email format to HTML
//$mail->AddAttachment("c20.jpg");
//$mail->AddAttachment("../img/c20.jpg");
//$mail->AddAttachment($_SERVER['../img/c20.jpg']));
$mail->Subject = 'Here is the ółsubject'.$imie.' '.$nazwisko;
$mail->Body = 'das'.$format_wydruku1.' '.$ile1.'This is the HTML messagóóęęe body <b>in SŁŁŚŚśśśłłóó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';
}
Took me a while to figure this out too, for me it was a path problem - this solved it for me:
$mail->AddAttachment($_SERVER['DOCUMENT_ROOT']."/rest/of/your/path/to.pdf");

Having trouble with PHPMailer

I am trying to use PHPMailer to send a gmail email. I followed this post
In order to do this, I set up a function shown below:
function sendEmail($email, $name) {
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
//IsSMTP(); // send via SMTP I commented it cos it gives an error
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = 'email#gmail.com'; // Changed my email
$mail->Password = "password";// Changed my password
$mail->From = 'email#gmail.com';
$mail->FromName = 'FROM NAME';
$mail->AddAddress($email);
$mail->IsHTML(true); // send as HTML
$mail->Subject = "Subject";
$mail->Body = "Body";
if (!$mail->Send()) {
return false;
} else {
return true;
}
}
Unfortunately, it keeps on returning false. Can you please tell me whats wrong with the code?
Edit: The error which I am getting is shown below:
SMTP -> ERROR: Failed to connect to server: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
SMTP Error: Could not connect to SMTP host.
UPDATED CODE:
$Mail = new PHPMailer();
$Mail->IsSMTP(); // Use SMTP
$Mail->Host = "smtp.gmail.com"; // Sets SMTP server
$Mail->SMTPDebug = 2; // 2 to enable SMTP debug information
$Mail->SMTPAuth = TRUE; // enable SMTP authentication
$Mail->SMTPSecure = "tls"; //Secure conection
$Mail->Port = 587; // set the SMTP port
$Mail->Username = EMAIL; // SMTP account username
$Mail->Password = PASS; // SMTP account password
$Mail->Priority = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
$Mail->CharSet = 'UTF-8';
$Mail->Encoding = '8bit';
$Mail->Subject = 'SUB';
$Mail->ContentType = 'text/html; charset=utf-8\r\n';
$Mail->From = EMAIL;
$Mail->FromName = 'FROM NAME';
$Mail->WordWrap = 900; // RFC 2822 Compliant for Max 998 characters per line
$Mail->AddAddress($email); // To:
$Mail->isHTML(TRUE);
$Mail->Body = "Hi";
$Mail->AltBody = "Hi";
$Mail->Send();
$Mail->SmtpClose();
Here is a working example:
<?php
function SendMail( $ToEmail, $MessageHTML, $MessageTEXT ) {
require_once ( 'class.phpmailer.php' ); // Add the path as appropriate
$Mail = new PHPMailer();
$Mail->IsSMTP(); // Use SMTP
$Mail->Host = "smtp.gmail.com"; // Sets SMTP server
$Mail->SMTPDebug = 2; // 2 to enable SMTP debug information
$Mail->SMTPAuth = TRUE; // enable SMTP authentication
$Mail->SMTPSecure = "tls"; //Secure conection
$Mail->Port = 587; // set the SMTP port
$Mail->Username = 'MyGmail#gmail.com'; // SMTP account username
$Mail->Password = 'MyGmailPassword'; // SMTP account password
$Mail->Priority = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
$Mail->CharSet = 'UTF-8';
$Mail->Encoding = '8bit';
$Mail->Subject = 'Test Email Using Gmail';
$Mail->ContentType = 'text/html; charset=utf-8\r\n';
$Mail->From = 'MyGmail#gmail.com';
$Mail->FromName = 'GMail Test';
$Mail->WordWrap = 900; // RFC 2822 Compliant for Max 998 characters per line
$Mail->AddAddress( $ToEmail ); // To:
$Mail->isHTML( TRUE );
$Mail->Body = $MessageHTML;
$Mail->AltBody = $MessageTEXT;
$Mail->Send();
$Mail->SmtpClose();
if ( $Mail->IsError() ) { // ADDED - This error checking was missing
return FALSE;
}
else {
return TRUE;
}
}
$ToEmail = 'Name#example.com';
$ToName = 'Name';
$Send = SendMail( $ToEmail, $MessageHTML, $MessageTEXT );
if ( $Send ) {
echo "<h2> Sent OK</h2>";
}
else {
echo "<h2> ERROR</h2>";
}
die;
?>
I tried this script and had no problem sending several messages.
UPDATED:
This is the typical response from Gmail on success:
SMTP -> FROM SERVER:220 mx.google.com ESMTP 20sm6345523qek.6
SMTP -> FROM SERVER: 250-mx.google.com at your service, [181.155.13.39]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250 ENHANCEDSTATUSCODES
SMTP -> FROM SERVER:220 2.0.0 Ready to start TLS
SMTP -> FROM SERVER: 250-mx.google.com at your service, [181.155.13.39]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2
250 ENHANCEDSTATUSCODES
SMTP -> FROM SERVER:250 2.1.0 OK 20sm6345523qek.6
SMTP -> FROM SERVER:250 2.1.5 OK 20sm6345523qek.6
SMTP -> FROM SERVER:354 Go ahead 20sm6345523qek.6
SMTP -> FROM SERVER:250 2.0.0 OK 1353474062 20sm6345523qek.6
SMTP -> FROM SERVER:221 2.0.0 closing connection 20sm6345523qek.6
Your Code is not working because you did not set the SMTPSecure option to ssl which is required for gmail account
include_once "/lib/phpmailer/PHPMailer.class.php";
include_once "/lib/phpmailer/SMTP.class.php";
include_once "/lib/phpmailer/POP3.class.php";
$mail = new PHPMailer(true);
$mail->IsSMTP();
try {
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 2;
$mail->SMTPSecure = 'ssl'; //<----------------- You missed this
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; //
$mail->Username = "xxxxxx#gmail.com";
$mail->Password = "xxxxxx";
$mail->AddAddress('to#example.com', 'John Doe');
$mail->SetFrom('xxxxxx#gmail.com', 'First Last');
$mail->Subject = 'This is a TEST message';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
$body = "To view the message, please use an HTML compatible email viewer!"; // automatically
$mail->MsgHTML($body);
$mail->Send();
echo "Message Sent OK</p>\n";
} catch ( phpmailerException $e ) {
echo $e->errorMessage();
} catch ( Exception $e ) {
echo $e->getMessage();
}
Output
SMTP -> FROM SERVER:220 mx.google.com ESMTP q22sm2927759bkv.16
SMTP -> FROM SERVER: 250-mx.google.com at your service, [62.173.54.190] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 250 ENHANCEDSTATUSCODES
SMTP -> FROM SERVER:250 2.1.0 OK q22sm2927759bkv.16
SMTP -> FROM SERVER:250 2.1.5 OK q22sm2927759bkv.16
SMTP -> FROM SERVER:354 Go ahead q22sm2927759bkv.16
SMTP -> FROM SERVER:250 2.0.0 OK 1353341553 q22sm2927759bkv.16
Message Sent OK
In such kinds of issues it is important to check how it runs on development environment before you deploy to production, since there are many server issues that might be related to the problem.
Because of that before anything set debug to true and check the messages you get.
$mail->SMTPDebug = 1;
That said, common server issues in such situations are the following.
Lack of SSL support in PHP. You must enable it.
Some kind of firewall might be blocking you from connecting to outbound sockets. You can check that using PHP.
-
$p = fsockopen( '127.0.0.1', <port number>, $errno, $errstr, 5 );
if ( !$p )
// port is closed or blocked
else
// port is open and available
fclose( $p );`
Try...
<?php
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$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 = "smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "smtp.gmail.com"; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->AddAddress('whoto#otherdomain.com', 'John Doe');
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->Subject = 'This is a TEST Message';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($obdy);
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Just replace with your configuration, set the require_once('class.phpmailer.php'); to point to the right place and replace 'contents.html' your HTML template.
or
Use this code if you choose not to use an HTML template...
<?php
$body ='Your HTML message should go here';
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$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 = "smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "smtp.gmail.com"; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->AddAddress('whoto#otherdomain.com', 'John Doe');
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->Subject = 'This is a TEST message';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPDebug = 0; // This will print debugging info
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "tls"; // Connect using a TLS connection
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Encoding = '7bit'; // SMS uses 7-bit encoding
$mail->IsHTML(true); // Set email format to HTML
// Authentication
$mail->Username = "xxx#xxx.xxx.xx"; // Login
$mail->Password = "xxxxxx"; // Password
//$to=
$to = "zzz#zzz.zzz.zz";
$mail->Subject = "Outstanding Balance Notification "; // Subject (which isn't required)
$mail->Body = "Dear Sir / Madam";
$mail->FromName = "stackoverflow";
$mail->From = "noreply#xxx.xxx.xx";
$mail->AddAddress($row["Email1"]);
try this.. :)
I have send mail from xampp server from localhost
This code is perfectly work for me
1: down load phpmailer from https://github.com/PHPMailer/PHPMailer
2: go to xampp and search php.ini
3 In php.ini search
;extension=php_openssl.dll
remove(;)
extension=php_openssl.dll
then save and restart p.c. its work
<%php <br/>
require_once("C:\\xampp\\phpMailer\\PHPMailer-master\\class.phpmailer.php"); <br/>
$mail = new PHPMailer(); <br/>
$mail->IsSMTP(); // telling the class to use SMTP <br/>
$mail->SMTPAuth = true; // Enable SMTP authentication <br/>
$mail->SMTPSecure = 'ssl' ; <br/>
$mail->Host = "smtp.gmail.com" ;// SMTP server <br/>
$mail->Port = 465; // or 587 <br/>
$mail->Username = 'senderemailid#gmail.com'; // SMTP username <br/>
$mail->Password = 'senderpassword'; // SMTP password <br/>
$mail -> IsHTML(true); <br/>
$mail->From = 'senderemailid#gmail.com'; <br/>
$mail->FromName = 'sendername'; <br/>
$mail->addAddress('receiveremailid#domain.com','receivername'); <br/>
$mail->WordWrap = 50; <br/>
$mail->Subject = "This mail send from PhP code xampp"; <br/>
$mail->Body = "Hi! \n\n This is my first e-mail sent through PHPMailer."; <br/>
if(!$mail->Send()) { <br/>
echo 'Message was not sent.'; <br/>
echo 'Mailer error: ' . $mail->ErrorInfo; <br/>
} else <br/>
{ <br/>
echo 'Message has been sent.'; <br/>
} <br/>
?> <br/>
2019 Update phpMailer with Gmail
I know this is an old question but it still comes up in Google and I need to update the answer to this.
If you are experience the issue (where many do) with phpmailer that it only works when you comment out IsSMTP() when trying to use gmail's SMTP then here is why.
When you comment out IsSMTP() you are telling phpmailer NOT TO USE SMTP which by default phpmailer will send the request to your local mail() instead. If you look at the emails sent at this point and look at the header of the email you will see that it is coming from your local server and not the address/domain you are trying to send it as. So yes commenting out IsSMTP() will make it work, but it really isn't. And sending from your local server that is not setup correctly will most likely result in your emails going to spam.
So how do I fix this
Plain and simple you most likely are using an old version of phpmailer, you need a newer version. The easy way to tell this is how you set your From address. If it looks like this $mail->From = "name#example.com" then you are using an old version.
The newest versions of phpmailer defines From as $mail->setFrom("name#example.com", "First Last"). If you see that then you are using a newer version of phpmailer.
How to do it right and actually make it work
Please make sure that you have TCP OUT port for 587 on your firewall
SMTP Gmail will only work with tls/587 AND NOT ssl/465 (ssl is 1990's)
Make sure that you have allow less secure apps set correctly within gmail. If you are using a G Suite account then you will have to have your admin enable it if it isn't already.
This is a perfect example how to use the new phpmailer with gmail smtp (and yes it does work, if not then something is wrong on your end)
How to install phpmailer
First download the latest version of phpmailer
There are 2 ways to install it. Composer or manual. The manual way all you need is
use PHPMailer\PHPMailer\PHPMailer; <-- make sure these are not in a function
use PHPMailer\PHPMailer\Exception;
require 'path/src/Exception.php';
require 'path/src/PHPMailer.php';
require 'path/src/SMTP.php';
EXAMPLE
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
* This uses traditional id & password authentication - look at the gmail_xoauth.phps
* example to see how to use XOAUTH2.
* The IMAP section shows how to save this message to the 'Sent Mail' folder using IMAP commands.
*/
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'path/src/Exception.php';
require 'path/src/PHPMailer.php';
require 'path/src/SMTP.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//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";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//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');
//Set who the message is to be sent to
$mail->addAddress('whoto#example.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), __DIR__);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
//Section 2: IMAP
//Uncomment these to save your message in the 'Sent Mail' folder.
#if (save_mail($mail)) {
# echo "Message saved!";
#}
}
//Section 2: IMAP
//IMAP commands requires the PHP IMAP Extension, found at: https://php.net/manual/en/imap.setup.php
//Function to call which uses the PHP imap_*() functions to save messages: https://php.net/manual/en/book.imap.php
//You can use imap_getmailboxes($imapStream, '/imap/ssl') to get a list of available folders or labels, this can
//be useful if you are trying to get this working on a non-Gmail IMAP server.
function save_mail($mail)
{
//You can change 'Sent Mail' to any other folder or tag
$path = "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail";
//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;
}
?>

Resources