SMTP Error on sending mail - php

I have been trying to send mail using wamp server in my laptop. The SMTP server is presented in online.
Here is my php code to send mail:
<?php
ini_set( 'SMTP', "mail.vickey1192.co.in" );
ini_set( 'smtp_port', 26 );
ini_set( 'sendmail_from', "admin#vickey1192.co.in" );
$to = "balavickey1192#gmail.com";
$subject = "Acknowledgement";
$message = "Thank you for registering with us<br>";
$from = "no-reply#vickey1192.co.in";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
I also set my php.ini file like this:
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = mail.vickey1192.co.in
; http://php.net/smtp-port
smtp_port = 26
; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = admin#vickey1192.co.in
This is the error I am getting:
Warning: mail() [function.mail]: SMTP server response: 550-Please turn on SMTP
Authentication in your mail client, or login to the 550-IMAP/POP3
server before sending your message. (vignesh-PC)
550-[115.118.170.201]:23328 is not permitted to relay through this
server 550 without authentication. in C:\wamp\www\mailtofunc.php on
line 12
What do I do now? Please help me guys...

I think its a problem with authentication. You need to add the SMTP user's username and password to the mail function to send the email.
//Using built in mail method
$mail = new PHPMailer();
$mail->Host = 'smtp.example.com'
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = 'your_username#example.com'; // a valid email here
$mail->Password = 'replace_with_your_password';
$mail->From = 'from#example.com';
$mail->AddReplyTo('from#example.com', 'Test');
$mail->FromName = 'Test SMTP';
$mail->AddAddress('test1#example.com', 'test2#example.com');
$mail->Subject = 'Test SMTP';
$mail->Body = 'Hello World';
$mail->Send();
You might be better off trying the PHP's Pear mail function, if you know how to use it.
//Using PEAR's mail function
<?php
include('Mail.php');
/* mail setup recipients, subject etc */
$recipients = "your_recipients#example.com";
$headers["From"] = "user#example.com";
$headers["To"] = "feedback#example.com";
$headers["Subject"] = "Some Subject";
$mailmsg = "Hello, This is a test.";
/* SMTP server name, port, user/passwd */
$smtpinfo["host"] = "smtp.example.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "smtpusername";
$smtpinfo["password"] = "smtpPassword";
/* Create the mail object using the Mail::factory method */
$mail_object =& Mail::factory("smtp", $smtpinfo);
/* Ok send mail */
$mail_object->send($recipients, $headers, $mailmsg);
?>

Your mail server requires authentication (username + password) before it will accept email from you. It is suggesting you either provide it via your SMTP connection (using SMTP AUTH, hopefully with TLS), or that you do a technique called POP before SMTP where you first login and 'check' your mail which will cause a temporary whitelisting of your host so it can send mail for a brief while afterward.

Related

Email failed to send: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting [duplicate]

