Swiftmailer Gmail Connection timed out #110 - smtp

I want to send emails using gmail's smtp with the PHP script posted below using Swiftmailer. Now this works fine on my own webserver. But when I used it on the webserver of the people I'm creating this for, I get an exception:
Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp.gmail.com [Connection timed out #110]' in ...
What could be the problem?
I'm assuming its got to do with the difference in server settings, because the code works on my own webserver. I've checked with phpinfo() the following:
- Registered Stream Socket Transports tcp, udp, unix, udg, ssl, sslv3, sslv2, tls
- OpenSSL support enabled
- OpenSSL Library Version OpenSSL 1.0.1e-fips 11 Feb 2013
This is my PHP code:
$emailname = MY_GMAIL_ACCOUNT_USERNAME;
$emailpass = MY_GMAIL_ACCOUNT_PASSWORD;
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
->setUsername($emailname)
->setPassword($emailpass);
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance($emailtitle)
->setFrom(array($emailname.'#gmail.com' => $emailsender))
->setTo(array($emailrecp))
->setBody($emailbody,'text/html');
$result = $mailer->send($message);

I had the same issue on a Digital Ocean server. Turns out they're blocking SMTP by default on IPv6. Here's the fix:
nano /etc/gai.conf
precedence ::ffff:0:0/96 100
as per:
https://www.digitalocean.com/community/questions/outgoing-connections-on-port-25-587-143-blocked-over-ipv6

My easy solution to avoid the problem of dynamic IP (every time i ping smtp.gmail.com I see a slight difference in the last 3digit chunk), is to simply use php built-in gethostbyname() to read the IP in real-time.
$smtp_host_ip = gethostbyname('smtp.gmail.com');
$transport = Swift_SmtpTransport::newInstance($smtp_host_ip,465,'ssl')
->setUsername('username')->setPassword('pwd');

Im not advanced in php and streams but it seems that IPv6 DNS resolution depends on the router and/or ISPs. I changed my provider, got a new router and the smtp connection always timed out.
To use IPv6 you should either add your own IPv6 or force stream_context_create to use IPv4. You can call setSourceIp() on a swiftmailer object or directly change the Swift_SmtpTransport class (i.e. in the constructor).
Use IPv6:
// replace IP with your own IPv6
$this->setSourceIp('2aaa:8a8:fc0:230:fds:4fd:faa:24ae');
Use IPv4 (mentioned at https://github.com/phergie/phergie/issues/195):
$this->setSourceIp('0.0.0.0');

just add
74.125.130.108 smtp.gmail.com
to server's hosts file

I've just been doing battle with exactly the same problem. Mine worked locally too, but as soon as it got on a real server ... no. It just would not work even though all the settings were the same.
After many hours, I've think I've found out why.
What seems to happen is that on a server with IPv4 and IPv6 support, IPv6 takes precedence. Which makes sense, given that it's newer. But in the case of smtp.gmail.com, it appears to only listen on IPv4. So when the server resolved smtp.gmail.com, it got its IPv6 address back and so PHP tried to connect to it. That eventually gives up with a "Connection timed out" exception. Now you would think that fsockopen, presumably, would detect the connection wasn't working and so try IPv4, but seemingly it doesn't.
If you find out what smtp.gmail.com's IPv4 address is (ping smtp.gmail.com) and simply put that IP in place of the hostname in the code - it works :)
It's not ideal coding in an IP address - given that Google could change it at any minute - but at least you will get some emails sent

The answer for me was that my server was blocking the outbound connection. It could be your firewall or your host.
The way to test this is to try connecting yourself. I used telnet on two different machines to compare and it became obvious that this was my issue. There may be a way to test this with curl directly.

Related

can't connect to MySQL remotely on Windows 10 [duplicate]

Sometimes I get the following error while I was doing HttpWebRequest to a WebService. I copied my code below too.
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream()
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = networkCredential(sla);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = v_Timeout * 1000;
if (url.IndexOf("asmx") > 0 && parStartIndex > 0)
{
AppHelper.Logger.Append("#############" + sla.ServiceName);
using (StreamWriter reqWriter = new StreamWriter(request.GetRequestStream()))
{
while (true)
{
int index01 = parList.Length;
int index02 = parList.IndexOf("=");
if (parList.IndexOf("&") > 0)
index01 = parList.IndexOf("&");
string parName = parList.Substring(0, index02);
string parValue = parList.Substring(index02 + 1, index01 - index02 - 1);
reqWriter.Write("{0}={1}", HttpUtility.UrlEncode(parName), HttpUtility.UrlEncode(parValue));
if (index01 == parList.Length)
break;
reqWriter.Write("&");
parList = parList.Substring(index01 + 1);
}
}
}
else
{
request.ContentLength = 0;
}
response = (HttpWebResponse)request.GetResponse();
If this happens always, it literally means that the machine exists but that it has no services listening on the specified port, or there is a firewall stopping you.
If it happens occasionally - you used the word "sometimes" - and retrying succeeds, it is likely because the server has a full 'backlog'.
When you are waiting to be accepted on a listening socket, you are placed in a backlog. This backlog is finite and quite short - values of 1, 2 or 3 are not unusual - and so the OS might be unable to queue your request for the 'accept' to consume.
The backlog is a parameter on the listen function - all languages and platforms have basically the same API in this regard, even the C# one. This parameter is often configurable if you control the server, and is likely read from some settings file or the registry. Investigate how to configure your server.
If you wrote the server, you might have heavy processing in the accept of your socket, and this can be better moved to a separate worker-thread so your accept is always ready to receive connections. There are various architecture choices you can explore that mitigate queuing up clients and processing them sequentially.
Regardless of whether you can increase the server backlog, you do need retry logic in your client code to cope with this issue - as even with a long backlog the server might be receiving lots of other requests on that port at that time.
There is a rare possibility where a NAT router would give this error should its ports for mappings be exhausted. I think we can discard this possibility as too much of a long shot though, since the router has 64K simultaneous connections to the same destination address/port before exhaustion.
The most probable reason is a Firewall.
This article contains a set of reasons, which may be useful to you.
From the article, possible reasons could be:
FTP server settings
Software/Personal Firewall Settings
Multiple Software/Personal Firewalls
Anti-virus Software
LSP Layer
Router Firmware
Computer Turned Off
Computer Not Plugged In
Fiddler
I had the same. It was because the port-number of the web service was changing unexpectedly.
This problem usually happens when you have more than one copy of the project
My project was calling the Web service with a specific port number which I assigned in the Web.Config file of my main project file. As the port number changed unexpectedly, the browser was unable to find the Web service and throwing that error.
I solved this by following the below steps: (Visual Studio 2010)
Go to Properties of the Web service project --> click on Web tab --> In Servers section --> Check Specific port
and then assign the standard port number by which your main project is calling the web service.
I hope this will solve the problem.
Cheers :)
I think, you need to check your proxy settings in "internet options". If you are using proxy/'hide ip' applications, this problem may be occurs.
I had the same problem. The problem is that I didn't start the selenium server. I have downloaded the selenium server and i started it. After starting the selenium server, issue gone and all worked fine.
Refer this : http://coding-issues.blogspot.in/2012/11/no-connection-could-be-made-because.html
I had the same error with my WCF service using Net TCP binding, but resolved after starting the below services in my case.
Net.Pipe.Listener.Adapter
Net.TCP.Listener.Adapter
Net.Tcp Port Sharing Service
In my case, some domains worked, while some did not. Adding a reference to my organization's proxy Url in my web.config fixed the issue.
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy proxyaddress="http://proxy.my-org.com/" usesystemdefault="True"/>
</defaultProxy>
</system.net>
When you call service which has only HTTP (ex: http://example.com) and you call HTTPS (ex: https://example.com), you get exactly this error - "No connection could be made because the target machine actively refused it"
I faced same error because when your Server and Client run on same machine the Client need server local ip address not Public ip address to communicate with server you need Public ip address only in case when Server and Client run on separate machine so use Local ip address in client program to connect with server Local ip address can be found using this method.
public static string Getlocalip()
{
try
{
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
return localIPs[7].ToString();
}
catch (Exception)
{
return "null";
}
}
I got this error in an application that uses AppFabric. The clue was getting a DataCacheException in the stack trace. To see if this is the issue for you, run the following PowerShell command:
#("AppFabricCachingService","RemoteRegistry") | % { get-service $_ }
If either of these two services are stopped, then you will get this error.
For me, I wanted to start the mongo in shell (irrelevant of the exact context of the question, but having the same error message before even starting the mongo in shell)
The process 'MongoDB Service' wasn't running in Services
Start cmd as Administrator and type,
net start MongoDB
Just to see MongoDB is up and running just type mongo, in cmd it will give Mongo version details and Mongo Connection URL
Well, I've received this error today on Windows 8 64-bit out of the blue, for the first time, and it turns out my my.ini had been reset, and the bin/mysqld file had been deleted, among other items in the "Program Files/MySQL/MySQL Server 5.6" folder.
To fix it, I had to run the MySQL installer again, installing only the server, and copy a recent version of the my.ini file from "ProgramData/MySQL/MySQL Server 5.6", named my_2014-03-28T15-51-20.ini in my case (don't know how or why that got copied there so recently) back into "Program Files/MySQL/MySQL Server 5.6".
The only change to the system since MySQL worked was the installation of Native Instruments' Traktor 2 and a Traktor Audio 2 sound card, which really shouldn't have caused this problem, and no one else has used the system besides me. If anyone has a clue, it would be kind of you to comment to prevent this for me and anyone else who has encountered this.
For service reference within a solution.
Restart your workstation
Rebuild your solution
Update service reference in WCFclient project
At this point, I received messsage (Windows 7) to allow system access.
Then the service reference was updated properly without errors.
I would like to share this answer I found because the cause of the problem was not the firewall or the process not listening correctly, it was the code sample provided from Microsoft that I used.
https://msdn.microsoft.com/en-us/library/system.net.sockets.socket%28v=vs.110%29.aspx
I implemented this function almost exactly as written, but what happened is I got this error:
2016-01-05 12:00:48,075 [10] ERROR - The error is: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it [fe80::caa:745:a1da:e6f1%11]:4080
This code would say the socket is connected, but not under the correct IP address actually needed for proper communication. (Provided by Microsoft)
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if(tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
I re-wrote the code to just use the first valid IP it finds. I am only concerned with IPV4 using this, but it works with localhost, 127.0.0.1, and the actually IP address of you network card, where the example provided by Microsoft failed!
private Socket ConnectSocket(string server, int port)
{
Socket s = null;
try
{
// Get host related information.
IPAddress[] ips;
ips = Dns.GetHostAddresses(server);
Socket tempSocket = null;
IPEndPoint ipe = null;
ipe = new IPEndPoint((IPAddress)ips.GetValue(0), port);
tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Platform.Log(LogLevel.Info, "Attempting socket connection to " + ips.GetValue(0).ToString() + " on port " + port.ToString());
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
s.SendTimeout = Coordinate.HL7SendTimeout;
s.ReceiveTimeout = Coordinate.HL7ReceiveTimeout;
}
else
{
return null;
}
return s;
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, "Error creating socket connection to " + server + " on port " + port.ToString());
Platform.Log(LogLevel.Error, "The error is: " + e.ToString());
if (g_NoOutputForThreading == false)
rtbResponse.AppendText("Error creating socket connection to " + server + " on port " + port.ToString());
return null;
}
}
This is really specific, but if you receive this error after trying to connect to a database using mongo, what worked for me was running mongod.exe before running mongo.exe and then the connection worked fine. Hope this helps someone.
One more possibility --
Make sure you're trying to open the same IP address as where you're listening. My server app was listening to the host machine's IP address using IPv6, but the client was attempting to connect on the host machine's IPv4 address.
I've received this error from referencing services located on a WCFHost from my web tier. What worked for me may not apply to everyone, but I'm leaving this answer for those whom it may. The port number for my WCFHost was randomly updated by IIS, I simply had to update the end routes to the svc references in my web config. Problem solved.
In my scenario, I have two applications:
App1
App2
Assumption: App1 should listen to App2's activities on Port 5000
Error: Starting App1 and trying to listen, to a nonexistent ghost town, produces the error
Solution: Start App2 first, then try to listen using App1
Go to your WCF project -
properties ->
->
debuggers
-> unmark the checkbox
Enable Edit and Continue
In my case this was caused by a faulty deployment where a setting in my web.config was not made.
A collegue explained that the IP address in the error message represents the localhost.
When I corrected the web.config I was then using the correct url to make the server calls and it worked.
I thought I would post this in case it might help someone.
Using WampServer 64bit on Windows 7 Home Premium 64bit I encountered this exact problem. After hours and hours of experimentation it became apparent that all that was needed was in my.ini to comment out one line. Then it worked fine.
commented out 1 line
socket=mysql
If you put your old /data/ files in the appropriate location, WampServer will accept all of them except for the /mysql/ folder which it over writes. So then I simply imported a backup of the /mysql/ user data from my prior development environment and ran FLUSH PRIVILEGES in a phpMyAdmin SQL window. Works great. Something must be wrong because things shouldn't be this easy.
I had this issue happening often. I found SQL Server Agent service was not running. Once I started the service manually, it got fixed. Double check if the service is running or not:
Run prompt, type services.msc and hit enter
Find the service name - SQL Server Agent(Instance Name)
If SQL Server Agent is not running, double-click the service to open properties window. Then click on Start button. Hope it will help someone.
I came across this error and took some time to resolve it. In my case I had https and net.tcp configured as IIS bindings on same port. Obviously you can't have two things on the same port. I used netstat -ap tcp command to check whether there is something listening on that port. There was none listening. Removing unnecessary binding (https in my case) solved my issue.
It was a silly issue on my side, I had added a defaultproxy to my web.config in order to intercept traffic in Fiddler, and then forgot to remove it!
There is a service called "SQL Server Browser" that provides SQL Server connection information to clients.
In my case, none of the existing solutions worked because this service was not running. I resumed it and everything went back to working perfectly.
I was facing this issue today. Mine was Asp.Net Core API and it uses Postgresql as the database. We have configured this database as a Docker container. So the first step I did was to check whether I am able to access the database or not. To do that I searched for PgAdmin in the start as I have configured the same. Clicking on the resulted application will redirect you to the http://127.0.0.1:23722/browser/. There you can try access your database on the left menu. For me I was getting an error as in the below image.
Enter the password and try whether you are able to access it or not. For me it was not working. As it is a Docker container, I decided to restart my Docker desktop, to do that right click on the docker icon in the task bar and click restart.
Once after restarting the Docker, I was able to login and see the Database and also the error was gone when I restart the application in Visual Studio.
Hope it helps.
it might be because of authorisation issues; that was the case for me.
If you have for example: [Authorize("WriteAccess")] or [Authorize("ReadAccess")] at the top of your controller functions, try to comment them out.
I just faced this right now...
Here on my end, I have 2 separated Visual Studio solutions (.sln)... opened each one in their own Visual Studio instance.
Solution 2 calls Solution 1 code. The problem was related to the port assigned to Solution 1. I had to change the port on solution 1 to another one and then Solution 2 started working again. So make sure you check the port assigned to your project.
Normally, connection scripts do not mention the port to use. For example:
$mysqli = mysqli_connect('127.0.0.0.1', 'user', 'password', 'database');
So, to connect with a manager that doesn't use port 3306, you have to specify the port number on the connection request:
$mysqli = mysqli_connect('127.0.0.0.1', 'user', 'password', 'database', '3307');
To check the connections on the MySQL or MariaDB database manager, use the script:
wamp(64)\www\testmysql.php
by putting 'http://localhost/testmysql.php' in the browser address bar having first modified the script according to your parameters.
I forgot to start the service so it failed because no service was listening on port.
Resolved by starting the service.

Open connection to remote MySQL using non default (unix) socket

I'm in a situation where I have to push data to a remote database, from a Powershell script.
The database's server uses multiple instances, each one using a specific socket.
I'm trying to open a connection remotely, using the .Net MySQL connector as follow :
$mdir = Split-Path $script:MyInvocation.MyCommand.Path
[void][system.reflection.Assembly]::LoadFrom("$mdir\MySQL.Data.dll")
$connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$connection.ConnectionString = "host=$myHost;port=$Port;uid=$User;pwd=$Pass;database=$Database;Socket=$Socket;Pooling=False"
$connection.Open()
I'm getting an error saying that Socket is not an existing keyword.
I've found reference to that keyword on google, but indeed not in the official documentation.
Example showing what I want to connect to :
Server : db.domain.com
Port : 2345
Socket : /var/sockets/mycustomsocket.sock
Is there a way to do what I want, and if so, what am I doing wrong ?
EDIT
What I was doing wrong is putting too much trust into the technical knowledge of my client, but at least, I learned something !
The case I described is pure nonsense due to the way MySQL works.
When an instance uses a socket, that socket is bound to a specific port. The case that my client described to me that lead to that question is therefore impossible.
It is not possible to have several instances of MySQL listening on the same port, but using different sockets. Wanting to connect to a remote file socket is therefore a non issue, and you should be able to connect using ip/hostname and port.
The Socket parameter in MySQL is supposed to be used locally, as it was noted in the comments.

Couchbase Server unable to start

I am unable to start my couchbase server. I am getting this error while I run the server.
supervisor: {local,inet_gethost_native_sup}
started: [{pid,<0.266.0>},{mfa,{inet_gethost_native,init,[[]]}}]
[error_logger:info,2015-01-06T18:14:37.164,nonode#nohost:error_logger<0.6.0>:ale_error_logger_handler:do_log:203]
=========================PROGRESS REPORT=========================
supervisor: {local,kernel_safe_sup}
started: [{pid,<0.265.0>},
{name,inet_gethost_native_sup},
{mfargs,{inet_gethost_native,start_link,[]}},
{restart_type,temporary},
{shutdown,1000},
{child_type,worker}]
[ns_server:warn,2015-01-06T18:14:37.189,nonode#nohost:dist_manager<0.264.0>:dist_manager:wait_for_address:118]Cannot listen on address `10.219.59.100`: eaddrnotavail
[ns_server:info,2015-01-06T18:14:37.189,nonode#nohost:dist_manager<0.264.0>:dist_manager:wait_for_address:122]Configured address `10.219.59.100` seems to be invalid. Giving OS a chance to bring it up.
[ns_server:warn,2015-01-06T18:14:38.190,nonode#nohost:dist_manager<0.264.0>:dist_manager:wait_for_address:118]Cannot listen on address `10.219.59.100`: eaddrnotavail
[ns_server:info,2015-01-06T18:14:38.190,nonode#nohost:dist_manager<0.264.0>:dist_manager:wait_for_address:122]Configured address `10.219.59.100` seems to be invalid. Giving OS a chance to bring it up.
Is it Ip address Problem ? My Ip address Is 10.219.59.102 but it looking for 10.219.59.100.
It sounds like the IP address the node was originally configured for has changed. If you don't specify a hostname as the node's name when you first configured the node, Couchbase will attempt to auto-detect the node's public IP address and use that. However if that IP address changes then it runs into problems.
Take a look at the Install guide, specifically the section on Using hostnames for how to change a node's name.

Packet is received on TCP level but not able to read

we are using SMPP protocol for sending messages to SMSC.
When SMSC restarted session, client binded it again successfully
But client unable to get/read further pdu like submit_resp, enquire_resp which SMSC has sent.
We have checked tcp dump using wireshark,
it has been found that client receive tcp packet in tcp dump, app not able to read anything,
In app, we have used Logica smpp lib.
we have checked by putting more logs in logica lib, then it is found that Logica lib doesn't get any thing to read from socket.
Please have comment, which can give more detail direction !!
You mentioned that when SMSC restarts,
The client bound again.
The client is not able to read subsequent PDU(s).
Since the question does not give any specific information, I will have to guess what the problem is. I would suggest to check the code for stale com.logica.smpp.Session object(s).

How can I map a local unix socket to an inet socket?

I'm curious if it is possible to map a UNIX socket on to an INET socket. The situation is simply that I'd like to connect to a MySQL server. Unfortunately it has INET sockets disabled and therefore I can only connect with UNIX sockets. The tools I'm using/writing have to connect on an INET socket, so I'm trying to see if I can map one on to the other.
It took a fair amount of searching but I did find socat, which purportedly does what I'm looking for. I was wondering if anyone has any suggestions on how to accomplish this. The command-line I've been using (with partial success) is:
socat -v UNIX-CONNECT:/var/lib/mysql/mysql.sock TCP-LISTEN:6666,reuseaddr
Now I can make connections and talk to the server. Unfortunately any attempts at making multiple connections fail as I need to use the fork option but this option seems to render the connections nonfunctional.
I know I can tackle the issue with Perl (my preferred language), but I'd rather avoid writing the entire implementation myself. I familiar with the IO::Socket libraries, I am simply hoping anyone has experience doing this sort of thing. Open to suggestions/ideas.
Thanks.
Reverse the order of your arguments to socat, and it works.
socat -v tcp-l:6666,reuseaddr,fork unix:/var/lib/mysql/mysql.sock
This instructs socat to
Listen on TCP port 6666 (with SO_REUSEADDR)
Wait to accept a connection
When a connection is made, fork. In the child, continue the steps below. In the parent, go to 2.
Open a UNIX domain connection to the /var/lib/mysql/mysql.sock socket.
Transfer data between the two endpoints, then exit.
Writing it the other way around
socat -v unix:/var/lib/mysql/mysql.sock tcp-l:6666,reuseaddr,fork
doesn't work, because this instructs socat to
Open a UNIX domain connection to the /var/lib/mysql/mysql.sock socket.
Listen on TCP port 6666 (with SO_REUSEADDR)
Wait to accept a connection
When a connection is made, spawn a worker child to transfer data between the two addresses.
The parent continues to accept connections on the second address, but no longer has the first address available: it was given to the first child. So nothing useful can be done from this point on.
Yes, you can do this in Perl.
Look at perlipc, IO::Select, IO::Socket and Beej's Guide to Network Programming.
You might want to consider doing it in POE - it's asynchronous library for dealing with events, so it looks like great for the task.
It is not 100% relevant, but I use POE to write proxy between stateless protocol (HTTP) and statefull protocol (telnet session, and more specifically - MUD session), and it was rather simple - You can check the code in here: http://www.depesz.com/index.php/2009/04/08/learning-poe-http-2-mud-proxy/.
In the comments somebody also suggested Coro/AnyEvent - I haven't played with it yet, but you might want to check it.