So as the title implies
Im trying to send an email (one email) but the problem I'm facing is bizarre.
Whenever debug is turned on, email is sent only once.
But when debug is turned off, around 3 to 4 emails are sent at once.
NOTE: I'm using localhost not an actual server.
to diagnose the problem, I did the following:
1- used a md5 to generate random string in the "subject" to check whether email is sent with same contents or different. and the results were totally different. meaning, emails weren't duplicate but actually being sent couple of times.
2- opened the project in a browser with no extensions to make sure the problem wasn't in an extension loading my project page more than once. and the results were also similar to number 1, different "subject" also.
so, long story shot. i have no idea what causes this problem to happen. and why it only stop happening when debug is turned on.
NOTE: this is not my first time to use PHP mailer, but my first time to face this problem. I'm also using the latest version of PHP mailer (6.5.1)
Here is my entire code:
in PHP mailer file:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
require ABSPATH.'inc/phpmailer/script/src/PHPMailer.php';
require ABSPATH.'inc/phpmailer/script/src/Exception.php';
require ABSPATH.'inc/phpmailer/script/src/SMTP.php';
function SendEmail(){
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_OFF;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->isSMTP();
$mail->Host = '*****';
$mail->SMTPAuth = true;
$mail->Username = '*****';
$mail->Password = '*****';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->SMTPAutoTLS = false;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->ClearAllRecipients();
$mail->clearAttachments();
//Recipients
$mail->setFrom('*****', '******');
$mail->addAddress('*******', '*****');
$mail->addReplyTo('******', '******');
//Attachments
$mail->addAttachment(ABSPATH.'upload/dog.jpg', 'new.jpg');
//Content
$mail->isHTML(true);
$mail->Subject = md5(rand()); //This is how I'm checking whether it sends same email with same subject header or different ones. and it does send different ones
$mail->Body = 'This is the HTML message body <b>in bold!</b>'. md5(rand());
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->ContentType = 'text/html; charset=utf-8\r\n';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
and here is the file I'm using to call the function
<?PHP
// NO LOOP here
require_once(ABSPATH.'inc/phpmailer/phpmailer.php');
SendEmail();
As always, the first place to check is the docs.
Since you've already tried the random hash in the subject trick (well done on your logic!), you know that the problem is not that your script is sending more than one message, but that your script is being called repeatedly, and you should see evidence of that in your web server logs too. The usual reason for this is browser extensions which have a nasty habit of doing multiple submissions. Test that by using a clean browser with no extensions (e.g. use a browser you don't normally use, like Opera, Brave, or Chrome Canary).
Any requests that your browser is making should appear in the network tab of the dev console. On the server side you can either set up remote debugging to trigger breakpoints (tricky), or var_dump every request to a log so you get full details of what's calling the script.
BTW, you really shouldn't be disabling TLS verification. Fix the problem properly instead of hiding it; the troubleshooting guide has lots on that subject.
I had the same issue and solved by upgrading to the latest version of PHPMailer.
Related
So i just received this error when trying to send an mail using PHPmailer from my site.
SMTP Error: The following recipients failed: XXXX
I tried to set $mail->SMTPAuth = true; to false but no result. And i tried to change the password for the mail account and update that in the sendmailfile.php but still the same.
It worked as intended two days ago, now i don't know why this is happening. Since there ain't any error code either i don't really know where to begin and since it did work..
Anyone who might know?
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->ContentType = 'text/html';
$mail->IsSMTP();
$mail->Host = "HOST.COM";
$mail->SMTPAuth = true;
$mail->Username = "MAIL_TO_SEND_FROM";
$mail->Password = "PASSWORD";
$mail->From = "MAIL_TO_SEND_FROM";
$mail->FromName = "NAME";
$mail->AddAddress($safeMail);
$mail->AddReplyTo("no-reply#example.COM", "No-reply");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$sub = "SUBJECT";
mail->Subject = ($sub);
I've encountered the same problem. Managed too fix it when i commented the next row:
$mail->isSMTP();
Noticed you already found an answer, however maybe this will fix the problem for other people.
This does prevent using your external SMTP server as RozzA stated in the comments.
Maybe your class.phpmailer.php file is corrupt. Download the latest version from :
https://github.com/PHPMailer/PHPMailer
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
It is a restriction from your SMTP server.
Sending e-mail messages is a vital part of the ever-growing Internet business. Sometimes, a large number of e-mails are required to be sent daily, even hourly. With this comes also the ever-increasing problem with the e-mail spam, and the countless number of junk messages users receive constantly.
The most common restrictions are:
150 e-mails per hour;
1500 e-mails per 24 hours;
50 recipients per message, where each recipient is counted as a separately sent e-mail message (e.g. if you have 50 recipients in a single message, this willcount as 50 sent messages);
One solution is to use a mailing list, then the restriction is 1500 e-mails for 24 hours. There's no restriction for the amount of emails sent per hour, i.e. you can send an email to a mailing list with up to 1500 recipients without a problem.
If you reach the hourly/daily limit you will get this error when trying to send further e-mails:
550 - Stop, you are sending too fast!
You will be able to send e-mails again, once the hour/day has passed.
Things you should know in order to avoid exceeding your limit:
The above e-mail restrictions are valid for the entire hosting account, and not for a single mailbox. This means, that if one of your mailboxes exceeds the allowed limit, you will not be able to send messages from any of your other e-mail accounts.
If, at any point you receive the afore-mentioned error message, it is highly recommended to stop all attempts to send messages from your mailboxes. If you continue trying, your messages will be left in a mail queue, which will have to clear first, before the server timer can reset and allow you to send e-mails again.
try inlcuding this
$mail->SMTPDebug = 1;
Just try to set SMTPAuth to false.
there is a slightly less probable problem.maybe this condition is caused by protection placed by your ISP.and you said it worked well two days ago.maybe that is the problem.try contacting your ISP.
or maybe its a problem with the recipients/senders email adresses
Here is some additional info about SMTP Auth
PLAIN (Uses Base64 encoding.)
LOGIN (Uses Base64 encoding.)
e.t.c - you can watch here http://en.wikipedia.org/wiki/SMTP_Authentication
For me solution was to set SMTPAuth to true for PHPMailer class
Please note in your lines i.e....
$mail->Username = "MAIL_TO_SEND_FROM";
$mail->Password = "PASSWORD";
$mail->From = "MAIL_TO_SEND_FROM";
Here at Line 1 and 3 you have to use same email address (You can't use different email address), this will work sure, I hope u r using different email address, (Email address must be same as username/password matching).
for Skip sending emails to invalid adresses; use try ... catch
$mail=new PHPMailer(true);
try {
$mail->CharSet = 'utf-8';
$mail->isSMTP();
$mail->isHTML(true);
$mail->Host = 'smtp.yourhost.com';
$mail->Port = 25;
$mail->SMTPAuth = false;
$mail->Username = 'xxxx';
$mail->Password = 'xxxx';
$mail->SMTPSecure = 'tls';
$mail->SMTPDebug = 0;
$mail->MailerDebug = false;
$mail->setFrom($absender, $name);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->Body = $message_other_player;
}
$mail->send();
// echo 'Message has been sent';
} catch (Exception $e) {
// echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
PHPMailer - Skip sending emails to invalid adresses
I've been trying to get my PhpMailer to work for over a week now.
I'm on a Windows machines, so I set up a "droplet" server with DigitalOcean (because they seem to have good step-by-step instructions) and then set up fake email accounts with ZohoMail (because it's free and I just need to test this.)
I've got breaks all over the three PhpMailer files I need (PhpMailerAutoload.php, class.phpmailer.php, and class.smtp.php). What I figured out is that I'm getting hung up on this line:
class.smtp.php line 1060 (or about since I've got breaks in there)
inside function get_lines:
$str = #fgets($this->smtp_conn, 515);
I put in more breaks, as below:
//*********Debug Code here
$test = $this->smtp_conn;
echo "\nContents of test var: \n";
var_dump($test);
echo "about to set str var \n";
$str = #fgets($test, 515);
echo "Contents of str var \n";
var_dump($str);
echo "\n out of debug code";
//***********End of debug code
After two minutes (2 minutes and 5 seconds to be precise) $test var_dumps just fine and "about to set str var" prints just fine.
But that's it. No more code executes.
I don't know what #fgets is. I don't see any documentation in the PHP manual for that, so I'm not sure where to go from here.
FIRST IDEA:
I checked on my php versions:
- server is running 5.5.9
- my PC is running 5.6.12
I'm guessing those are close enough.
SECOND IDEA:
I found that in the past there are a "==" vs "=" issue with this line of code, but that's clearly not the issue here.
THIRD IDEA:
I also read that some people fixed this problem by making sure that "php_openssl.dll" is enabled in their php.ini file.
In mine I have a line that reads:
extension = php_openssl.dll
So I think that's OK.
FOURTH IDEA:
Is my configuration wrong?
I'm using the following:
SMTP Host: smtp.zoho.com (should I get the IP address instead?)
SMTP Port: 465
and I think I have encryption and authentication turned on. (My code is at the end if that helps.)
FIFTH IDEA:
Start over using gmail to see if that gives me any clues, unless someone has a better idea.
function send_SMTP_email($email, $name, $subject, $msg) {
//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't have access to that
date_default_timezone_set('Etc/UTC');
require_once '/inc/phpmailer/PHPMailerAutoload.php'; // will load class.phpmailer.php and class.smtp.php itself
require_once '/inc/config.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging, TO DO: Disable for production
// 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_HOST;
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = SMTP_PORT;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = SYSTEM_EMAIL;
//Password to use for SMTP authentication
$mail->Password = SYSTEM_PASSWORD;
//Set who the message is to be sent from
$mail->setFrom(SYSTEM_EMAIL, SYSTEM_NAME);
//Set an alternative reply-to address
$mail->addReplyTo(SYSTEM_EMAIL, SYSTEM_NAME);
//Set who the message is to be sent to
$mail->addAddress($email, $name);
//Set the subject line
$mail->Subject = $subject;
//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'), dirname(__FILE__));
//Send HTML OR Plain Text
$mail->isHTML(true);
//Set body
$mail->Body = "<p>" . $msg . "</p>";
//Include plain text if non-HTML email reader
$mail->AltBody = $msg;
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
$result = $mail->send();
//send the message, check for errors
//if (!$mail->send()) {
if (!$result) {
$return_val = "Mailer Error: " . $mail->ErrorInfo;
} else {
$return_val = "";
}
return $return_val;
}
I just had the same problem and finally found the problem. The default is set to TLS. Once I changed it to SSL with
$mail->SMTPSecure = 'ssl';
everything worked fine. Hopes this helps, if anyone else faces the same issue.
So i just received this error when trying to send an mail using PHPmailer from my site.
SMTP Error: The following recipients failed: XXXX
I tried to set $mail->SMTPAuth = true; to false but no result. And i tried to change the password for the mail account and update that in the sendmailfile.php but still the same.
It worked as intended two days ago, now i don't know why this is happening. Since there ain't any error code either i don't really know where to begin and since it did work..
Anyone who might know?
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->ContentType = 'text/html';
$mail->IsSMTP();
$mail->Host = "HOST.COM";
$mail->SMTPAuth = true;
$mail->Username = "MAIL_TO_SEND_FROM";
$mail->Password = "PASSWORD";
$mail->From = "MAIL_TO_SEND_FROM";
$mail->FromName = "NAME";
$mail->AddAddress($safeMail);
$mail->AddReplyTo("no-reply#example.COM", "No-reply");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$sub = "SUBJECT";
mail->Subject = ($sub);
I've encountered the same problem. Managed too fix it when i commented the next row:
$mail->isSMTP();
Noticed you already found an answer, however maybe this will fix the problem for other people.
This does prevent using your external SMTP server as RozzA stated in the comments.
Maybe your class.phpmailer.php file is corrupt. Download the latest version from :
https://github.com/PHPMailer/PHPMailer
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
It is a restriction from your SMTP server.
Sending e-mail messages is a vital part of the ever-growing Internet business. Sometimes, a large number of e-mails are required to be sent daily, even hourly. With this comes also the ever-increasing problem with the e-mail spam, and the countless number of junk messages users receive constantly.
The most common restrictions are:
150 e-mails per hour;
1500 e-mails per 24 hours;
50 recipients per message, where each recipient is counted as a separately sent e-mail message (e.g. if you have 50 recipients in a single message, this willcount as 50 sent messages);
One solution is to use a mailing list, then the restriction is 1500 e-mails for 24 hours. There's no restriction for the amount of emails sent per hour, i.e. you can send an email to a mailing list with up to 1500 recipients without a problem.
If you reach the hourly/daily limit you will get this error when trying to send further e-mails:
550 - Stop, you are sending too fast!
You will be able to send e-mails again, once the hour/day has passed.
Things you should know in order to avoid exceeding your limit:
The above e-mail restrictions are valid for the entire hosting account, and not for a single mailbox. This means, that if one of your mailboxes exceeds the allowed limit, you will not be able to send messages from any of your other e-mail accounts.
If, at any point you receive the afore-mentioned error message, it is highly recommended to stop all attempts to send messages from your mailboxes. If you continue trying, your messages will be left in a mail queue, which will have to clear first, before the server timer can reset and allow you to send e-mails again.
try inlcuding this
$mail->SMTPDebug = 1;
Just try to set SMTPAuth to false.
there is a slightly less probable problem.maybe this condition is caused by protection placed by your ISP.and you said it worked well two days ago.maybe that is the problem.try contacting your ISP.
or maybe its a problem with the recipients/senders email adresses
Here is some additional info about SMTP Auth
PLAIN (Uses Base64 encoding.)
LOGIN (Uses Base64 encoding.)
e.t.c - you can watch here http://en.wikipedia.org/wiki/SMTP_Authentication
For me solution was to set SMTPAuth to true for PHPMailer class
Please note in your lines i.e....
$mail->Username = "MAIL_TO_SEND_FROM";
$mail->Password = "PASSWORD";
$mail->From = "MAIL_TO_SEND_FROM";
Here at Line 1 and 3 you have to use same email address (You can't use different email address), this will work sure, I hope u r using different email address, (Email address must be same as username/password matching).
for Skip sending emails to invalid adresses; use try ... catch
$mail=new PHPMailer(true);
try {
$mail->CharSet = 'utf-8';
$mail->isSMTP();
$mail->isHTML(true);
$mail->Host = 'smtp.yourhost.com';
$mail->Port = 25;
$mail->SMTPAuth = false;
$mail->Username = 'xxxx';
$mail->Password = 'xxxx';
$mail->SMTPSecure = 'tls';
$mail->SMTPDebug = 0;
$mail->MailerDebug = false;
$mail->setFrom($absender, $name);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->Body = $message_other_player;
}
$mail->send();
// echo 'Message has been sent';
} catch (Exception $e) {
// echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
PHPMailer - Skip sending emails to invalid adresses
I recently moved from windows shared hosting to a VPS. I'm struggling to get phpmailer to work for a contact form on my website.
The code for my site the sets up the email to send is:
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "smtp.gmail.com"; // specify main and backup server or localhost
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->SMTPSecure = "tls";
$mail->SMTPDebug = 1; // can vary the amount of debug info given on error
$mail->Username = "mail#mydomain.com"; // SMTP username
$mail->Password = "########"; // SMTP password
$mail->Port = 587;
This code worked on the old windows shared hosting. Also everything else is identical too with the site (the class.phpmailer.php file etc)
So I'm guessing it's something to do with my setup of iis or the server itself.
Connecting out works on port 587 according to my webhosts who checked that for me
I installed php using the Microsoft tool that does everything for you. the site is in php and is working, and it looks to my untrained eye like all is fine there.
I've checked that php_openssl.dll is enabled.
I've spent a long time reading around and fiddling with no luck. I'm really at a loss as what to look at next. Any ideas what it could be or what I should try?
thanks!
Phil.
EDIT:
The action on the php form is to go to contactprocessor.php.
That file contains this code:
<?
ob_start();
if(isset($_POST['btnSubmit']))
{
require("class.phpmailer.php");
$mail = new PHPMailer();
//Your SMTP servers details
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "smtp.gmail.com"; // specify main and backup server or localhost
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->SMTPSecure = "tls";
$mail->SMTPDebug = 1; // can vary the amount of debug info given on error
$mail->Username = "mail#mydomain.com"; // SMTP username
$mail->Password = "########"; // SMTP password
$mail->Port = 587;
$redirect_url = "http://www.mydomain.com/contact/contact_success.php"; //Redirect URL after submit the form
$mail->From = $mail->Username; //Default From email same as smtp user
$mail->FromName = "Website Contact Form";
$mail->AddAddress("mail#mydomain.com", "From Contact Form"); //Email address where you wish to receive/collect those emails.
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "From Contact Form";
$message = "FullName: ".htmlspecialchars($_POST['fullname'])." <br> <br>
\r\n <br>EmailAddress: ".htmlspecialchars($_POST['email'])." <br> <br>
\r\n <br>Phone Number: ".htmlspecialchars($_POST['mobile'])." <br> <br>
\r\n <br> Message: <br>".htmlspecialchars($_POST['message']);
$mail->Body = $message;
if(!$mail->Send())
{
echo "Sorry the message could not be sent. Please email mail#mydomain.com instead. Thanks<p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
header("Location: $redirect_url");
}
?>
Instead of actually sending the email, it just seems to print the above to screen of the user as if it's a webpage. it's as if the server thinks it's a html page and is just serving it.
You wrote:
Instead of actually sending the email, it just seems to print the above [code] to screen of the user as if it's a webpage. it's as if the server thinks it's a html page and is just serving it.
I think your problem is unrelated to phpMailer, or indeed email at all.
This is almost certain to be simply a small difference between the PHP configuration on your old and new servers.
Your PHP code is using the short-style PHP tags -- ie starting with <?.
Many PHP servers are configured not to allow this short-style tag, and only run PHP code that starts with the full <?php tag.
Given what you stated in the remark I quoted above, I suspect this is your problem, because what you describe is exactly the symptom I would expect from that.
You have two options:
Change your code to use the long style <?php tag.
Change your server config to allow the short <? tag.
I would recommend taking option (1) if possible, because the long-form tags are considered best practice (the short form is not recommended because it can have a potential clash with the <?xml marker at the start of most XML documents).
If you have a lot of short-form <? tags (and assuming you're allowed to do so), changing the server config may be worth considering, but if it's easy enough to fix the problem by switching to long tags, I'd say that would be better.
Hope that helps.
Thanks to Spudley for the answer. I had <? at the start (which is a shorthand that doesn't work on new php installations apparently). It should be <?php that's made it work. Thanks again.
I've used PHP to send emails before but never to send a full HTML page from another source and so I'm wondering where to start and a few other things.
I did a bit of research but my confusion isn't clearing up any.
Do I directly get the web-page contents and send that or can I use a setting to just use a URL?
What is the simplest method I could use and could someone show me an example?
Are there risks with sending an email like this to say... 5000 people and how do I change the header data with a return link to URL source?
The following line get the contents of a HTML page.
$mail->MsgHTML(file_get_contents('contents.html'));
Go here for full details:
http://phpmailer.worxware.com/index.php?pg=exampleagmail
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 = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "tls"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "yourusername#gmail.com"; // GMAIL username
$mail->Password = "yourpassword"; // GMAIL 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 = 'PHPMailer Test Subject via mail(), advanced';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML(file_get_contents('contents.html'));
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
Disclaimer: I can't yet comment, so please forgive this being an "answer".
I think you're probably going to have to clarify your objectives a little bit here.
It sounds like what you want to do is first build a basic scraper unless you have access to the raw html file.
Basically you can use fopen("Url", "r"), fsockopen("url", 80), or use a curl handler to submit the page request.
From here, depending on your method, you would read the response and generate an HTML or multi-part e-mail.
As far as adding a link to the e-mail header, you can do that, but I have a feeling it's not going to do what you want it to. The way to do it will depend on how you decide to send the e-mail.
Ives' answer is nice.
There is one gotcha you really want to consider with emailing an html page.
Html emails and Html pages are two totally different school.
Html emails take you back 10 years (hello tables!) in what you can do to support as many email clients as possible.
It's very likely a straight email-a-webpage thing will look total crap on the recipient email..
and then you've got to consider embedding stylesheets, etc..