I am trying to send an email via GMail's SMTP server from a PHP page, but I get this error:
authentication failure [SMTP: SMTP server does no support authentication (code: 250, response: mx.google.com at your service, [98.117.99.235] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)]
Can anyone help? Here is my code:
<?php
require_once "Mail.php";
$from = "Sandra Sender <sender#example.com>";
$to = "Ramona Recipient <ramona#microsoft.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
$host = "smtp.gmail.com";
$port = "587";
$username = "testtest#gmail.com";
$password = "testtest";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>
// Pear Mail Library
require_once "Mail.php";
$from = '<fromaddress#gmail.com>';
$to = '<toaddress#yahoo.com>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
$smtp = Mail::factory('smtp', array(
'host' => 'ssl://smtp.gmail.com',
'port' => '465',
'auth' => true,
'username' => 'johndoe#gmail.com',
'password' => 'passwordxxx'
));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo('<p>' . $mail->getMessage() . '</p>');
} else {
echo('<p>Message successfully sent!</p>');
}
Using Swift mailer, it is quite easy to send a mail through Gmail credentials:
<?php
require_once 'swift/lib/swift_required.php';
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
->setUsername('GMAIL_USERNAME')
->setPassword('GMAIL_PASSWORD');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test Subject')
->setFrom(array('abc#example.com' => 'ABC'))
->setTo(array('xyz#test.com'))
->setBody('This is a test mail.');
$result = $mailer->send($message);
?>
Your code does not appear to be using TLS (SSL), which is necessary to deliver mail to Google (and using ports 465 or 587).
You can do this by setting
$host = "ssl://smtp.gmail.com";
Your code looks suspiciously like this example which refers to ssl:// in the hostname scheme.
I don't recommend Pear Mail. It has not been updated since 2010. Also read the source files; the source code is almost outdated, written in PHP 4 style and many errors / bugs have been posted (Google it). I am using Swift Mailer.
Swift Mailer integrates into any web application written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.
Send emails using SMTP, sendmail, postfix or a custom Transport
implementation of your own.
Support servers that require username & password and/or encryption.
Protect from header injection attacks without stripping request data
content.
Send MIME compliant HTML/multipart emails.
Use event-driven plugins to customize the library.
Handle large attachments and inline/embedded images with low memory
use.
It is a free and open source you can Download Swift Mailer and upload to your server. (The feature list is copied from owner website).
The working example of Gmail SSL/SMTP and Swift Mailer is here...
// Swift Mailer Library
require_once '../path/to/lib/swift_required.php';
// Mail Transport
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
->setUsername('username#gmail.com') // Your Gmail Username
->setPassword('my_secure_gmail_password'); // Your Gmail Password
// Mailer
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject Here')
->setFrom(array('sender#example.com' => 'Sender Name')) // can be $_POST['email'] etc...
->setTo(array('receiver#example.com' => 'Receiver Name')) // your email / multiple supported.
->setBody('Here is the <strong>message</strong> itself. It can be text or <h1>HTML</h1>.', 'text/html');
// Send the message
if ($mailer->send($message)) {
echo 'Mail sent successfully.';
} else {
echo 'I am sure, your configuration are not correct. :(';
}
<?php
date_default_timezone_set('America/Toronto');
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = "gdssdh";
//$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
//$mail->Host = "ssl://smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$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->Username = "user#gmail.com"; // GMAIL username
$mail->Password = "password"; // GMAIL password
$mail->SetFrom('contact#prsps.in', 'PRSPS');
//$mail->AddReplyTo("user2#gmail.com', 'First Last");
$mail->Subject = "PRSPS password";
//$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address = "user2#yahoo.co.in";
$mail->AddAddress($address, "user2");
//$mail->AddAttachment("images/phpmailer.gif"); // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
SwiftMailer can send E-Mail using external servers.
here is an example that shows how to use a Gmail server:
require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";
//Connect to localhost on port 25
$swift =& new Swift(new Swift_Connection_SMTP("localhost"));
//Connect to an IP address on a non-standard port
$swift =& new Swift(new Swift_Connection_SMTP("217.147.94.117", 419));
//Connect to Gmail (PHP5)
$swift = new Swift(new Swift_Connection_SMTP(
"smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS));
As of May 30, 2022, Google will no longer support the use of third-party applications and devices that allow you to sign in to your Google Account with your username and password.
However, there is an easy solution provided by Google.
Instead of a password, input an app password generated by Google. Firstly, go to the settings and enable 2-Step Verification.
Then click on the App passwords.
You should see the App passwords screen. App passwords let you sign in to your Google Account from apps on devices that don't support 2-Step Verification. Select Mail as the app and then select a device. In my case, I chose Other, because I want to deploy my application to the cloud.
Once done, click on the GENERATE button. You will see your generated app password.
Just copy the password and replace the previous password in your email sending service with the generated one. You won't be able to see the password again though.
That's it!
The code as listed in the question needs two changes
$host = "ssl://smtp.gmail.com";
$port = "465";
Port 465 is required for an SSL connection.
Send Mail using phpMailer library through Gmail
Please donwload library files from Github
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
*/
//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 '../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';
// 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'), dirname(__FILE__));
//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!";
}
I had this problem also. I set the correct settings and have enabled less secure apps but it still did not work. Finally, I enabled this https://accounts.google.com/UnlockCaptcha, and it worked for me.
To install PEAR's Mail.php in Ubuntu, run following set of commands:
sudo apt-get install php-pear
sudo pear install mail
sudo pear install Net_SMTP
sudo pear install Auth_SASL
sudo pear install mail_mime
Gmail requires port 465, and also it's the code from phpmailer
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 email using SMTP 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
I have a solution for GSuite accounts that doesnt have the "#gmail.com" sufix. Also I think it will work for GSuite accounts with the #gmail.com but havent tried it.
First you should have the privileges to change the option "allos¿w less secure app" for your GSuite account. If you have the privileges (you can check in account settings->security) then you have to deactivate "two step factor authentication" go to the end of the page and set to "yes" for allow less secure applications. That's all. If you dont have privileges to change those options the solution for this thread will not work. Check https://support.google.com/a/answer/6260879?hl=en to make changes to "allow less..." option.
I tried the suggestion offered by #shasi kanth, but it didn't work out. I read the documentation and there are few changes made. So I managed to send mail via Gmail using this code, where vendor/autoload.php is got by composer with composer require "swiftmailer/swiftmailer:^6.0":
<?php
require_once 'vendor/autoload.php';
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))->setUsername ('SendingMail')->setPassword ('Password');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message('test'))
->setFrom(['Sending mail'])
->setTo(['Recipient mail'])
->setBody('Message')
;
$result = $mailer->send($message);
?>
Set
'auth' => false,
Also, see if port 25 works.

