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.
Related
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.
I'm using PHPMailer (Version 5) for user registration. (When user registers to my site the Profile activation code is sent to user to activate it).
PHPMailer works, I tested it many times (I registered Myself with other mails and with gmail too for testing purposes, I always got the activation code), but many users complain that they not getting the activation codes and then I have to send them manually...
I can't understand what is the problem (When I checked my users database there are many users that got activation codes, but also that couldn't received).. I debug PHPMailer, but there is not any error or problem...
I'm Using PHPMailer With Gmail SMTP:
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "mymail#gmail.com";
$mail->Password = "MyPassword";
$mail->From = "mymail#gmail.com";
$mail->FromName = 'www.mysite.com';
$mail->AddAddress($email);
$mail->WordWrap = 80;
$mail->IsHTML(true);
$mail->Subject = 'Registration';
$mail->Body = $message;
$mail->AltBody = $message;
$mail->Send();
I also tried to use SSL-465, but the result is the same..
Please Help!
Thank you very much in advanced...
I Solved this problem from server (host). I checked mail functions / configs and found "MAX_EMAIL_PER_HOUR" was set to 30 (Really strange, by default It is 100) So I changed it to 500 and It fixed all PHPMailer Issues...
In addition:
Enabling "Allow less secure apps" will usually solve many problem for PHPMailer, and it does not really make your app significantly less secure. (When enabling Google warns you that the App is insecure).
If you Need More security, PHPMailer added support for XOAUTH2 for google, you can use it...
I haven't used this technology before, but I'll play with it as soon as possible ;)
With Best Wishes!
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.
I created a form that uses phpMailer to email the results to the website owner. Of course, before I add the owner's email address I use mine to test that the form works. When I use my email the form sends perfectly, however, when I use the owner's address it throws the error "could not instantiate mail function" and won't send the form. The error only occurs with email addresses associated with the owner's domain. Any idea why this could be happening?
If I type this into the command line it works fine:
echo 'test' | mail -s 'test' me#example.com
edit: I wasn't initially using SMTP, but it's now configured as shown below. The error message is now "SMTP Error: The following recipients have failed xxx#somedomain.com" and the end result is still the same. It can e-mail to a number of gmail test addresses but has issue with the owner's email#hisdomain.com. Further, with SMTPDebug it's now producing the error "RCPT TO command failed: 550 No Such User Here" The owner's e-mail, however, works without issue when e-mailed through gmail, outlook, etc.
phpMailer code:
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->Debugoutput = "error_log";
$mail->Host = "mail.mydomain.com";
$mail->SMTPAuth = true;
$mail->Username = "admin#mydomain.com";
$mail->Password = "XXXXXXXXXXXXXXX";
$mail->CharSet = 'UTF-8';
$mail->AddReplyTo($emailAddress);
$mail->SetFrom("admin#mydomain.com");
$mail->AddAddress($toAddress,$toName);
$mail->Subject = $emailSubject;
$mail->isHTML(true);
$mail->Body = $emailBody;
$mail->AltBody = strip_tags($emailBody);
// Attempt to send the e-mail
if (!$mail->send()) {
//error handling
}
There are couple of things you should try and check with this particular error message:
Make sure you can use regular php mail() function. Create a blank page and use the php mail() to send a test email. If that works, maybe its your SMTP that's having issues with the particular user domain. Setup gmail SMTP or a different SMTP to send emails:
$mail->IsSMTP();
$mail->Host = "smtp.domain.com";
// optional
// used only when SMTP requires authentication
$mail->SMTPAuth = true;
$mail->Username = 'smtp_username';
$mail->Password = 'smtp_password';
Can you share your phpMailer source for us to view?
Set $mail->SMTPDebug = 2; so you can see what the server has to say, and read the troubleshooting guide.
You're using authentication without encryption, which is not a good combination and many servers won't allow that. Add this:
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
You've based your code on an old example, so you're probably using an old version of PHPMailer too; get the latest from github.
Hello I am trying to get a website up and running. It is currently hosted on AWS, so I do not have my own smtp server running at this moment. So after reading a few articles, I have understood that we could used gmail as a smtp server.
I wanted to double check if what I read was right, I am going to use smart job board software, can I plug in the values provided by gmail and use that as an smtp server??
Yes, Google allows connections through their SMTP and allows you to send emails from your GMail account.
There are a lot of PHP mail scripts that you can use. Some of the most popular SMTP senders are: PHPMailer (with an useful tutorial) and SWIFTMailer (and their tutorial).
The data you need to connect and send emails from their servers are your GMail account, your password, their SMTP server (in this case smtp.gmail.com) and port (in this case 465) also you have to make sure that emails are being sent over SSL.
A quick example of sending an email like that with PHPMailer:
<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // SMTP authentication
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Port = 465; // SMTP Port
$mail->Username = "john.doe#gmail.com"; // SMTP account username
$mail->Password = "your.password"; // SMTP account password
$mail->SetFrom('john.doe#gmail.com', 'John Doe'); // FROM
$mail->AddReplyTo('john.doe#gmail.com', 'John Doe'); // Reply TO
$mail->AddAddress('jane.doe#gmail.com', 'Jane Doe'); // recipient email
$mail->Subject = "First SMTP Message"; // email subject
$mail->Body = "Hi! \n\n This is my first e-mail sent through Google SMTP using PHPMailer.";
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
?>
I successfully use the GMail SMTP server.
We do have a corporate GMail account, though I don't think that matters. A personal GMail account should suffice.
I do not have a PHP sample however the following configuration for ASP.Net should provide adequate guidance:
<mailSettings>
<smtp from="me#gmail.com">
<network enableSsl="true" host="smtp.gmail.com" port="587" userName="me#gmail.com" password="mypassword" />
</smtp>
</mailSettings>
If someone has a suitable PHP sample, feel free to edit my answer or post your own.
Authentication is required I believe, but I don't see why not. I won't do the research for you, but there are a couple things to look into:
Their SMTP server requires TLS encryption and is hosted on a non-standard port (995). You will need to ensure that AWS supports both of these options for SMTP outbound.
There is probably a cap on emails you can send before being marked as spam. You should research this and ensure it is not beyond your requirements.
You can user PHPMailer class for this job. And you can easily configure the smtp.
An example of configuration
if (class_exists(#PHPMailer)) {
$smtp_mail = new PHPMailer();
$smtp_mail->isSMTP();
$smtp_mail->SMTPAuth = true; // enable SMTP authentication
$smtp_mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$smtp_mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$smtp_mail->Port = 465; // set the SMTP port
$smtp_mail->Username = "info#example.com"; // GMAIL username
$smtp_mail->Password = "password"; // GMAIL password
$smtp_mail->From = "info#example.com";
$smtp_mail->FromName = "Name";
$smtp_mail->AltBody = "This is the body when user views in plain text format"; //Text Body
$smtp_mail->WordWrap = 50; // set word wrap
$smtp_mail->AddReplyTo("info#example.com","Name");
$smtp_mail->isHTML(true); // send as HTML
}
Although you can technically use Gmail as SMTP server, it is not recommended for larger websites. By time you may receive issues like "421 4.7.0 Temporary System Problem" or similar, is it was not designed to be used by an application, rather a single person.
Related issue for the error message above:
Gmail SMTP error - Temporary block?