Sending Email with Laravel swiftmailer (Connection could not be established) - laravel

When trying to send email using laravel swiftmailer & using smtp.gmail.com my php.ini ssl connection is open already but still get these errors
my .env file code
MAIL_DRIVER=mail
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=dg.shahneel21321#gmail.com
MAIL_PASSWORD=example123
MAIL_ENCRYPTION=tsl
Error # 1 (when using MAIL_ENCRYPTION=tsl)
Connection could not be established with host smtp.gmail.com :stream_socket_client(): unable to connect to tsl://smtp.gmail.com:587 (Unable to find the socket transport "tsl" - did you forget to enable it when you configured PHP?)
Error # 2 (when using MAIL_ENCRYPTION=ssl)
Connection could not be established with host smtp.gmail.com :stream_socket_client(): SSL: An existing connection was forcibly closed by the remote host.
I also tried already give solution on stackoverflow
add this to mail.php
'stream' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
],
also adding the following lines to _establishSocketConnection() in
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
Please help!! Thanks in advance

Related

Laravel websockets with nginx

I have followed tutorials to configure laravel with websockets using docker, except that my php version is PHP 8.1.9, and laravel 8.
My nginx container is a reverse proxy to web_dev container, and does SSL termination. So further communication internally is over http.
nginx.conf
server {
listen 80;
server_name mydomain.co.uk *.mydomain.co.uk;
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name mydomain.co.uk *.mydomain.co.uk;
include common.conf;
include ssl.conf;
location / {
include common_location.conf;
proxy_pass http://web_dev;
}
}
server {
listen 6001 ssl;
server_name mydomain.co.uk *.mydomain.co.uk;
include common.conf;
include ssl.conf;
location /ws {
proxy_read_timeout 60;
proxy_connect_timeout 60;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_cache_bypass $http_upgrade;
proxy_set_header Sec-WebSocket-Key 'SGVsbG8sIHdvcmxkIQAAAA==';
proxy_set_header Sec-WebSocket-Version '13';
include common_location.conf;
proxy_pass http://web_dev:6001/;
}
}
Then I have a curl command:
curl -k \
--no-buffer \
--header "Connection: upgrade" \
--header "Upgrade: websocket" \
-v \
https://mydomain.co.uk:6001/ws/app/mydomainkey
This is the output:
Connected to mydomain.co.uk (127.0.0.1) port 6001 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* TLSv1.0 (OUT), TLS header, Certificate Status (22):
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS header, Certificate Status (22):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
....
* TLSv1.2 (IN), TLS handshake, Finished (20):
* TLSv1.2 (OUT), TLS header, Supplemental data (23):
> GET /ws/app/mydomainkey HTTP/1.1
> Host: mydomain.co.uk:6001
> User-Agent: curl/7.81.0
> Accept: */*
> Connection: upgrade
> Upgrade: websocket
>
* TLSv1.2 (IN), TLS header, Supplemental data (23):
* Mark bundle as not supporting multiuse
< HTTP/1.1 101 Switching Protocols
< Server: nginx/1.21.5
< Date: Sun, 04 Sep 2022 12:00:33 GMT
< Connection: upgrade
< Upgrade: websocket
< Sec-WebSocket-Accept: 5Tz1rM6Lpj3X4PQub3+HhJRM11s=
< X-Powered-By: Ratchet/0.4.4
< Strict-Transport-Security: max-age=31536000; includeSubDomains
<
* TLSv1.2 (IN), TLS header, Supplemental data (23):
�r{"event":"pusher:connection_established","data":"{\"socket_id\":\"155833011.137698690\",\"activity_timeout\":30}"}
This I think shows that the port 6001 and the SSL are configured correctly and that the websocket connection was established.
When I go to the url for websockets dashboard and click connect, I get
WebSocket connection to 'wss://mydomain.co.uk:6001/ws/app/bookhaircut?protocol=7&client=js&version=4.3.1&flash=false' failed:
I also tried fetch("wss://mydomain.co.uk:6001/ws/app/mydomainkey?protocol=7&client=js&version=4.3.1&flash=false"); which gives a different error:
On the web_dev container, I'm running supervisor which runs php artisan websockets:serve. I can verify that my web_dev container can connect to its websockets running service, because I ran in php artisan tinker:
`event (new \App\Events\NewTrade('test'))`
=> []
Then I checked supervisor logs I get many entries:
So in conclusion:
nginx is serving correctly because curl command works correctly with nginx with SSL (this also generates log entries in supervisor)
laravel is internally connecting correctly
But pusher-js in web browser is complaining that wss scheme is not supported and that websocket connection failed. My nginx version: nginx/1.21.5
I'm not even using Echo yet. Echo uses pusher-js, and the dashboard is implemented using pusher-js. So if the dashboard doesn't work, nor will my Echo work.
I have now down-graded my pusher to 4.3.1 in package.json but that didn't do anything because the version is hardcoded in the dashboard (also 4.3 though).
Any ideas?
I tried to modify the dashboard to pull a different version https://cdnjs.cloudflare.com/ajax/libs/pusher/6.0.3/pusher.js
And that didnt make any difference.
Could nginx support wss instead of http? I have only seen configs with http. Configs with wss: throw an error.
So I'm out of ideas.
Here's my config files:
websockets.php
'apps' => [
[
'id' => env('PUSHER_APP_ID'),
'name' => env('APP_NAME'),
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'path' => "/ws",
'capacity' => null,
'enable_client_messages' => false,
'enable_statistics' => true,
],
],
/* ssl is left empty.*/
related problems:
https://github.com/beyondcode/laravel-websockets/issues/102
How I found out:
I first tried to set SSL cert for the internal communication despite nginx doing termination (I had to try it) - but then the curl command broke, I couldn't connect to my websockets unless I removed my SSL certificates (was getting bad gateway).
So I ended up with these:
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => false,
'host' => "127.0.0.1",
'port' => 6001,
'useTLS' => false,
'scheme' => 'http',
],
],
And in config/websockets.php
'apps' => [
[
'id' => env('PUSHER_APP_ID'),
'name' => env('APP_NAME'),
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'path' => "/ws", //<-- important for nginx path detection
'capacity' => null,
'enable_client_messages' => false,
'enable_statistics' => true,
],
],
'ssl' => [
'local_cert' => null,
'local_pk' => null,
'passphrase' => null,
],
Then I noticed one thing about logging. When I got the websocket error in the browser, I was also receiving a new logging entry for my supervisor/websocket.log.
I tried to remove the 'path' => "/ws", and I received the same exact browser error but no log entry.
That gave me the fist hint when something is better than nothing. And I needed to stick to any settings that would not break this logging feature.
Then I found that when I remove these lines from nginx.conf, it started all working, shockingly!!
proxy_set_header Sec-WebSocket-Key 'SGVsbG8sIHdvcmxkIQAAAA==';
proxy_set_header Sec-WebSocket-Version '13';
Originally I added these so I could simplify the curl command. But I didn't know that this would brake the browser's websockets. So the curl for testing now looks like this:
curl -k \
--no-buffer \
--header "Connection: upgrade" \
--header "Upgrade: websocket" \
--header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQAAAA==" \ //<-- this is random you can use it
--header "Sec-WebSocket-Version: 13" \
-v \
https://mydomain.co.uk:6001/ws/app/mydomainkey

