laravel swift-mailer exception "Expected response code 250 but got an empty response" using gmail smtp-relay (database queue driver) - laravel

the gmail smtp-relay works fine using the sync driver, but if we queue the email we this error. cleared config, cache, & restarted queue workers. tested in prod and dev, same results
[2021-01-24 20:04:22] production.ERROR: Expected response code 250 but got an empty response {"exception":"[object] (Swift_TransportException(code: 0): Expected response code 250 but got an empty response at /home/****/****/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:448)
were wondering is this because of serialization and something is not making it through that process???
using latest stable release of laravel >8.0. gmail smtp is authenticating just fine, per why the sync driver sends emails easily. maybe there needs to be a timeout on the queue jobs so they dont barrage gmail so quickly? also our code works fine using sendgrid for example as the smtp relay. thanks.

See https://laracasts.com/discuss/channels/laravel/laravel-swift-mailer-exception-expected-response-code-250-but-got-an-empty-response-using-gmail-smtp-relay-database-queue-driver
Update your AppServiceProvider.php
add this inside boot();
// Fix for SwiftMailer Service;
$_SERVER["SERVER_NAME"] = "your.domain.name";

For users of smtp-relay.gmail.com, if you use localhost/127.0.0.1 as domain during developments, you probably need to change the domain name to use in EHLO command to begin the transaction. I solved this by adding &local_domain=dev.mydomain.tld at the and of my DSN.
smtp://smtp-relay.gmail.com:587?encryption=tls&local_domain=dev.mydomain.tld&...
For SwiftMailer Symfony bundle (since 2.4.0), you can set the local_domain config parameter:
// config/packages/dev/swiftmailer.yaml
swiftmailer:
...
local_domain: dev.mydomain.tld

Explanation for the 2 previous Answers
if $_SERVER["SERVER_NAME"] is the solution:
When you are using cron
The reason is that $_SERVER["SERVER_NAME"] is null when cron is executed. $_SERVER["SERVER_NAME"] is usually only defined for http access.
Example implementation (laravel):
if (!isset($_SERVER['SERVER_NAME'])) {
$url = config('env.APP_URL');
$domain = mb_ereg_replace("http(s)? ://", "", $url);
$domainParts = explode('/', $domain);
ini_set('server_name', count($domainParts) > 0 ? $domainParts[0] : $domain)
}
References :
Cron Job $_SERVER issue
https://github.com/swiftmailer/swiftmailer/issues/992
if 'local_domain' is the solution
When you have a mailhost setting of MAIL_HOST=smtp-relay.gmail.com in your laravel project
The reason is that if local_domain' is not set, the protocol for mail communication with Gmail will be EHLO [127.0.0.1]` and the communication will be disconnected.
By the way, I used gmail->gmail alias and did not need relay in the first place, so I solved the problem by setting MAIL_HOST=smtp.gmail.com.
References:
https://blog.trippyboy.com/2021/laravel/laravel-expected-response-code-250-but-got-an-empty-response/
I had to deal with both of them because of cron messaging and MAIL_HOST=smtp-relay.gmail.com in my environment.
I hope this information will help you.

Related

Socket.io support for WSO2 API Manager Websocket?

Does inbuilt WebSocket API in WSO2 APIM manager supports socket.io/nodejs based endpoint?
I have socket.io based websocket server (in NodeJS) And socket.io javascript client, in between we are using WSO2 API manager for authenticating websocket connections. But WSO2 fails to connect backend server and gives nothing in response.
I used access_token query parameter for passing Bearer token (from JavaScript client) and it seems working as no error. But WSO2 does not forward requests to endpoint.
Same works fine with native WebSocket server-client.
You can add the following logs to <AM_HOME>/repository/conf/log4j.properties to debug the issue further.
For APIM 3.x.x you can change it according to the log4j2 and add to log4j2.properties
log4j.logger.org.wso2.carbon.inbound.endpoint.protocol.websocket.InboundWebsocketSourceHandler=DEBUG log4j.logger.org.wso2.carbon.inbound.endpoint.protocol.websocket.InboundWebsocketResponseSender=DEBUG
log4j.logger.org.wso2.carbon.websocket.transport.WebSocketClientHandler=DEBUG
log4j.logger.org.wso2.carbon.websocket.transport.WebsocketTransportSender=DEBUG
Previous answer was for socket.io JS client, here is the same hack for socket.io python client.
Modify client.py file from /home/user/.local/lib/python3.6/site-packages/engineio
line no. 515
change this,
return ('{scheme}://{netloc}/{path}/?{query}'
'{sep}transport={transport}&EIO=3').format(...
to this,
return ('{scheme}://{netloc}/{path}?{query}'
'{sep}transport={transport}&EIO=3').format(...
Now, instead of directly modifying actual flow we can use conditional parameter.
if self.noslash == 'true':
return ('{scheme}://{netloc}/{path}?{query}'
'{sep}transport={transport}&EIO=3').format(...
else return original statement.
noslash parameter can be fetched from connect() function in both engineio and socketio library of python.
def connect(self, url, headers={}, transports=None,
engineio_path='engine.io', noslash=None):
self.noslash = noslash
Here is the sample connection string for python-socketio
sio.connect('http://localhost:9099', headers={'Authorization':'Bearer 90e8sf10-3s1w-495f-b20d-5a009f63193v'}, transports=['websocket'], socketio_path='/livefeed/v1', noslash='true')
finally I get rid of this issue. Yes, WSO2 APIM websocket supports socket.io js library that will be the first answer to my own query. More on that, here are some findings.
The actual reason for issue was request URL pattern used by socket.io library and WSO2 APIM. Socket.io JS library make the final URL with / at the end of resource (reference), which is not accepted by query separation logic used by WSO2.
So in simple, this is acceptable
ws://localhost:9099/livefeed/v1?EIO=4&transport=websocket
but not this,
ws://localhost:9099/livefeed/v1/?EIO=4&transport=websocket
Solution:
After few discussions with WSO2 team, it was clear that it is impossible to implement changes at their end. So little hack in socket.io.js file worked for me.
line number - 2535
changed this,
_this.opts.path = _this.opts.path.replace(/\/$/, "") + "/";
to this,
if(typeof opts.noslash!== 'undefined' && opts.noslash== "true"){
_this.opts.path = _this.opts.path.replace(/\/$/, "");
}else{
_this.opts.path = _this.opts.path.replace(/\/$/, "") + "/";
}
and created socket using extra argument.
var socket = io.connect("http://localhost:9099?access_token=90e8sf10-3s1w-495f-b20d-5a009f63193v", { transports: ['websocket', 'polling'], path: '/livefeed/v1', noslash: 'true' });
I know this is not a actual solution, but it worked for me.

SwiftMailer with Gmail SMTP suddenly stopped working: Connection could not be established with host smtp.gmail.com [ #0]

I have several websites that use SwiftMailer with Gmail. I haven't touched any of these sites' code, and suddenly all of them no longer work, resulting in Fatal errors: Connection could not be established with host smtp.gmail.com [ #0]
I've searched all over the internet for what may cause this, tried several solutions, but nothing works. Does anyone know if something either changed on Gmail's end (they no longer allow me to connect?) or what else could have happened?
Some things I tried:
open ports on server router (465 for SSL) - didn't help
disable firewall on server - didn't help
try the IP-address of smtp.gmail.com in stead of the domain name, using ping to find out the IP - didn't help
changing settings in the SwiftMailer program (setting certain verification options to false) - didn't help
I know this isn't a very concrete coding question, but I haven't changed anything to my code so the problem literally cannot be in my code. I'm just hoping someone knows what changed 2-3 days ago, and what I need to do to make SwiftMailer work again.
Note: the Gmail accounts' passwords or account security settings such as 2-step verification and sorts also didn't change. Also, using a different SMTP such as the one from GMX.net, the script still works just fine!
Strange hm?
I had the same issue today. I succesfully tried the workaround mentioned in this web.
Something has been changed in Gmail config. I will try a better solution but in the mean time will use this workaround.
Hope it help.
https://github.com/swiftmailer/swiftmailer/issues/544
You could disable the SSL check by modifying the function
"_establishSocketConnection" in StreamBuffer.php. Add these lines
before stream_socket_client command:
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
I would highly recommend you look into the logging plugin.
https://swiftmailer.symfony.com/docs/plugins.html#logger-plugin
It is likely to be already installed so all you need to do is follow the instructions in here and if you run the logger it will give you reasons why the email is failing.
While Toni's solution works it requires fiddling around with vendor source which is not ideal. You can also set the stream options programmatically in your code, where you use the swiftmailer $mailer instance, e.g.
$transport = $mailer->getTransport();
if($transport instanceof \Swift_Transport_EsmtpTransport){
$transport->setStreamOptions([
'ssl' => ['allow_self_signed' => true, 'verify_peer' => false, 'verify_peer_name' => false]
]);
}

Laravel Socialite InvalidStateException in AbstractProvider.php line 200

I'm building a web app in my local system (Ubuntu-14.04 64Bit) using laravel 5.3. I used Socialite to signin from social networks. I configured G+, Facebook, GitHug. I'm using Chromium as my default browser. Finally the problem is i'm getting
InvalidStateException in AbstractProvider.php line 200
frequently. i tried
php artisan cache:clear
php artisan config:clear
composer dump-autoload
these are helping to solve the issue temporarily, again the problem raising.
please help me in this issue..
I have the same issue and I've read a lot about this, that depend if the URL where you are at the moment of the login request has www. at the beginning or not.
Into config\services.php, if you have the redirect set as http://sitename.tld/callback/facebook the oauth works if you send the login request from sitename.tld, while if you try from www.sitename.tld you get the exception.
I haven't yet understood how to have it working with and without www at the beginning.
If the AbstractProvider.php line 200 fires the exception when the state of the user is not present means that the User cannot be created.
First check your code when you get the details from the provider(facebook, github) if you create a user and you return it.
If you have managed and logged in your app and you deleted the user from the user table remember to delete also the data from the socialite account table.
I was getting that exception because 'state' wasn't saved in session. But I was using asPopup method - Socialite::driver('facebook')->asPopup()->redirect(); so I saved session then - $request->session()->save();. So I solved this issue.
or try
session()->put('state', $request->input('state'));
$user = Socialite::driver('facebook')->user();
it works
I have same issue and solved in 3 steps;
add request on the top
use Illuminate\Http\Request;
Pass request object to function
public function handleProviderCallback(Request $request)
{
try {
$user = Socialite::driver('facebook')->user();
} catch (Exception $e) {
throw new Exception;
}
}
Clear cache.
php artisan cache:clear
I had the same error but my solution was a little different. I am posting here just in case someone else keeps hitting this post like I did for a possible answer.
I develop on Ubuntu 18.04 desktop since it is a server with a GUI. Socialite works great locally but as soon as I pushed/pulled the changes through git to the server, it quit.
I was running traces by recording what was sent to and from google. I "dd($_GET)" to get a raw dump before Socialite had a chance to get the info so I knew what was stored and ready for use. All info was there but Socialite didn't seem to "see" it. That is when I reasoned it was my apache2 header configuration interfering with the cookies/session data.
I had set header security in my apache2 configs. One of the settings was
Header always edit Set-Cookie ^(.*) "$1;HttpOnly;Secure;SameSite=Strict"
This setting was interfering with the cookie information that socialite needed. I removed that setting from my apache2 header config(by commenting out) and restarted Apache. Finally I removed all sessions in storage/framework/session/* and cleared them from my browser just to be sure. That worked for me.
After I got it working, one by one enabled and tested each of the following settings to have the framework secure what header info it can:
SESSION_SECURE_COOKIE=true
in my .env file
'http_only' => true, and
'same_site' => 'lax'(setting to "strict" did not seem to work)
in my config/session.php file.
Now it is back to testing security and tweaking things back if need be.

Bitbucket - Webhook keep returning error 500

Would like to check, I am fairly new to Bitbucket's new introduced webhook where previously i was using services where Bitbucket will execute a link to my site thus triggering a deployment script.
So since the old service is going to be depreciated soon, we all migrated to webhook instead. With the same implementation, I keep getting an error 500 upon commit/push/merge and there is no way for us to see the details for the error given. At first I thought it was my server giving problem but when i call the link manually via browsers and everything was fine. The deployment script can be executed successfully so then why bitbucket's webhook keeps telling me error 500?
Subsequently I find the guide given by Bitbucket was not helpful. There is no specified call method to the url stated so is the webhook initiates a GET or POST request? previously using services initiates a POST request. Then, are there any necessary payloads i need to include into the webhook URL? None is stated. Then, if there is an error at least let me see the error so I can fix it instead of telling me error 500.
I hope someone here can help me with this issue. Below are some specification of the site.
Server : Ubuntu LEMP 14.04 x64 Laravel framework 5.0
Webhook Url: bot.example.com/bitbucket/deploy/{Site API}
Method : GET
And when the abode link is call, it reaches a controller that does
public function attemptDeploy($site_api)
{
$script = 'nohup setsid php ~/scripts/deploy.php ' . $site_api. ' > /dev/null 2>&1 &';
exec($script);
return response('Deploy running.', 200);
}
Note that when i call this link manually either form browser or console everything works perfectly except from bitbucket's webhook. How can i solve this issue?
I was in the same situation. Bitbucket trims the body of the response and I couldn't see the error given by my server.
I've looked into the logs storage/logs/laravel.log and saw TokenMismatchException. Webhooks being API calls they don't store cookies or sessions so CSRF from Laravel breaks.
You need to add an exception from CSRF for the bitbucket deploy route. You can add this exception in app/Http/Middleware/VerifyCsrfToken.php. For example if your link is www.your_site.com/bit_deploy you will have:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'bit_deploy'
];
}
Hope that this helps you ... as I've lost 3 hours on this.
PS: at the time of writing this answer, bitbucket webhooks performs POST calls (not GET)

Joomla 1.5: why does trying to send email result in: PHPMAILER_RECIPIENTS_FAILED

I'm trying to send emails from Joomla! 1.5.9, but keep getting this error message: PHPMAILER_RECIPIENTS_FAILEDrecipient_name<recipient_email>
A few more facts:
It's a WAMP server (joomla 1.5.9, PHP 5.2.8)
Validation emails are sent with no problem at all
Joomla! is set to use SMTP
The IIS SMTP service is used (though I'm not 100% sure about it's configuration)
The diagnostics tool smtpdiag shows no problem when checking the sender/recipient
Any ideas?
Thanks,
Omer.
Perhaps this has already been answered before # Joomla forums itself.
http://forum.joomla.org/viewtopic.php?f=431&t=272547
I tried many of the solutions given in the link Sukumar provided but none of them worked.
Then I tried to use PHP mail function instead of SMTP and it worked :)
Change the following line in configuration.php in the root folder
var $mailer = 'smtp';
to
var $mailer = 'PHP mail';

Resources