I've looked into the following links:
phpmailer send gmail smtp timeout
send email using Gmail SMTP server through PHP Mailer
http://uly.me/phpmailer-and-gmail-smtp/
...and tried to implement for myself a combination of those however...most of the time it sends this message...
Message could not be sent.
Mailer Error: SMTP connect() failed.
However there was one time where it sent this when I experimented between "tls" and "ssl"...
SMTP ERROR: Failed to connect to server: Connection timed out (110) SMTP connect() failed.
Message could not be sent.
Mailer Error: SMTP connect() failed.
My code is attached...did I somehow miss something? I asked the web hosting service if they're blocking and gave them a template of my code - they said the server allows connections to Gmail's SMTP.
require_once("class.phpmailer.php");
$mail = new PHPMailer();
$mail -> IsSMTP();
$mail -> SMTPDebug = 2;
$mail -> SMTPAuth = 'true';
$mail -> SMTPSecure = 'tls';
$mail -> SMTPKeepAlive = true;
$mail -> Host = 'smtp.gmail.com';
$mail -> Port = 587;
$mail -> IsHTML(true);
$mail -> Username = "myemail#gmail.com";
$mail -> Password = "mypassword";
$mail -> SingleTo = true;
$to = xxx;
$from = xxx;
$fromname = xxx;
$subject = xxx;
$message = xxx
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
$mail -> From = $from;
$mail -> FromName = $fromname;
$mail -> AddAddress($to);
$mail -> Subject = $subject;
$mail -> Body = $message;
if(!$mail -> Send()){
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail-> ErrorInfo;
exit;
}
I dug into it. Use fsocketopen, which is native to php, to test the connection and eliminate most of the potential problems. Write a simple php page with this:
$host = "smtp.gmail.com";
$port = "587";
$checkconn = fsockopen($host, $port, $errno, $errstr, 5);
if(!$checkconn){
echo "($errno) $errstr";
} else {
echo 'ok';
}
You should get back "ok". If not you know you have a connection problem that has nothing to do with Phpmailer. If that's the case it's probably the hosting company. If not then it's probably something simple about the difference between your local host and the hosting company like different versions of php.
I suspect though that this script won't make the connection
I had this same problem and solved it:
First, turn on smtp error logging in phpmailer:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
Then retry your phpmailer email send. You will see the entire SMTP conversation on standard error output. If you're using a web server, look in the web server log file.
I could then see the error response from gmail. Gmail was not accepting the login.
The error within the smtp conversation refers to an article. It gives some tips:
Allow less secure apps to use your account.
Login to gmail from a web browser.
Confirm the gmail login captcha. (It may not actually display a captcha to you, but this was the additional step that suddenly allowed my email to go through.)
Use ssl
$mail -> SMTPSecure = 'ssl';
Port should be 465
$mail -> Port = 465;
Change your host to:
$mail -> Host = 'ssl://smtp.gmail.com';
Hopefully it works
Check to make sure you can reach gmail from your webhost. I'm assuming it's linux. SSH in and on the command line type
telnet smtp.gmail.com 587
You should get back
Connected to smtp.something
It has to be a configuration difference between localhost and your provider
This question has many duplicates, so here's a canned answer:
Base your code on the gmail example provided with PHPMailer
Check out the troubleshooting docs
Be aware of this issue, related to what Larry K said.
That might probably be Gmail blocking your access.
Go to your security configurations and see if it's blocking any access..
Or try to change your password and try again.
Add
date_default_timezone_set('Etc/UTC');
before including the autoloader. SMTP Needs to have the timezone set which was my issue.
Download sendmail for Windows from
http://www.glob.com.au/sendmail/sendmail.zip
Copy sendmail.exe and sendmail.ini into C:/usr/lib/
Edit sendmail.ini and enter your mail account credentials.
You might want to configure these 2 fields as well (or sending may not work)
force_sender=you-sender#yourdomain.com
force_recipient=you#yourdomain.com
By the way I uncommented debug_logfile so I can see what data is being sent to my SMTP server.
edit c:\php\php.ini
sendmail_from = you#yourdomain.com
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = C:/usr/lib/sendmail.exe -t -i
Restart apache
Start sendmail.exe either from [Start] > Run > C:/usr/lib/sendmail.exe or Go to C:/usr/lib in Windows Explorer and then DoubleClick on the exe file.
And this solution appears in Sendmail Wamp Php
I tried it on Windows 10 now and it runs with gmail account
Added:
Open CMD and make a sendmail as daemon/service using
sc create SendMail binpath= "C:\usr\lib\sendmail.exe"
Now, be sure you have OpenSSL installed on your system, you can download it from here: https://slproweb.com/products/Win32OpenSSL.html
Installs the version what do you need and dont remember to install "files to windows folder". Do a restart and try again, you will have it solved.
Related
I have installed WAMP Server on my Windows 10 PC and when I try to send emails through a valid SMTP configuration it doesn't work. The same SMTP configuration works on another LAMP installation and also on a live server.
When I try sending the email through a PrestaShop installation I get following error:
Error: Please check your configuration
Connection could not be established with host smtp.gmail.com [ #0]
And with Magento I get following error:
SMTP Pro Self Test Results
Sending test email to your contact form address: xxxxxxx#example.com from: xxx.adsxx#example.com. Unable to send test email.
Exception message was: Could not open socket
Please check the user guide for frequent error messages and their solutions.
Default templates exist.
Email communications are enabled.
As per my understanding, this issue is not dependent on Magento or PrestaShop, it is coming because of the WAMP installation.
Do I have to enable some extension or something for the WAMP installation? Or have I missed something else?
Please help. Already wasted a lot of time investigating and trying solutions from the Web, but nothing seems to be working.
Download the sendmail.zip
Create a folder named “sendmail” in “C:\wamp\”.
Extract these 4 files in “sendmail” folder: “sendmail.exe”, “libeay32.dll”, “ssleay32.dll” and “sendmail.ini”.
Open the “sendmail.ini” file and configure it as following
smtp_server=smtp.gmail.com
smtp_port=465
smtp_ssl=ssl
default_domain=localhost
error_logfile=error.log
debug_logfile=debug.log
auth_username=[your_gmail_account_username]#gmail.com
auth_password=[your_gmail_account_password]
pop3_server=
pop3_username=
pop3_password=
force_sender=
force_recipient=
hostname=localhost
You do not need to specify any value for these properties: pop3_server, pop3_username, pop3_password, force_sender, force_recipient. The error_logfile and debug_logfile settings should be kept blank if you have already sent successful email(s) otherwise size of this file will keep increasing. Enable these log file settings if you don’t get able to send email using sendmail.
Enable IMAP Access in your GMail’s Settings -> Forwarding and POP/IMAP -> IMAP Access:
Enable “php_openssl” and “php_sockets” extensions for PHP compiler:
Open php.ini from “C:\wamp\bin\apache\Apache2.2.17\bin” and configure it as following (The php.ini at “C:\wamp\bin\php\php5.3.x” would not work) (You just need to configure the last line in the following code, prefix semicolon (;) against other lines):
Restart WAMP Server.
Create a PHP file and write the following code in it:
<?php
$to = 'recipient#yahoo.com';
$subject = 'Testing sendmail.exe';
$message = 'Hi, you just received an email using sendmail!';
$headers = 'From: [your_gmail_account_username]#gmail.com' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-type: text/html; charset=utf-8';
if(mail($to, $subject, $message, $headers))
echo "Email sent";
else
echo "Email sending failed";
?>
Make appropriate changes in $to and $headers variables to set recipient and sender (“From” header) addresses. Save it as “send-mail.php”. (You can save it anywhere or inside any sub-folder in “C:\wamp\www”.)
Open this file in browser, it MUST work now
These are possibly causes which prevent you from sending mails via WAMP server.
Your firewall configurations may (by default) block some ports used by WAMP for sending emails.
These ports may be already used by your others applications. Prefer to this to know which port is being used by which application.
Administrators rights are required for the WAMP server to be able to send mail. Run the server as administrator.
Since you're sure that settings have already worked on a server so I assume there nothing to check with PHP.ini
make sure that your -
extension=php_openssl.dll
extension=php_sockets.dll
is enable in php.ini file.
check is Enable ssl_module under Apache Module.
You can use PHP Mailer or Download php mailer with example from here. Once you setup the phpmailer with your project use following code to send mail using gmail SMTP :
require_once('inc/class.phpmailer.php'); # INCLUDE PHPMailer CLASS FILE
require_once("inc/class.smtp.php"); # INCLUDE OTHER SMTP FILE
Include above files in your project or PHP file which you use to send email and then :
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0; # ENABLE SMTP DEBUG INFORMATION (FOR TESTING)
# 1 = ERROR AND MESSAGE
# 2 = MESSAGE ONLY
$mail->SMTPAuth = true; # ENABLE SMTP AUTHENTICATION
$mail->Host = "Host Addresss"; # smtp.gmail.com
$mail->Port = 587; # PORT NUMBER
$mail->Username = "example#gmail.com"; # SMTP EMAIL USER NAME
$mail->Password = "xxxxxxx"; # SMTP ACCOUNT PASSWORD
$mail->SetFrom('example#gmail.com', 'Test Name');
$mail->SMTPSecure = 'tls';
$mail->AddReplyTo("example#gmail.com","SMTP TEST");
$v_Msg ="This is a test message via SMTP";
$mail->Subject = "EMAIL SUBJECT";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; # OPTIONAL
$address = "sendto#email.com"; # ADDRESS WHERE YOU WANT TO SEND MAIL
$mail->AddAddress($address, "TESTING");
$mail->MsgHTML($v_Msg); # EMAIL CONTENT
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo; # ERROR MESSAGE, IF MAIL NOT SENT SUCCESSFULLY
}else {
echo "Message sent!"; # SUCCESS MESSAGE
}
NOTE : Make sure your smtp gmail account must be Allow less secure apps: ON. You can turn on less secure apps for your gmail
account using THIS URL
Sometimes its easier not to rely on your own smtp server. (firewalls everywhere)
You can experiment with some other online mail delivery services than gmail, like mailgun or sendgrid.
$from = "someonelse#example.com";
$headers = "From:" . $from;
echo mail ("borutflis1#gmail.com" ,"testmailfunction" , "Oj",$headers);
I have trouble sending email in PHP. I get an error: SMTP server response: 530 SMTP authentication is required.
I was under the impression that you can send email without SMTP to verify. I know that this mail will propably get filtered out, but that doesn't matter right now.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = someonelse#example.com
This is the setup in the php.ini file. How should I set up SMTP? Are there any SMTP servers that require no verification or must I setup a server myself?
When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).
For example, I usually use PHPMailer with similar settings to this ones:
$mail = new PHPMailer();
// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "username"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
// Content
$mail->setFrom('domain#example.com');
$mail->addAddress('receipt#domain.com');
$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';
$mail->send();
You can find more about PHPMailer here: https://github.com/PHPMailer/PHPMailer
<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "YOURMAIL#gmail.com");
$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = YourMail#address.com";
$headers = "From: YOURMAIL#gmail.com";
mail("Sending#provider.com", "Testing", $message, $headers);
echo "Check your email now....<BR/>";
?>
or, for more details, read on.
For Unix users, mail() is actually using Sendmail command to send email. Instead of modifying the application, you can change the environment. msmtp is an SMTP client with Sendmail compatible CLI syntax which means it can be used in place of Sendmail. It only requires a small change to your php.ini.
sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"
Then even the lowly mail() function can work with SMTP goodness. It is super useful if you're trying to connect an existing application to mail services like sendgrid or mandrill without modifying the application.
The problem is that PHP mail() function has a very limited functionality. There are several ways to send mail from PHP.
mail() uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.
mail() uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.
Mailing libraries use direct connections. Libs are easier to set up. I used SwiftMailer and it perfectly sends mail from Gmail account. I think that PHPMailer is pretty good too.
No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail() function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer class or interface with abstract send() method. Inherit two classes MyPhpMailer and MySwiftMailer. Implement send() method in appropriate ways.
There are some SMTP servers that work without authentication, but if the server requires authentication, there is no way to circumvent that.
PHP's built-in mail functions are very limited - specifying the SMTP server is possible in WIndows only. On *nix, mail() will use the OS's binaries.
If you want to send E-Mail to an arbitrary SMTP server on the net, consider using a library like SwiftMailer. That will enable you to use, for example, Google Mail's outgoing servers.
In cases where you are hosting a WordPress site on Linux and have server access, you can save some headaches by installing msmtp which allows you to send via SMTP from the standard PHP mail() function. msmtp is a simpler alternative to postfix which requires a bit more configuration.
Here are the steps:
Install msmtp
sudo apt-get install msmtp-mta ca-certificates
Create a new configuration file:
sudo nano /etc/msmtprc
...with the following configuration information:
# Set defaults.
defaults
# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <username#example.net>
password <password>
from <address-to-receive-bounces#example.net>
syslog LOG_MAIL
You need to replace the configuration data represented by everything within "<" and ">" (inclusive, remove these). For host/username/password, use your normal credentials for sending mail through your mail provider.
Tell PHP to use it
sudo nano /etc/php5/apache2/php.ini
Add this single line:
sendmail_path = /usr/bin/msmtp -t
Complete documentation can be found here:
https://marlam.de/msmtp/
I know this is an old question but it's still active and all the answers I saw showed basic authentication, which is deprecated. Here is an example showing how to send via Google's Gmail servers using PHPMailer with XOAUTH2 authentication:
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;
//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');
//Load dependencies from composer
//If this causes an error, run 'composer install'
require '../vendor/autoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number:
// - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
// - 587 for SMTP+STARTTLS
$mail->Port = 465;
//Set the encryption mechanism to use:
// - SMTPS (implicit TLS on port 465) or
// - STARTTLS (explicit TLS on port 587)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Set AuthType to use XOAUTH2
$mail->AuthType = 'XOAUTH2';
//Fill in authentication details here
//Either the gmail account owner, or the user that gave consent
$email = 'someone#gmail.com';
$clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com';
$clientSecret = 'RANDOMCHARS-----lGyjPcRtvP';
//Obtained by configuring and running get_oauth_token.php
//after setting up an app in Google Developer Console.
$refreshToken = 'RANDOMCHARS-----DWxgOvPT003r-yFUV49TQYag7_Aod7y0';
//Create a new OAuth2 provider instance
$provider = new Google(
[
'clientId' => $clientId,
'clientSecret' => $clientSecret,
]
);
//Pass the OAuth provider instance to PHPMailer
$mail->setOAuth(
new OAuth(
[
'provider' => $provider,
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'refreshToken' => $refreshToken,
'userName' => $email,
]
)
);
//Set who the message is to be sent from
//For gmail, this generally needs to be the same as the user you logged in as
$mail->setFrom($email, 'First Last');
//Set who the message is to be sent to
$mail->addAddress('someone#gmail.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail XOAUTH2 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->CharSet = PHPMailer::CHARSET_UTF8;
$mail->msgHTML(file_get_contents('contentsutf8.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!';
}
Reference: PHPMailer examples folder
For another approach, you can take a file like this:
From: Sunday <sunday#gmail.com>
To: Monday <monday#gmail.com>
Subject: Day
Tuesday Wednesday
and send like this:
<?php
$a1 = ['monday#gmail.com'];
$r1 = fopen('a.txt', 'r');
$r2 = curl_init('smtps://smtp.gmail.com');
curl_setopt($r2, CURLOPT_MAIL_RCPT, $a1);
curl_setopt($r2, CURLOPT_NETRC, true);
curl_setopt($r2, CURLOPT_READDATA, $r1);
curl_setopt($r2, CURLOPT_UPLOAD, true);
curl_exec($r2);
https://php.net/function.curl-setopt
I created a simple lightweight SMTP email sender for PHP if anybody needs it. Here is the URL:
https://github.com/Nerdtrix/EZMAIL
It was tested in both environments, production and development.
I have used phpmailer() concept to send mail to users from my shared server using php script, but I'm not able to send even though everything is right in my script according to phpmailer code.
My code like this:
$message = " This is testing message from my server";
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "moorthi.mrk10#gmail.com"; // My gmail username
$mail->Password = "************"; // My Gmail Password
$mail->SetFrom("moorthi.mrk10#gmail.com");
$mail->Subject = "Test Mail from my Server";
$mail->Body = $message;
$mail->AddAddress($email);
if($mail->Send())
{
print json_encode("SUCCESS");
}
else
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
Note: I have used " GMail " as my SMTP server and SMTPSecure is " ssl " and port is "465" and username & passwords are my GMail username & password
I used VPS shared server and I kept my php script on that server.
I think there is no problem in my php script and I don't know why it doesn't work.
I got the ERROR like this.
2014-02-21 12:30:11 CLIENT -> SERVER: EHLO jkcorporates.com
2014-02-21 12:30:11 CLIENT -> SERVER: AUTH LOGIN
2014-02-21 12:30:11 CLIENT -> SERVER: bW9vcnRoaS5tcmsxMEBnbWFpbC5jb20=
2014-02-21 12:30:11 CLIENT -> SERVER: OTk0MTI0MTE0MA==
2014-02-21 12:30:11 SMTP ERROR: Password command failed: 534-5.7.14
534-5.7.14 i-_eumA> Please log in via your web browser and then try again.
534 5.7.14 54 k76sm17979938yho.18 - gsmtp
2014-02-21 12:30:11 CLIENT -> SERVER: QUIT
" The ERROR is " SMTP connect() failed.
Please give some solution for that.
Remember: I use Shared Server Name 'VPS.mydomain.com' and I want to use GMail as my SMTP server to send mail to users.
A bit late, but perhaps someone will find it useful.
Links that fix the problem (you must be logged into google account):
https://security.google.com/settings/security/activity?hl=en&pli=1
https://www.google.com/settings/u/1/security/lesssecureapps
https://accounts.google.com/b/0/DisplayUnlockCaptcha
Some explanation of what happens:
This problem can be caused by either 'less secure' applications trying to use the email account (this is according to google help, not sure how they judge what is secure and what is not) OR if you are trying to login several time in a row OR if you change countries (for example use VPN, move code to different server or actually try to login from different part of the world).
To resolve I had to: (first time)
login to my account via web
view recent attempts to use the account and accept suspicious access: THIS LINK
disable the feature of blocking suspicious apps/technologies: THIS LINK
This worked the first time, but few hours later, probably because I was doing a lot of testing the problem reappeared and was not fixable using the above method. In addition I had to clear the captcha (the funny picture, which asks you to rewrite a word or a sentence when logging into any account nowadays too many times) :
after login to my account I went HERE
Clicked continue
Use this:
https://www.google.com/settings/u/1/security/lesssecureapps
https://accounts.google.com/b/0/DisplayUnlockCaptcha
https://security.google.com/settings/security/activity?hl=en&pli=1
this link allow acces to google account
UPDATE 19-05-2017:
These url you must to visit from the IP address that will be send email
Solved the problem - PHPMailer - SMTP ERROR: Password command failed when send mail from my server
require_once('class.phpmailer.php');
include("class.smtp.php");
$nameField = $_POST['name'];
$emailField = $_POST['email'];
$messageField = $_POST['message'];
$phoneField = $_POST['contactno'];
$cityField = $_POST['city'];
$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
$body .= $nameField;
try {
//$mail->Host = "mail.gmail.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->SMTPKeepAlive = true;
$mail->Mailer = "smtp";
$mail->Username = "xxxxx#gmail.com"; // GMAIL username
$mail->Password = "********"; // GMAIL password
$mail->AddAddress('sendto#gmail.com', 'abc');
$mail->SetFrom('xxxxxx#gmail.com', 'def');
$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($body);
$mail->Send();
echo "Message Sent OK</p>\n";
header("location: ../test.html");
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
Important:
Go to google Setting and do 'less secure' applications enables. It will work.
It Worked for Me.
As others already suggested, you can enable the "less secure" applications or you can simply switch from ssl to tls:
$mailer->Host = 'tls://smtp.gmail.com';
$mailer->SMTPAuth = true;
$mailer->Username = "xxx#gmail.com";
$mailer->Password = "***";
$mailer->SMTPSecure = 'tls';
$mailer->Port = 587;
When using tls there's no need to grant access for less secure applications, just make sure, IMAP is enabled.
Login to your Gmail account using the web browser.
Click on this link to enable applications to access your account: https://accounts.google.com/b/0/DisplayUnlockCaptcha
Click on Continue button to complete the step.
Now try again to send the email from your PHP script. It should work.
I face the same problem, and think that I do know why this happens.
The gmail account that I use is normally used from India, and the webserver that I use is located in The Netherlands.
Google notifies that there was a login attempt from am unusualy location and requires to login from that location via a web browser.
Furthermore I had to accept suspicious access to the gmail account via https://security.google.com/settings/security/activity
But in the end my problem is not yet solved, because I have to login to gmail from a location in The Netherlands.
I hope this will help you a little! (sorry, I do not read email replies on this email address)
Just in caser anyone ends here like me.
In may case despite having enabled unsecure access to my google account, it refused to send the email throwing an SMTP ERROR: Password command failed: 534-5.7.14.
(Solution found at https://know.mailsbestfriend.com/smtp_error_password_command_failed_5345714-1194946499.shtml)
Steps:
log into your google account
Go to https://accounts.google.com/b/0/DisplayUnlockCaptcha and click continue to enable.
Setup your phpmailer as smtp with ssl:
$mail = new PHPMailer(true);
$mail->CharSet ="utf-8";
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // or 0 for no debuggin at all
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->SMTPAuth = true;
$mail->Username = 'yourgmailaccount';
$mail->Password = 'yourpassword';
And the other $mail object properties as needed.
Hope it helps someone!!
You need to use an APP password.
Visit this link to view how to create one.
For those who are still unable to get it working, try the following in addition to the method provided by #CallMeBob.
PHP.ini
Go to C:\xampp\php , edit php.ini file with notepad.
Press CTRL+F on your keyboard, input sendmail_path on the search bar and click Find Next twice.
Right now, you should be at the [mail munction] section.
Remove the semicolon for this line:
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
Add a semicolon for this line:
sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe"
SendMail.ini
Go to C:\xampp\sendmail, edit sendmail.ini file with notepad
Change the following:
smtp_server=smtp.gmail.com
smtp_port=465
auth_username=your-gmail-username#gmail.com
auth_password=your-gmail-password
force_sender=your-gmail-username#gmail.com
Note:
** smtp_port must tally with your those written in your php code.
** Remember to change your-gmail-username and your-gmail-password to whichever account you are using.
**
Hope this helps! :)
If you are G Suit user it can be solved by Administrator
Go to your Admin panel
Type in top search bar «Security» (Select Security with Shield icon)
Open Basic settings
Goto Less secure apps section
Press: Go to settings for less secure apps ››
And now select one of Radio Button
a) Disable access to less secure apps for all users (Recommended)
b) Allow users to manage their access to less secure apps
c) Enforce access to less secure apps for all users (Not Recommended)
Usually It does not working because of a)! And will start working immediately with c) option. b) – option will need more configuration for each user in GSuit
Hope it helps
This error is due to more security features of gmail..
Once this error is generated...Please login to your gmail account..there you can find security alert from GOOGLE..follow the mail...check on click for less secure option..Then try again phpmailer..
Your mail won't be sent online unless you complete the two-step verification for your g-mail account and use that password.
after publishing the code to the server, I am using gmail account to send a mail.
I followed the following steps to solve the issue
https://www.google.com/settings/u/1/security/lesssecureapps
https://security.google.com/settings/security/activity?hl=en&pli=1
if you added the 2 step verification then you need to remove to make it work
I would like to send email through php code hosted locally.
<?php
$email = "myemail#local.com";
$titre = "My subject";
$message = "Text message !";
mail($email, $titre, $message);
?>
When I run this code, I get the following error :
Warning: mail() [<a href='function.mail'>function.mail</a>]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\...
I went into the php.ini file and it seems to be already well configured.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25
How can I fix this ?
Thank you
It is configured to use localhost:25 for the mail server.
The error message says that it can't connect to localhost:25.
Therefore you have two options:
Install / Properly configure an SMTP server on localhost port 25
Change the configuration to point to some other SMTP server that you can connect to
I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.
<?php
include 'nav.php';
/*
Download PhpMailer from the following link:
https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
Extract the PHPMailer-master folder into your xampp->htdocs folder
Make changes in the following code and its done :-)
You will receive the mail with the name Root User.
To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
And change the name here:
public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some //other folder
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "trials.php#gmail.com"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP(); // telling the class to use SMTP
$rec1="trials.php#gmail.com"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject = "Eventbook";
$mail->Body = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo //Fill in the document.location thing
'<script type="text/javascript">
if(confirm("Your mail has been sent"))
document.location = "/";
</script>';
}
?>
You will need to install a local mailserver in order to do this.
If you want to send it to external e-mail addresses, it might end up in unwanted e-mails or it may not arrive at all.
A good mailserver which I use (I use it on Linux, but it's also available for Windows) is Axigen:
http://www.axigen.com/mail-server/download/
You might need some experience with mailservers to install it, but once it works, you can do anything you want with it.
try this
ini_set("SMTP","aspmx.l.google.com");
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: test#gmail.com" . "\r\n";
mail("email#domain.com","test subject","test body",$headers);
It is possible to send Emails without using any heavy libraries I have included my example here.
lightweight SMTP Email sender for PHP
https://github.com/Nerdtrix/EZMAIL
Tested in both environments production and development.
and most importantly emails will not go to spam unless your IP is blacklisted by the server.
cheers.
$from = "someonelse#example.com";
$headers = "From:" . $from;
echo mail ("borutflis1#gmail.com" ,"testmailfunction" , "Oj",$headers);
I have trouble sending email in PHP. I get an error: SMTP server response: 530 SMTP authentication is required.
I was under the impression that you can send email without SMTP to verify. I know that this mail will propably get filtered out, but that doesn't matter right now.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = someonelse#example.com
This is the setup in the php.ini file. How should I set up SMTP? Are there any SMTP servers that require no verification or must I setup a server myself?
When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).
For example, I usually use PHPMailer with similar settings to this ones:
$mail = new PHPMailer();
// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "username"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
// Content
$mail->setFrom('domain#example.com');
$mail->addAddress('receipt#domain.com');
$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';
$mail->send();
You can find more about PHPMailer here: https://github.com/PHPMailer/PHPMailer
<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "YOURMAIL#gmail.com");
$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = YourMail#address.com";
$headers = "From: YOURMAIL#gmail.com";
mail("Sending#provider.com", "Testing", $message, $headers);
echo "Check your email now....<BR/>";
?>
or, for more details, read on.
For Unix users, mail() is actually using Sendmail command to send email. Instead of modifying the application, you can change the environment. msmtp is an SMTP client with Sendmail compatible CLI syntax which means it can be used in place of Sendmail. It only requires a small change to your php.ini.
sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"
Then even the lowly mail() function can work with SMTP goodness. It is super useful if you're trying to connect an existing application to mail services like sendgrid or mandrill without modifying the application.
The problem is that PHP mail() function has a very limited functionality. There are several ways to send mail from PHP.
mail() uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.
mail() uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.
Mailing libraries use direct connections. Libs are easier to set up. I used SwiftMailer and it perfectly sends mail from Gmail account. I think that PHPMailer is pretty good too.
No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail() function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer class or interface with abstract send() method. Inherit two classes MyPhpMailer and MySwiftMailer. Implement send() method in appropriate ways.
There are some SMTP servers that work without authentication, but if the server requires authentication, there is no way to circumvent that.
PHP's built-in mail functions are very limited - specifying the SMTP server is possible in WIndows only. On *nix, mail() will use the OS's binaries.
If you want to send E-Mail to an arbitrary SMTP server on the net, consider using a library like SwiftMailer. That will enable you to use, for example, Google Mail's outgoing servers.
In cases where you are hosting a WordPress site on Linux and have server access, you can save some headaches by installing msmtp which allows you to send via SMTP from the standard PHP mail() function. msmtp is a simpler alternative to postfix which requires a bit more configuration.
Here are the steps:
Install msmtp
sudo apt-get install msmtp-mta ca-certificates
Create a new configuration file:
sudo nano /etc/msmtprc
...with the following configuration information:
# Set defaults.
defaults
# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <username#example.net>
password <password>
from <address-to-receive-bounces#example.net>
syslog LOG_MAIL
You need to replace the configuration data represented by everything within "<" and ">" (inclusive, remove these). For host/username/password, use your normal credentials for sending mail through your mail provider.
Tell PHP to use it
sudo nano /etc/php5/apache2/php.ini
Add this single line:
sendmail_path = /usr/bin/msmtp -t
Complete documentation can be found here:
https://marlam.de/msmtp/
I know this is an old question but it's still active and all the answers I saw showed basic authentication, which is deprecated. Here is an example showing how to send via Google's Gmail servers using PHPMailer with XOAUTH2 authentication:
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;
//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');
//Load dependencies from composer
//If this causes an error, run 'composer install'
require '../vendor/autoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number:
// - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
// - 587 for SMTP+STARTTLS
$mail->Port = 465;
//Set the encryption mechanism to use:
// - SMTPS (implicit TLS on port 465) or
// - STARTTLS (explicit TLS on port 587)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Set AuthType to use XOAUTH2
$mail->AuthType = 'XOAUTH2';
//Fill in authentication details here
//Either the gmail account owner, or the user that gave consent
$email = 'someone#gmail.com';
$clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com';
$clientSecret = 'RANDOMCHARS-----lGyjPcRtvP';
//Obtained by configuring and running get_oauth_token.php
//after setting up an app in Google Developer Console.
$refreshToken = 'RANDOMCHARS-----DWxgOvPT003r-yFUV49TQYag7_Aod7y0';
//Create a new OAuth2 provider instance
$provider = new Google(
[
'clientId' => $clientId,
'clientSecret' => $clientSecret,
]
);
//Pass the OAuth provider instance to PHPMailer
$mail->setOAuth(
new OAuth(
[
'provider' => $provider,
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'refreshToken' => $refreshToken,
'userName' => $email,
]
)
);
//Set who the message is to be sent from
//For gmail, this generally needs to be the same as the user you logged in as
$mail->setFrom($email, 'First Last');
//Set who the message is to be sent to
$mail->addAddress('someone#gmail.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail XOAUTH2 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->CharSet = PHPMailer::CHARSET_UTF8;
$mail->msgHTML(file_get_contents('contentsutf8.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!';
}
Reference: PHPMailer examples folder
For another approach, you can take a file like this:
From: Sunday <sunday#gmail.com>
To: Monday <monday#gmail.com>
Subject: Day
Tuesday Wednesday
and send like this:
<?php
$a1 = ['monday#gmail.com'];
$r1 = fopen('a.txt', 'r');
$r2 = curl_init('smtps://smtp.gmail.com');
curl_setopt($r2, CURLOPT_MAIL_RCPT, $a1);
curl_setopt($r2, CURLOPT_NETRC, true);
curl_setopt($r2, CURLOPT_READDATA, $r1);
curl_setopt($r2, CURLOPT_UPLOAD, true);
curl_exec($r2);
https://php.net/function.curl-setopt
I created a simple lightweight SMTP email sender for PHP if anybody needs it. Here is the URL:
https://github.com/Nerdtrix/EZMAIL
It was tested in both environments, production and development.