Laravel-websocket can't connect to Azure VM through apache2

I want to implement Laravel-WebSocket + pusher substitute (https://github.com/beyondcode/laravel-websockets) with Laravel-echo on an Azure VM with apache2 reverse proxy. However, no matter what I tried, they just can't connect. It's always between error 404, 502 and 500 when a client-side listener tries to connect.
This VM only allows entry through 80 and 443. Therefore, I did reverse proxy which redirects '/WebSocket' to http://127.0.0.1:6001 (where the WebSocket runs. TCP) The server is under https. I've tried to modify server .conf file to no avail. I've tried to enable/disable SSL and encrypted as well. I tried to directly access 127.0.0.1:6001 within the VM using elinks, but with http I got 'error connecting to socket' with https I got 'SSL error'. I'm fairly sure that the request at least reached the machine, as if I shut down the WebSocket server the error changes into 503 Service not available. Also, I can see apache2 error logs as requests being made. Most of the time it is 502 proxy error. (AH01102: error reading status line from remote server 127.0.0.1:6001) If I tweak SSL settings it generally changes to 404, which I take as a sign of incorrect certificate/key in this case. The firewall is open.
I've tried every guide I can find. Most of them are about nginx, which I can't change to. If possible I would rather not set up another virtual host.
This is in websocket.php:
....
'apps' => [
[
'id' => env('PUSHER_APP_ID'),
'name' => env('APP_NAME'),
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'enable_client_messages' => false,
'enable_statistics' => true,
],
]
....
'ssl' => [
'local_cert' => 'my_self_signed_cert.pem',
'local_pk' => 'my_key.pem',
'passphrase' => null,
]
...
This is the pusher setting in broadcasting.php:
...
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'host' => env('PUSHER_APP_HOST'),
'port' => env('PUSHER_APP_PORT'),
'scheme' => 'https',
'encrypted' => true,
],
]
...
I tried 127.0.0.1 as the host and 6001 as the port as default, then I followed this guide: https://42coders.com/setup-beyondcode-laravel-websockets-with-laravel-forge/ and changed them to my-domain-name and 443 respectively (the websocket is still running on 6001).
This is the echo definition in /resources/js/bootstrap.js (suggested by the package documentation):
import Echo from "laravel-echo";
window.Pusher = require("pusher-js");
window.Echo = new Echo({
broadcaster: "pusher",
key: "my-pusher-key",
wsHost: window.location.hostname + '/websocket',
wsPort:443,
disableStats: true,
});
This is the apache2 setting:
<VirtualHost *:443>
ServerName my_server_name
RequestHeader unset x-forwarded-host
...
SSLEngine on
SSLCertificateFile my-self-cert
SSLCertificateKeyFile my-key
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off
ProxyPreserveHost On
<Location /websocket>
ProxyPass "http://127.0.0.1:6001" Keepalive=On
ProxyPassReverse "http://127.0.0.1:6001"
</Location>
...
RewriteEngine on
RewriteCond %{HTTP:UPGRADE} websocket [NC]
RewriteCond %{HTTP:CONNECTION} Upgrade [NC]
RewriteRule /(.*) http://127.0.0.1:6001/$1 [P,L]
ProxyRequests Off
</VirtualHost>
Changing the http to ws or wss will trigger the error 'No protocol handler was valid', despite the fact that I already included the wstunnel module.
I expect the WebSocket console to immediately react as soon as the listener subscribes to the broadcast channel.
OK, this issue has finally been resolved! The way to do it is to set up a separate server (https) as a dedicated WebSocket server. Please follow this guide:
https://42coders.com/setup-beyondcode-laravel-websockets-with-laravel-forge/
It looks like the setting has to be on https or the WebSocket server can't receive a response from the backend. Also, I encountered a strange problem where Pusher.php in vendor/pusher/pusher-php-server misses about 400 lines of code, several other files are also missing despite it has the same version of this package (~3.0) as my local implementation. If you get call to undefined method when the WebSocket server receives broadcast event, this is likely the reason. If you can't connect to the websocket on Chrome, but you can on firefox, you need to disable verify-peers, please check the section on Laravel Velvet in the Laravel-Websockets document for more details (even if you don't use Laravel Velvet)

Getting Unauthorized error trying to send email with Sparkpost (Laravel 5.4)

I've been following the Laravel Mail docs https://laravel.com/docs/5.4/mail to send email via a SparkPost account. When I try and send I'm getting
ClientException
Client error: `POST https://api.sparkpost.com/api/v1/transmissions` resulted in a `401 Unauthorized` response:
{"errors": [ {"message": "Unauthorized."} ]}
As per the docs I've got the sparkpost key in config/services.php and though the docs don't mention anything about it (why not!?) a bit of Googling convinced me to set the mail driver etc. in my .env file. I then have a web route to check the config being used,
Route::get('test', function()
{
dd(Config::get('mail'));
});
which gives
array:9 [▼
"driver" => "sparkpost"
"host" => "smtp.sparkpostmail.com"
"port" => "587"
"from" => array:2 [▶]
"encryption" => "tls"
"username" => "my-sparkpost-account-login-email-address"
"password" => "my-sparkpost-account-login-password"
"sendmail" => "/usr/sbin/sendmail -bs"
"markdown" => array:2 [▶]
]
I actually want to use a mailable and views which I've set up, but just to test the sending I bypassed these and set the following route to test:
Route::get('/sparkpost', function () {
Mail::send('emails.test', [], function ($message) {
$message
->from('marketing#my-sparkpost-sending-domain.com', 'Me')
->to('my-email-address', 'My-Name')
->subject('A Test Email');
});
});
which got the error at the top (testing with my mailables and views gave the exact same error which makes me think they are correctly set up - assuming the above test route is correct).
The on thing I'm wondering about is I'm testing on my local machine, so test URL is http://localhost/seg/public/sparkpost - I'm wondering if this is tripping SparkPost up (i.e. do I have to actually be sending from a server running at the same domain as the sending domain configured in sparkpost, or is it just the sending address in the email that has to match?)
Thanks for any suggestions!
if you use smtp driver,
You need go to Account > SMTP Relay to get credentials for SMTP,
it's not your sparkpost account credentials.
if you use sparkpost driver,
you need put api key of sparkpost into config/services.php, there is no need to input smtp username and password if you use sparkpost driver

yandex smtp doesnt work on codeigniter(digitalocean+ubuntu+serverpilot)

I send email on localhost but doesnt work same settings on server(digitalocean+serverpilot).
php's open ssl support is enabled.
php get "Message: fsockopen(): unable to connect to
ssl://smtp.yandex.com.tr:465 (Connection timed out)
codeigniter framework get :
The following SMTP error was encountered: 110 Connection timed out
Unable to send email using PHP SMTP. Your server might not be
configured to send mail using this method.
my code is:
$config = Array('protocol' => 'smtp','smtp_host' => 'ssl://smtp.yandex.com.tr','smtp_port' => 465, 'smtp_user' => 'info#mydomain.com','smtp_pass' => 'mypass','mailtype' => 'html', 'charset' => 'utf-8');
$this->load->library('email');
$this->email->initialize($config);
$this->email->set_newline("\r\n");
$this->email->from('info#mydomain.com', 'test.com');
$this->email->to('testing#yandex.com');
$this->email->subject('test');
$this->email->message('test body');
$this->email->send();
echo $this->email->print_debugger();
nslookup smtp.yandex.com:
Server: 2001:4860:4860::8844 Address: 2001:4860:4860::8844#53
Non-authoritative answer: smtp.yandex.com canonical name =
smtp.yandex.ru. Name: smtp.yandex.ru Address: 93.158.134.38
Name: smtp.yandex.ru Address: 87.250.250.38 Name: smtp.yandex.ru
Address: 213.180.204.38 Name: smtp.yandex.ru Address: 213.180.193.38
Name: smtp.yandex.ru Address: 77.88.21.38
and telnet request is work.
Your outgoing connection may be blocked by a firewall.
Use tool like tcptraceroute to locate the problem.

Email sending with CI using hotmail

I am trying to create an email notification system with CI. The problem is the system on which I am working on has blocked gmail. So, i am unable to use the gmail SMTP. Now, I have to figure out a way to send emails with hotmail or any other SMTP services.
Here is my code which worked for gmail but now for hotmail
config/Email.php:
$config = array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.live.com',
'smtp_port' => 587,
'smtp_user' => 'muttalebr#hotmail.com',
'smtp_pass' => 'XXXXXX',
'charset' => 'utf-8',
'newline' => "\r\n",
'crlf' => "\r\n",
'mailtype' => "html",
);
the actual function that calls the email.php and send the email:
function sends($from,$to,$send,$user){
$link=base_url()."index.php/anonymouscoll/cmembersarea/".$user;
$emailmessage="Hello $to,<br />You have a new Gift from $from.<br />Click on the link:<a href=$link>$link</a> to check your gift.<br /><br /><br />Best Regards<br />Online Communication.";
$this->load->library('email');
$this->email->from('muttalebr#hotmail.com','Gift File');
$this->email->to($send);
$this->email->subject('You have a new Gift');
$this->email->message($emailmessage);
if($this->email->send()){
echo "Email sent";
}
else{
show_error($this->email->print_debugger());
}
Each time i call the ‘sends’ function i get the below error:
Severity: Warning
Message: fsockopen() [function.fsockopen]: SSL operation failed with code 1. OpenSSL Error messages: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Filename: libraries/Email.php
Line Number: 1673
and
Severity: Warning
Message: fsockopen() [function.fsockopen]: Failed to enable crypto
Filename: libraries/Email.php
Line Number: 1673
I have also tried with
‘smtp_host’ => ‘sslv2://smtp.live.com’,
but it just wont work on my local machine.
I am using windows 7 on my local machine and windows Xp for the system I will use the application[the one which blocked gmail]. I tried with both XAMPP ver 1.8.1 and WAMPP ver 2.2
Looking forward for your responses
~muttalebm
The error because you didn't enable SSL in your php.info file. SO search how to enable to it . Otherwise you can look into my answer to the question in the below link which is same liek this. I faced this error when i am doing and i resolved it.
Reference Link
Which version of PHP are you using?
There is apparently a bug in fsockopen ssl in some versions:
https://bugs.php.net/bug.php?id=54511

Resources