How to send email using Google OAuth (via SMTP)? - php

Have read this and this and using example from here.
However, I am still having difficulty in sending emails as a verified Google user using OAuth. I have the valid OAuth tokens, secrets, and xoauth token as well.
My code to send the email:
$authenticateParams = array('XOAUTH', $initClientRequestEncoded);
$smtp = new Zend_Mail_Protocol_Smtp('smtp.gmail.com', 587, array(
"AUTH" => $authenticateParams, 'ssl' => 'tls'));
try {
// Create a new mail object
$mail = new Zend_Mail();
$mail->setFrom("aaaaa#gmail.com");
$mail->addTo("bbbbb#gmail.com");
$mail->setSubject("Your account has been created");
$email = "Thank you for registering!";
$mail->setBodyText($email);
$mail->send();
} catch (Exception $e) {
echo "error sending email . <BR>" . $e;
}
But this seems to send an anonymous email and not as the user authenticated. If I do:
$smtp = new Zend_Mail_Transport_Smtp('smtp.gmail.com', array('AUTHENTICATE' => $authenticateParams, 'ssl' => 'tls'));
Zend_Mail::setDefaultTransport($smtp);
I get: exception 'Zend_Mail_Protocol_Exception' with message '5.5.1 Authentication Required.
I'm sure it's just a case of getting the mail transport smtp params right, but the documentation for sending SMTP emails is non-existent and I can't find any code examples for this.

Check out the following blog posts which will show you where you went wrong.
google smtp oauth2 authentication
send mail with gmail smtp and xoauth

Related

Can't receive emails sent from a Codeception test

