SwiftMailer test username and password - php

I really don't know if this is about SwiftMailer or mailtrap.io but the problem is when I try to establish a SMTP connection to said service (mailtrap.io) I never get any errors, even if I don't use any username or password. Am I not supposed to get any authentication errors when not using any username or password? Or am I doing this the wrong way?
This is the method I use to test if the dynamic connection can be made before I store it in the .env file.
/**
* E-mail configuration
*
* #param Request $request
* #return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
*/
public function postEmailConfiguration(Request $request)
{
# Try connecting to the SMTP
try {
$encryption = $request->input('encryption');
if ($encryption == 'null') {
$encryption = NULL;
}
$transport = new Swift_SmtpTransport($request->input('host'), $request->input('port'), $encryption);
$transport->setUsername($request->input('username'));
$transport->setPassword($request->input('password'));
$mailer = new Swift_Mailer($transport);
$mailer->getTransport()->start();
# Update .env file
$this->setEnvironmentValues([
'MAIL_HOST' => $request->input('host'),
'MAIL_PORT' => $request->input('port'),
'MAIL_USERNAME' => $request->input('username'),
'MAIL_PASSWORD' => $request->input('password'),
'MAIL_ENCRYPTION' => $request->input('encryption')
]);
return redirect()->back()->with('success', 'Connection to SMTP establised and saved!');
}
# Could not connect to SMTP
catch (Swift_TransportException $e) {
return redirect()->back()->with('error', 'Could not connect to SMTP server.<br>Error: ' . $e->getMessage());
}
# Could not connect to SMTP
catch (Exception $e) {
return redirect()->back()->with('error', 'Could not connect to SMTP server.<br>Error: ' . $e->getMessage());
}
}

I tested a connection to Gmail with SwiftMailer 6 on Symfony 4.4 and the code below (it's similar to yours) works as expected for me.
So if you want to check if the connection is established without a message sending use the next code:
public function checkConnection()
{
try {
// Create the Transport
$transport = (new \Swift_SmtpTransport(
'smtp.gmail.com',
'587',
'tls'
))
->setUsername('your.username#gmail.com')
->setPassword('yourSuperPassword');
// Create the Mailer using your created Transport
$mailer = new \Swift_Mailer($transport);
$mailer->getTransport()->start();
return true;
} catch (\Swift_TransportException $e) {
return $e->getMessage();
} catch (\Exception $e) {
return $e->getMessage();
}
}
otherwise, it throws an exception:
Swift_TransportException:
Failed to authenticate on SMTP server with username "your.username#gmail.com" using 3 possible authenticators. Authenticator LOGIN returned Expected response code 235 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials z7sm3020898ljj.98 - gsmtp".
Authenticator PLAIN returned Expected response code 235 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials z7sm3020898ljj.98 - gsmtp".
Authenticator XOAUTH2 returned Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials z7sm3020898ljj.98 - gsmtp".

Related

Can't send mail with Gmail

I'm trying to send an email when a user is subscribing in my web site.
To save me time ... I'm using Swift_Mailer with Symfony.
First, I tried to send a mail with the console :
php .\bin\console swiftmailer:email:send
And that's working, the mail was sent and the client received it.
So now I said to myself, I will be able to send emails with the code.
That's my Controller code :
public function register(Request $request, \Swift_Mailer $mailer)
{
// Here saving new user in the database
$this->sendMail($user->getEMail(), $mailer);
$content = $this->renderView("register.html.twig");
return new Response($content);
}
private function sendMail($email, \Swift_Mailer $mailer)
{
$message = (new \Swift_Message('Hello Email'))
->setFrom(['my.email#gmail.com' => "my name"])
->setTo($email)
->setBody('Here is the message itself');
$mailer->send($message);
}
And That's my .env file :
MAILER_URL=gmail://my.email#gmail.com:myPasswordHere#localhost
When I'm trying to send the mail, no error, I tried this StackOverflow link, but no problem, echo "Successfull", but nothing in the Gmail send box and nothing my client email box.
Can you please help me to ... save me time ^^
------------------------------------------------------------- EDIT 1 ------------------------------------------------------------
I never edited the config/packages/swiftmailer.yaml file, that's it's content :
swiftmailer:
url: '%env(MAILER_URL)%'
spool: { type: 'memory' }
------------------------------------------------------------- EDIT 2 ------------------------------------------------------------
I also tryed to make a new transporter with this code :
$transport = (new \Swift_SmtpTransport('smtp.gmail.com', 465))
->setUsername('my.email#gmail.com')
->setPassword('myPasswordHere');
$mailer = new \Swift_Mailer($transport);
And that's the error I get : Connection could not be established with host smtp.gmail.com [php_network_getaddresses: getaddrinfo failed: Unknown host. #0]
------------------------------------------------------------- EDIT 3 ------------------------------------------------------------
I've got a swiftmailer.yaml fil in the config/packages/dev folder and that's it's default content :
# See https://symfony.com/doc/current/email/dev_environment.html
swiftmailer:
# send all emails to a specific address
#delivery_addresses: ['me#example.com']
I tried to put the same content as in the config/packages/swiftmailer.yaml, but no result.
I don't see something like this in your code:
// Create the Transport
$transport = (new \Swift_SmtpTransport('mail hoster etc', port))
->setUsername('your email')
->setPassword('your password');
// Create the Mailer using your created Transport
$mailer = new \Swift_Mailer($transport);
Maybe it's a reason why your mails isn't sent.

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');
});

Using aws smtp mail service in laravel 5.4 application

I want to send a mail to the company's office mail(other than email field for login) when a candidate appy for the job posting
Controller function
public function ImmediateApply(Request $request) {
try {
$request['resume'] = $this->image->uploadImage($request->resume, 'resumes');
if (ImmediateApply::where('job_post_id', '=', $request->job_post_id)->where('email', '=', $request->email)->count() == 0) {
$application = ImmediateApply::create($request->all());
$job = JobPost::find($request->job_post_id);
$company = Company::find($job->company_id);
$company->notify(new JobApplication($job));
return response()->json([
'message' => 'You have applied successfully',
'code' => '201']);
}
} catch (Exception $e) {
return response()->json([
'message' => $e->getMessage(),
'code' => 400,
], 400);
}
}
company model
public function routeNotificationForMail() {
return $this->office_mail;
}
Now I'am getting the error
1.Failed to authenticate on smtp server with username "x" using 2
possible authenticators
2.CredentialsException in InstanceProfileProvider.php line 79: Error
retrieving credentials from the instance profile metadata server.
(Error creating resource: [message]
fopen(http://169.254.169.254/latest/meta-data/iam/security-credentials/):
failed to open stream: Connection timed out [file]
/var/www/html/jobs-website/laravel5.4/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php
[line] 312)
But when i check in smtp online test, I'am recieving the mail correctly
Actually i don't know the reason for the 1st error.It doesn't persist now.
Changing
MAIL_DRIVER = ses
from
MAIL_DRIVER = smtp
solved the 2nd error.
now everything working fine.

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.

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

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

Categories