Mail not sent on gmail, yahoo [duplicate]

I am trying to send an email via GMail's SMTP server from a PHP page, but I get this error:
authentication failure [SMTP: SMTP server does no support authentication (code: 250, response: mx.google.com at your service, [98.117.99.235] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)]
Can anyone help? Here is my code:
<?php
require_once "Mail.php";
$from = "Sandra Sender <sender#example.com>";
$to = "Ramona Recipient <ramona#microsoft.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
$host = "smtp.gmail.com";
$port = "587";
$username = "testtest#gmail.com";
$password = "testtest";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>
// Pear Mail Library
require_once "Mail.php";
$from = '<fromaddress#gmail.com>';
$to = '<toaddress#yahoo.com>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
$smtp = Mail::factory('smtp', array(
'host' => 'ssl://smtp.gmail.com',
'port' => '465',
'auth' => true,
'username' => 'johndoe#gmail.com',
'password' => 'passwordxxx'
));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo('<p>' . $mail->getMessage() . '</p>');
} else {
echo('<p>Message successfully sent!</p>');
}
Using Swift mailer, it is quite easy to send a mail through Gmail credentials:
<?php
require_once 'swift/lib/swift_required.php';
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
->setUsername('GMAIL_USERNAME')
->setPassword('GMAIL_PASSWORD');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test Subject')
->setFrom(array('abc#example.com' => 'ABC'))
->setTo(array('xyz#test.com'))
->setBody('This is a test mail.');
$result = $mailer->send($message);
?>
Your code does not appear to be using TLS (SSL), which is necessary to deliver mail to Google (and using ports 465 or 587).
You can do this by setting
$host = "ssl://smtp.gmail.com";
Your code looks suspiciously like this example which refers to ssl:// in the hostname scheme.
I don't recommend Pear Mail. It has not been updated since 2010. Also read the source files; the source code is almost outdated, written in PHP 4 style and many errors / bugs have been posted (Google it). I am using Swift Mailer.
Swift Mailer integrates into any web application written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.
Send emails using SMTP, sendmail, postfix or a custom Transport
implementation of your own.
Support servers that require username & password and/or encryption.
Protect from header injection attacks without stripping request data
content.
Send MIME compliant HTML/multipart emails.
Use event-driven plugins to customize the library.
Handle large attachments and inline/embedded images with low memory
use.
It is a free and open source you can Download Swift Mailer and upload to your server. (The feature list is copied from owner website).
The working example of Gmail SSL/SMTP and Swift Mailer is here...
// Swift Mailer Library
require_once '../path/to/lib/swift_required.php';
// Mail Transport
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
->setUsername('username#gmail.com') // Your Gmail Username
->setPassword('my_secure_gmail_password'); // Your Gmail Password
// Mailer
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject Here')
->setFrom(array('sender#example.com' => 'Sender Name')) // can be $_POST['email'] etc...
->setTo(array('receiver#example.com' => 'Receiver Name')) // your email / multiple supported.
->setBody('Here is the <strong>message</strong> itself. It can be text or <h1>HTML</h1>.', 'text/html');
// Send the message
if ($mailer->send($message)) {
echo 'Mail sent successfully.';
} else {
echo 'I am sure, your configuration are not correct. :(';
}
<?php
date_default_timezone_set('America/Toronto');
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = "gdssdh";
//$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
//$mail->Host = "ssl://smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$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->Username = "user#gmail.com"; // GMAIL username
$mail->Password = "password"; // GMAIL password
$mail->SetFrom('contact#prsps.in', 'PRSPS');
//$mail->AddReplyTo("user2#gmail.com', 'First Last");
$mail->Subject = "PRSPS password";
//$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address = "user2#yahoo.co.in";
$mail->AddAddress($address, "user2");
//$mail->AddAttachment("images/phpmailer.gif"); // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
SwiftMailer can send E-Mail using external servers.
here is an example that shows how to use a Gmail server:
require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";
//Connect to localhost on port 25
$swift =& new Swift(new Swift_Connection_SMTP("localhost"));
//Connect to an IP address on a non-standard port
$swift =& new Swift(new Swift_Connection_SMTP("217.147.94.117", 419));
//Connect to Gmail (PHP5)
$swift = new Swift(new Swift_Connection_SMTP(
"smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS));
As of May 30, 2022, Google will no longer support the use of third-party applications and devices that allow you to sign in to your Google Account with your username and password.
However, there is an easy solution provided by Google.
Instead of a password, input an app password generated by Google. Firstly, go to the settings and enable 2-Step Verification.
Then click on the App passwords.
You should see the App passwords screen. App passwords let you sign in to your Google Account from apps on devices that don't support 2-Step Verification. Select Mail as the app and then select a device. In my case, I chose Other, because I want to deploy my application to the cloud.
Once done, click on the GENERATE button. You will see your generated app password.
Just copy the password and replace the previous password in your email sending service with the generated one. You won't be able to see the password again though.
That's it!
The code as listed in the question needs two changes
$host = "ssl://smtp.gmail.com";
$port = "465";
Port 465 is required for an SSL connection.
Send Mail using phpMailer library through Gmail
Please donwload library files from Github
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
*/
//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 '../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';
// 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'), dirname(__FILE__));
//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!";
}
I had this problem also. I set the correct settings and have enabled less secure apps but it still did not work. Finally, I enabled this https://accounts.google.com/UnlockCaptcha, and it worked for me.
To install PEAR's Mail.php in Ubuntu, run following set of commands:
sudo apt-get install php-pear
sudo pear install mail
sudo pear install Net_SMTP
sudo pear install Auth_SASL
sudo pear install mail_mime
Gmail requires port 465, and also it's the code from phpmailer
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 email using SMTP 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
I have a solution for GSuite accounts that doesnt have the "#gmail.com" sufix. Also I think it will work for GSuite accounts with the #gmail.com but havent tried it.
First you should have the privileges to change the option "allos¿w less secure app" for your GSuite account. If you have the privileges (you can check in account settings->security) then you have to deactivate "two step factor authentication" go to the end of the page and set to "yes" for allow less secure applications. That's all. If you dont have privileges to change those options the solution for this thread will not work. Check https://support.google.com/a/answer/6260879?hl=en to make changes to "allow less..." option.
I tried the suggestion offered by #shasi kanth, but it didn't work out. I read the documentation and there are few changes made. So I managed to send mail via Gmail using this code, where vendor/autoload.php is got by composer with composer require "swiftmailer/swiftmailer:^6.0":
<?php
require_once 'vendor/autoload.php';
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))->setUsername ('SendingMail')->setPassword ('Password');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message('test'))
->setFrom(['Sending mail'])
->setTo(['Recipient mail'])
->setBody('Message')
;
$result = $mailer->send($message);
?>
Set
'auth' => false,
Also, see if port 25 works.