I have a local Wordpress website that sends emails successfully, however if I try to send an email from a Codeception integration test, I do not receive any emails. (By the way, I don't think the problem has to do with Wordpress, which is why I'm posting here rather than Wordpress Stack Exchange).
I've configured Wordpress like this:
add_action( "phpmailer_init", array( $this, "configure_mailer" ) );
function configure_mailer( $mailer ) {
$mailer->isSMTP();
$mailer->Host = "smtp.gmail.com";
$mailer->SMTPAuth = true;
$mailer->Username = "myemail#gmail.com";
$mailer->Password = "mypassword";
$mailer->SMTPSecure = "tls";
$mailer->Port = 587;
$mailer->IsHTML( true );
}
Now if I try to send an email with wp_mail (which internally uses a PHPMailer instance configured as above) from my Wordpress code, eg. via an API request, I do receive the email:
// This is the custom API route that sends the email
register_rest_route( "mynamespace/v1", "/send-email", [
"methods" => \WP_REST_Server::CREATABLE,
"permission_callback" => "__return_true",
"callback" => function() {
$result = wp_mail( "myemail#example.com", "Test subject", "Test message", array( "From: MySite <myemail#example.com>");
return new \WP_REST_Response( $result );
}
]);
// This is the API request
POST https://example.com/wp-json/mynamespace/v1/send-email
The above request returns true because wp_mail returns true (as it does when an email is sent successfully), and I receive the email.
If I try to send the email from a Codeception integration test, the test succeeds because wp_mail still returns true, but I do not receive the email. (The \Codeception\TestCase\WPTestCase comes from wpbrowser, a package I use for testing Wordpress with Codeception).
class EmailTest extends \Codeception\TestCase\WPTestCase {
public function testSendsEmail() {
$result = wp_mail( "myemail#example.com", "Test subject", "Test message", array( "From: MySite <myemail#mysite.com>");
$this->assertTrue( $result );
}
}

Laravel 5.4 SMTP emails not working

I am using laravel 5.4 and configured gmail smtp details for sending emails. Below is code and return expection error.
Email Code:
try {
Mail::raw('Text', function ($message) {
$message->to('lpkapil#mailinator.com');
});
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
print_r($e->getCode());
echo "</pre>";
die();
}
Returned Execption Message & Error code
Error Message:
Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required
Error Code:
530
Gmail smtp details used:
MAIL_HOST: smtp.gmail.com
MAIL_PORT: 587
MAIL_ENCRYPTION: tls
username: gmail id
password: password
Please suggest a solution.
This is a easy way to send mails using Laravel.You can use this function on your controller. You have to make a blade template file as example "emailfile.blade.php" with what ever the details you want to show on the email and pass the variables to that blade using the inputs array as I mentioned below.
$inputs = array(
'name'=> 'Your Name',
'address' =>'Your Address',
'company' =>'Your Company',
);
Mail::send('emailfile', $inputs, function ($message) {
$message->from('sender#gmail.com', 'Sender Name');
$message->to('reciver#gmail.com',$name=null)->subject('Mail Subject!');
$message->cc('cc#gmail.com');
});

Amazon SES PHPMail or SDK

I've registered with Amazon SES service with email limit setup and out of the sandbox. I've tried many PHPMailer function and all return me as error : Connexion time out (110). Is it possible the send mail from PHPMailer?
I have seen on Amazon SES site this link.
<?php
// Replace path_to_sdk_inclusion with the path to the SDK as described in
// http://docs.aws.amazon.com/aws-sdk-php/v2/guide/quick-start.html
define('REQUIRED_FILE','path_to_sdk_inclusion');
// Replace sender#example.com with your "From" address.
// This address must be verified with Amazon SES.
define('SENDER', 'sender#example.com');
// Replace recipient#example.com with a "To" address. If your account
// is still in the sandbox, this address must be verified.
define('RECIPIENT', 'recipient#example.com');
// Replace us-west-2 with the AWS region you're using for Amazon SES.
define('REGION','us-west-2');
define('SUBJECT','Amazon SES test (AWS SDK for PHP)');
define('BODY','This email was sent with Amazon SES using the AWS SDK for PHP.');
require REQUIRED_FILE;
use Aws\Ses\SesClient;
$client = SesClient::factory(array(
'version'=> 'latest',
'region' => REGION
));
$request = array();
$request['Source'] = SENDER;
$request['Destination']['ToAddresses'] = array(RECIPIENT);
$request['Message']['Subject']['Data'] = SUBJECT;
$request['Message']['Body']['Text']['Data'] = BODY;
try {
$result = $client->sendEmail($request);
$messageId = $result->get('MessageId');
echo("Email sent! Message ID: $messageId"."\n");
} catch (Exception $e) {
echo("The email was not sent. Error message: ");
echo($e->getMessage()."\n");
}
?>
I've copy all the codes, put my variable instead of showned in the demo script. Now I'm getting the error : You must use KEY ans SECRET_KEY to use this script... Where I cant put my KEY and SECRETKEY in the script? There is no explanation on how to do this.
Is there another way send email throught Amazon SES service?
Thanks!
So simple. I have to add key and secret in :
$client = SesClient::factory(array(
'version'=> 'latest',
'region' => REGION,
'credentials' => array(
'key' => 'XXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXX',
)
));
and set XXXXXXXXXXXXXXXX full access to api in amazon security credentials
As far as I know PHP Mailer was not working with AWS SES by API, you should use SES SMTP with PHP Mailer.
The correct ports are 25, 465 or 587.

Gmail smtp 5.5.2 error with PHP ZEND and Xoauth2

I trying to send emails with Gmail using gmail api with xoauth authentication.
The IMAP example from google works fine.
I am trying to implement the thing based on these articles:
http://www.boxuk.com/blog/php-smtp-xoauth2-gmail/
http://www.chargenevier.com/2013/02/google-smtp-and-oauth2-authentication/
I get the following error when i try to send the email:
Fatal error: Uncaught exception 'Zend_Mail_Protocol_Exception' with message '5.5.2 Syntax error. e5sm17066681bkg.3 - gsmtp
I also tried the openssl method on the first article, after write in XOAUTH2 i get the same error from the server and connection is closed.
Interesting when i do echo base64_encode("user=\1auth=Bearer \1\1") i got a string whitch is more shorter than that when i echo the $smtpInitClientRequestEncoded variable what is generated with constructAuthString method, what is working fine in the IMAP example.
And mail.google.com gives 5.5.2 Cannot decode response for the shorter encoded string.
function constructAuthString($email, $accessToken) {
return base64_encode("user=$email\1auth=Bearer $accessToken\1\1");
}
function sendEmail($email,$accessToken){
$smtpInitClientRequestEncoded = constructAuthString($email, $accessToken);
echo '<br/><br/>BASE64: ' . $smtpInitClientRequestEncoded;
$config = array('ssl' => 'ssl',
'port' => '465',
'auth' => 'xoauth',
'xoauth_request' => $smtpInitClientRequestEncoded
);
$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
$mail = new Zend_Mail();
$mail->setBodyText('some body text');
$mail->setFrom($email, 'Some Sender');
$mail->addTo("myemail#gmail.com", 'Some Recipient');
$mail->setSubject('Test sending by smtp');
$mail->send($transport);
}
What do you think, what is wrong? Why dont this authenticates?
$accesToken was bad. I passed $client->getAccessToken(), but you need just the access_token string from this string, not the whole.

Swiftmailer config : send mail using gmail

I can send email from my pc using swiftmailer, but mail not sending in server.
I'm using swiftmailer 5.0.1. Project details are,
A simple php project in netbeans
swiftmailer 5.0.1
twig 1.13.1
My code is
public function init() {
$this->username = 'username#gmail.com';
$this->password = 'password';
$this->host = 'ssl://smtp.gmail.com';
$this->port = 465;
$this->from = 'username#gmail.com';
$this->subject = 'Company - contact';
$this->body_part_type = 'text/html';
}
public function send_email($from_name_add, $to_add, $fullname, $email, $mobile, $content) {
$this->init();
$transport = Swift_SmtpTransport::newInstance($this->host, $this->port)
->setUsername($this->username)
->setPassword($this->password);
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$cid = $message->embed(Swift_Image::fromPath('../public_html/pic/logo.png'));
$this->body = $this->renderEmailTemplate('email', $fullname, $email, $mobile, $content, $cid);
$message->setSubject($this->subject)
->setFrom(array('username#gmail.com' => '' . $from_name_add))
->setTo($to_add)
->setContentType($this->body_part_type)
->setBody($this->body);
$result = $mailer->send($message);
return $result;
}
This code works FINE in my pc. But after upload this code/project to server, mail not sending. Error is,
<br />
<b>Fatal error</b>: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host ssl://smtp.gmail.com [Connection timed out #110]' in /home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php:259
Stack trace:
#0 /home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php(64): Swift_Transport_StreamBuffer->_establishSocketConnection()
#1 /home/am***/lib/Swift/classes/Swift/Transport/AbstractSmtpTransport.php(115): Swift_Transport_StreamBuffer->initialize(Array)
#2 /home/am***/lib/Swift/classes/Swift/Mailer.php(80): Swift_Transport_AbstractSmtpTransport->start()
#3 /home/am***/controller/send_mail.php(54): Swift_Mailer->send(Object(Swift_Message))
#4 /home/am***/public_html/contact.php(43): send_mail->send_email('Am*** Inc', 'fe****#gma...', 'asdf', 'asdf#in.com', '111111111111', 'Testing mail')
#5 {main}
thrown in <b>/home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php</b> on line <b>259</b><br />
HINT: There is an allready running php symfony2 project in that server, this project can send mail successfully.
Here is the symfony2 code,
$message = \Swift_Message::newInstance()
->setSubject($sub)->setFrom($from)->setTo($to)->setContentType("text/html")
->setBody($this->renderView('FZAm***Bundle:Layout:mail.html.twig', array
('name' => $this->fullname, 'mobile' => $this->mobile, 'email' => $this->email,
'content' => $this->content, 'time' => $this->sys_time, 'ip' => $userip,
'server_time' => date('Y-m-d H:i:s'))
));
try {
$this->get('mailer')->send($message);
// catch and other follows.
Config details are,
mail_contact_from: username#gmail.com
mail_contact_to: username#gmail.com
mail_contact_sub: Contact info
I passed only this details and all settings are default. If any info needed please ask i'l post.
Reason i'm changing from symfony2 project to this ordinary php+swift+twig is my hosting is only 100mb and i need to upload more images. But symfony2 occupy more space.
Looks like your live server is missing OpenSSL, so you need to enable it in order to get secure connections working (i.e. enable the php_openssl module). Also check this question.
After some search in google.
To send mail using gmail auth you need to use this code,
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465);
This is the correct way to send mail. This mail will be send by gmail.
PHP use mail() to send just a mail,
mail($to,$subject,$message,$headers);
This code sends a mail using php code.
Swiftmailer can also send a mail using this php mail() function,
Here is swift code.
$transport = Swift_MailTransport::newInstance();
// nothing inside ()
The problem in this mail is, gmail displays following message,
This message may not have been sent by: username#gmail.com
Sometimes this mail will go to spam.

Categories