Laravel 5.4 SMTP emails not working - php

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

Related

Laravel: Expected response code 354 but got code \"503\", with message \"503-All RCPT commands were rejected with this error

The Laravel mail() function works OK when I send emails to Gmail accounts from my company mail (sales#stopshoprei.com). But When I send it to my own company email domain accounts like 'info#360synergytech.com' from the same mail (sales#stopshoprei.com) it gives the error.
(Expected response code 354 but got code "503", with message
"503-All RCPT commands were rejected with this error:\r\n503-No Such
User Here\r\n503 Valid RCPT command must precede DATA\r\n"",).
Controller
public function mailSenderIntegration(Request $request)
{
$data = $request->input();
$crm_payment = CrmPayment::where('unique_Id', $data["unique_Id"])->first();
//data for client mail
$firstName = $crm_payment->first_name;
$services_choosed = $crm_payment->requested_services;
$services_choosed = json_decode($services_choosed);
$count_services = count($services_choosed);
$client_email = $crm_payment->email;
$mailData = [
'name' => $firstName,
'body' => "There's an integration you need which is not listed at
futureflippercrm.stopshoprei.com.
Our sales person would contact you soon for requirements.",
];
//Mail client
Mail::to($client_email)
->send(new mailTempInt($mailData));
}
.env
MAIL_DRIVER=smtp
MAIL_HOST=mail.stopshoprei.com
MAIL_PORT=465
MAIL_USERNAME=sales#stopshoprei.com
MAIL_PASSWORD=*******
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=sales#stopshoprei.com
MAIL_FROM_NAME="Future Flipper CRM"
I tried to change port but same result. Is this an issue with domain?

SwiftMailer test username and password

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".

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.

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