how to send smtp mail from localhost

I always get this message when trying to send email from my local host.
SMTP Error: Could not connect to SMTP host. Message could not be sent.
Mailer Error: SMTP Error: Could not connect to SMTP host.
below is my code: please help
<?php
// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
// When we unzipped PHPMailer, it unzipped to
// public_html/PHPMailer_5.2.0
require("class.phpmailer.php");
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_PHPMailer#bradm.inmotiontesting.com
// pass: password
$mail->Username = "project#reliable.com.pk"; // SMTP username
$mail->Password = "Nov112014"; // SMTP password
// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
$mail->From = $email;
// below we want to set the email address we will be sending our email to.
$mail->AddAddress("mani9418#gmail.com", "Usman Ali Siddiqui");
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "You have received feedback from your website Etutionhub!";
// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body = $message;
$mail->AltBody = $message;
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
Open the php.ini. For XAMPP, it is located in C:\XAMPP\php\php.ini. Find out if you are using WAMP or LAMP server.
Note: Make a backup of php.ini file.
Search [mail function] in the php.ini file.
You can find like below.
[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 = postmaster#localhost
Change the localhost to the smtp server name of your ISP. No need to change the smtp_port. Leave it as 25. Change sendmail_from from postmaster#localhost to your domain email address which will be used as from address.
So for me, it will become like this.
[mail function]
; For Win32 only.
SMTP = smtp.example.com
smtp_port = 25
; For Win32 only.
sendmail_from = info#example.com
Restart the XAMPP or WAMP(apache server) so that changes will start working.
Now try to send the mail using the mail() function.
mail("example#example.com","Success","Great, Localhost Mail works");
Mail will be sent to example#example.com from the localhost with Subject line "Success" and body "Great, Localhost Mail works".
You can add this line
$mail->SMTPSecure = "ssl";
after
$mail->SMTPAuth = true;

Php mailer error: SMTP error

I am using php mailer class. I am getting :
SMTP Error: The following recipients failed: s_deshmukh88#hotmail.com
$mail = new phpMailer();
$body = "Hello, this is a test mail.";
//$body = preg_replace('/\\\\/','', $body); //Strip backslashes
$mail->IsSMTP(); // tell the class to use SMTP
//$mail->SMTPAuth = true; // enable SMTP authentication
//$mail->Port = 25; // set the SMTP server port
$mail->Host = "localhost"; // SMTP server
$mail->Username = "localhost"; // SMTP server username
$mail->Password = "password"; // SMTP server password
//$mail->SMTPSecure = "tls";
//$mail->IsSendmail(); // tell the class to use Sendmail
$mail->AddReplyTo("name#domain.com","First Last");
$mail->From = "name#domain.com";
$mail->FromName = "First Last";
$to = "s_deshmukh88#hotmail.com";
$mail->AddAddress($to);
$mail->Subject = "First PHPMailer Message";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap = 80; // set word wrap
$mail->MsgHTML($body);
$mail->IsHTML(true); // send as HTML
if($mail->Send()){
echo 'Message has been sent.';
}
What can be the reason ?
Just try to put SMTPAuth to false and Host to'localhost'.
Thanks !! :)
I had this problem using authenticated SMTP. When I tested my mailing from home using xampp but connected to a (shared) server, emails went to users without problems. When I tried the same thing with the PHP on the host server, emails went through to addresses on my account but NOT to external addresses. (Ie. if my address is fred#bloggs.com and I send an email to fred#bloggs.com, it goes through but if I send it to jim#smith.com, it fails) The solution turned out to be to use the full host address when working on my local pc, ie $mail->Host = "mail.fred.bloggs.com", but $mail->Host = "localhost" on the server. May seem perverse but it works.
I just ran into this issue, and in my case, i believe it was the webhost's mail server that was not allowing a non-matching domain name for the From address. So for example, i was using mail.mydomain.com to send mail, but i wanted the from address to be test#test.com
When i switched the from address to test#mydomain.com, then the email was getting sent.

Send email using the GMail SMTP server from a PHP page

I am trying to send an email via GMail's SMTP server from a PHP page, but I get this error:
authentication failure [SMTP: SMTP server does no support authentication (code: 250, response: mx.google.com at your service, [98.117.99.235] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)]
Can anyone help? Here is my code:
<?php
require_once "Mail.php";
$from = "Sandra Sender <sender#example.com>";
$to = "Ramona Recipient <ramona#microsoft.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
$host = "smtp.gmail.com";
$port = "587";
$username = "testtest#gmail.com";
$password = "testtest";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>
// Pear Mail Library
require_once "Mail.php";
$from = '<fromaddress#gmail.com>';
$to = '<toaddress#yahoo.com>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
$smtp = Mail::factory('smtp', array(
'host' => 'ssl://smtp.gmail.com',
'port' => '465',
'auth' => true,
'username' => 'johndoe#gmail.com',
'password' => 'passwordxxx'
));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo('<p>' . $mail->getMessage() . '</p>');
} else {
echo('<p>Message successfully sent!</p>');
}
Using Swift mailer, it is quite easy to send a mail through Gmail credentials:
<?php
require_once 'swift/lib/swift_required.php';
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
->setUsername('GMAIL_USERNAME')
->setPassword('GMAIL_PASSWORD');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test Subject')
->setFrom(array('abc#example.com' => 'ABC'))
->setTo(array('xyz#test.com'))
->setBody('This is a test mail.');
$result = $mailer->send($message);
?>
Your code does not appear to be using TLS (SSL), which is necessary to deliver mail to Google (and using ports 465 or 587).
You can do this by setting
$host = "ssl://smtp.gmail.com";
Your code looks suspiciously like this example which refers to ssl:// in the hostname scheme.
I don't recommend Pear Mail. It has not been updated since 2010. Also read the source files; the source code is almost outdated, written in PHP 4 style and many errors / bugs have been posted (Google it). I am using Swift Mailer.
Swift Mailer integrates into any web application written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.
Send emails using SMTP, sendmail, postfix or a custom Transport
implementation of your own.
Support servers that require username & password and/or encryption.
Protect from header injection attacks without stripping request data
content.
Send MIME compliant HTML/multipart emails.
Use event-driven plugins to customize the library.
Handle large attachments and inline/embedded images with low memory
use.
It is a free and open source you can Download Swift Mailer and upload to your server. (The feature list is copied from owner website).
The working example of Gmail SSL/SMTP and Swift Mailer is here...
// Swift Mailer Library
require_once '../path/to/lib/swift_required.php';
// Mail Transport
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
->setUsername('username#gmail.com') // Your Gmail Username
->setPassword('my_secure_gmail_password'); // Your Gmail Password
// Mailer
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject Here')
->setFrom(array('sender#example.com' => 'Sender Name')) // can be $_POST['email'] etc...
->setTo(array('receiver#example.com' => 'Receiver Name')) // your email / multiple supported.
->setBody('Here is the <strong>message</strong> itself. It can be text or <h1>HTML</h1>.', 'text/html');
// Send the message
if ($mailer->send($message)) {
echo 'Mail sent successfully.';
} else {
echo 'I am sure, your configuration are not correct. :(';
}
<?php
date_default_timezone_set('America/Toronto');
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = "gdssdh";
//$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
//$mail->Host = "ssl://smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$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->Username = "user#gmail.com"; // GMAIL username
$mail->Password = "password"; // GMAIL password
$mail->SetFrom('contact#prsps.in', 'PRSPS');
//$mail->AddReplyTo("user2#gmail.com', 'First Last");
$mail->Subject = "PRSPS password";
//$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address = "user2#yahoo.co.in";
$mail->AddAddress($address, "user2");
//$mail->AddAttachment("images/phpmailer.gif"); // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
SwiftMailer can send E-Mail using external servers.
here is an example that shows how to use a Gmail server:
require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";
//Connect to localhost on port 25
$swift =& new Swift(new Swift_Connection_SMTP("localhost"));
//Connect to an IP address on a non-standard port
$swift =& new Swift(new Swift_Connection_SMTP("217.147.94.117", 419));
//Connect to Gmail (PHP5)
$swift = new Swift(new Swift_Connection_SMTP(
"smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS));
As of May 30, 2022, Google will no longer support the use of third-party applications and devices that allow you to sign in to your Google Account with your username and password.
However, there is an easy solution provided by Google.
Instead of a password, input an app password generated by Google. Firstly, go to the settings and enable 2-Step Verification.
Then click on the App passwords.
You should see the App passwords screen. App passwords let you sign in to your Google Account from apps on devices that don't support 2-Step Verification. Select Mail as the app and then select a device. In my case, I chose Other, because I want to deploy my application to the cloud.
Once done, click on the GENERATE button. You will see your generated app password.
Just copy the password and replace the previous password in your email sending service with the generated one. You won't be able to see the password again though.
That's it!
The code as listed in the question needs two changes
$host = "ssl://smtp.gmail.com";
$port = "465";
Port 465 is required for an SSL connection.
Send Mail using phpMailer library through Gmail
Please donwload library files from Github
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
*/
//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 '../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';
// 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'), dirname(__FILE__));
//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!";
}
I had this problem also. I set the correct settings and have enabled less secure apps but it still did not work. Finally, I enabled this https://accounts.google.com/UnlockCaptcha, and it worked for me.
To install PEAR's Mail.php in Ubuntu, run following set of commands:
sudo apt-get install php-pear
sudo pear install mail
sudo pear install Net_SMTP
sudo pear install Auth_SASL
sudo pear install mail_mime
Gmail requires port 465, and also it's the code from phpmailer
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 email using SMTP 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
I have a solution for GSuite accounts that doesnt have the "#gmail.com" sufix. Also I think it will work for GSuite accounts with the #gmail.com but havent tried it.
First you should have the privileges to change the option "allos¿w less secure app" for your GSuite account. If you have the privileges (you can check in account settings->security) then you have to deactivate "two step factor authentication" go to the end of the page and set to "yes" for allow less secure applications. That's all. If you dont have privileges to change those options the solution for this thread will not work. Check https://support.google.com/a/answer/6260879?hl=en to make changes to "allow less..." option.
I tried the suggestion offered by #shasi kanth, but it didn't work out. I read the documentation and there are few changes made. So I managed to send mail via Gmail using this code, where vendor/autoload.php is got by composer with composer require "swiftmailer/swiftmailer:^6.0":
<?php
require_once 'vendor/autoload.php';
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))->setUsername ('SendingMail')->setPassword ('Password');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message('test'))
->setFrom(['Sending mail'])
->setTo(['Recipient mail'])
->setBody('Message')
;
$result = $mailer->send($message);
?>
Set
'auth' => false,
Also, see if port 25 works.

Categories