12

I've been trying for a whlie on this, and have so far been failing miserably. My most recent attempt was lifted from this stack code here: Sending email through Gmail SMTP server with C#, but I've tried all the syntax I could find here on stack and elsewhere. My code currently is:

var client = new SmtpClient("smtp.gmail.com", 587)
{
    Credentials = new NetworkCredential("me@gmail.com", "mypass"),
    EnableSsl = true
};

client.Send("me@gmail.com","me@gmail.com","Test", "test message");

Running that code gives me an immediate exception "Failure sending mail" that has an innerexeption "unable to connect to the remote server".

If I change the port to 465 (as gmail docs suggest), I get a timeout every time.

I've read that 465 isn't a good port to use, so I'm wondering what the deal is w/ 587 giving me failure to connect. My user and pass are right. I've read that I have to have POP service setup on my gmail account, so I did that. No avail.

I was originally trying to get this working for my branded GMail account, but after running into the same problems w/ that I thought going w/ my regular gmail account would be easier... so far that's not the case.

Kiquenet
  • 13,271
  • 31
  • 133
  • 232
Paul
  • 32,974
  • 9
  • 79
  • 112
  • Can you connect through a standard email client? If not, it might be a problem with you firewall. Did you enable POP access in your account? – MiffTheFox Jul 04 '09 at 13:42

7 Answers7

16

I ran in to this problem a while ago as well. The problem is that SmtpClient does not support implicit SSL connections, but does support explicit connections (System.Net.Mail with SSL to authenticate against port 465). The previous class of MailMessage (I believe .Net 1.0) did support this but has long been obsolete.

My answer was to call the CDO (Collaborative Data Objects) (http://support.microsoft.com/kb/310212) directly through COM using something like the following:

    /// <summary>
    /// Send an electronic message using the Collaboration Data Objects (CDO).
    /// </summary>
    /// <remarks>http://support.microsoft.com/kb/310212</remarks>
    private void SendTestCDOMessage()
    {
        try
        {
            string yourEmail = "YourUserName@gmail.com";

            CDO.Message message = new CDO.Message();
            CDO.IConfiguration configuration = message.Configuration;
            ADODB.Fields fields = configuration.Fields;

            Console.WriteLine(String.Format("Configuring CDO settings..."));

            // Set configuration.
            // sendusing:               cdoSendUsingPort, value 2, for sending the message using the network.
            // smtpauthenticate:     Specifies the mechanism used when authenticating to an SMTP service over the network.
            //                                  Possible values are:
            //                                  - cdoAnonymous, value 0. Do not authenticate.
            //                                  - cdoBasic, value 1. Use basic clear-text authentication. (Hint: This requires the use of "sendusername" and "sendpassword" fields)
            //                                  - cdoNTLM, value 2. The current process security context is used to authenticate with the service.

            ADODB.Field field = fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"];
            field.Value = "smtp.gmail.com";

            field = fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"];
            field.Value = 465;

            field = fields["http://schemas.microsoft.com/cdo/configuration/sendusing"];
            field.Value = CDO.CdoSendUsing.cdoSendUsingPort;

            field = fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"];
            field.Value = CDO.CdoProtocolsAuthentication.cdoBasic;

            field = fields["http://schemas.microsoft.com/cdo/configuration/sendusername"];
            field.Value = yourEmail;

            field = fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"];
            field.Value = "YourPassword";

            field = fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"];
            field.Value = "true";

            fields.Update();

            Console.WriteLine(String.Format("Building CDO Message..."));

            message.From = yourEmail;
            message.To = yourEmail;
            message.Subject = "Test message.";
            message.TextBody = "This is a test message. Please disregard.";

            Console.WriteLine(String.Format("Attempting to connect to remote server..."));

            // Send message.
            message.Send();

            Console.WriteLine("Message sent.");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

Do not forget to browse through your COM references and add the "Microsoft CDO for Windows 200 Library" which should add two references: ADODB, and CDO.

Bryan Allred
  • 621
  • 4
  • 5
15

I tried your code, and it works prefectly with port 587, but not with 465.

Have you checked the fire wall? Try from the command line "Telnet smtp.gmail.com 587" If you get "220 mx.google.com ESMTP...." back, then the port is open. If not, it is something that blocks you call.

Daniel

tvanfosson
  • 490,224
  • 93
  • 683
  • 780
  • thanks, that was exactly it. I had put the rule in my firewall to let port 587 through, and my email client had no problem using it, but my a/v was suspicious of my console test app, thinking it was a worm trying to propogate. – Paul Jul 06 '09 at 02:55
  • hello, i tried this test in telnet , it worked (i got 220 mx.google.com ESMTP), but when i try sending mail using .net 2.0 app, i get `Server does not support secure connections.` do you know what is causing the problem – Smith Jan 28 '12 at 20:31
  • @Paul Can someone please have a look here? https://stackoverflow.com/questions/52386437/how-to-solve-error-connecting-to-smtp-host-errno-10061-no-connection-could-b – Deva Sep 21 '18 at 05:47
9

I implemented an email client sometime back that could talk to gmail on both 587 and 465...

Port 25 is the normal unencrypted pop port; not available on gmail.

The other two ports have encryption; 587 uses TLS, 465 uses SSL.

To use 587 you should set SmtpClient.EnableSsl = true.

465 wont work with SmtpClient, it will work with the deprecated class SmtpMail instead.

2

Try this link http://www.google.com/accounts/DisplayUnlockCaptcha on server.

Business Gmail accounts, (or normal gmail accounts don't sure about this one) demands a DisplayUnlockCaptcha for the very first time.

Fevzi Apaydın
  • 1,030
  • 7
  • 7
1

Your private network's firewall blocked the ports 587 and 465. You can use default port 25 or enable there ports on firewall

1

There are two ways to do SMTP over SSL: Explicit and Implicit. Explicit means you connect to a normal SMTP port (usually 25 or 587) in plaintext, then issue the “starttls” command to switch to SSL-mode. Implicit means you connect to a port that expects everything to be SSL (usually 465).

Asp.net use “System.Net.Mail.SmtpClient()” to send Email. The main problem is SmtpClient does not support implicit SSL connections, but does support explicit connections (System.Net.Mail with SSL to authenticate against port 465). So, if the mail server(SMTP) do not support Explicit connection, it fails to send email and show messages like “Connection timeout“, “The message could not be sent to the SMTP server. The transport error code was 0x80040217. The server response was not available” etc.

To solve this issue in ASP.net we can use the Collaboration Data Objects (CDO) for Windows 2000 library (Cdosys.dll) to send an e-mail message with attachments. Microsoft Outlook use this DLL to send email. In your ASP.net solution, you have to add referance “Microsoft CDO for windows 2000 Library“. It will add two marked dll in Bin folder.

image to add referance

Now do the bellow code in C#.net:

public static void SendMail(string FromName, string FromEmail, string ReceiverEmail, string CC, string BCC, string subj, string Mssg)
{
 const var cdoSendUsingPort = 2;
 const var cdoBasicAuth = 1;
 const var cdoTimeout = 60;
 var mailServer = "mail.XXXXXXX.net";
 var SMTPport = 465;
 var mailusername = "yyy@XXXXXXX.net";
 var mailpassword = "PPPPXXXX";
 var objEmail = CreateObject("CDO.Message");
 var objConf = objEmail.Configuration;
 var objFlds = objConf.Fields;
 objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort;
 objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = mailServer;
 objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTPport;
 objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true;
 objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = cdoTimeout;
 objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasicAuth;
 objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = mailusername;
 objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = mailpassword;
 objFlds.Update();
 objEmail.To = ReceiverEmail;
 objEmail.From = FromEmail;
 objEmail.CC = CC;
 objEmail.BCC = BCC;
 objEmail.Subject = subj;
 objEmail.HTMLBody = Mssg;
 objEmail.Send();
}

In VB.net

Public Shared Sub SendMail(ByVal FromName As String, ByVal FromEmail As String, ByVal ReceiverEmail As String, ByVal CC As String, ByVal BCC As String, ByVal subj As String, ByVal Mssg As String)

''#################Sending Email##########################

Const cdoSendUsingPort = 2 ' Send the message using SMTP
 Const cdoBasicAuth = 1 ' Clear-text authentication
 Const cdoTimeout = 60 ' Timeout for SMTP in seconds

Dim mailServer = "mail.XXXXXXX.net"
 Dim SMTPport = 465
 Dim mailusername = "yyy@XXXXXXX.net"
 Dim mailpassword = "PPPPXXXX"




Dim objEmail = CreateObject("CDO.Message")
 Dim objConf = objEmail.Configuration
 Dim objFlds = objConf.Fields

With objFlds
 .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort
 .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = mailServer
 .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTPport
 .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
 .Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = cdoTimeout
 .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasicAuth
 .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = mailusername
 .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = mailpassword
 .Update()
 End With

objEmail.To = ReceiverEmail
 objEmail.From = FromEmail
 objEmail.CC = CC
 objEmail.BCC = BCC
 objEmail.Subject = subj
 objEmail.HTMLBody = Mssg
 'objEmail.AddAttachment "C:\report.pdf"
 objEmail.Send()
 End Sub

Referance: Original post Implicit & Explicit SMTP http://help.fogcreek.com/9002/using-an-smtp-server-with-ssl use the Cdosys.dll library to send an e-mail message with attachments https://support.microsoft.com/en-us/help/310212/how-to-use-the-cdosys-dll-library-to-send-an-e-mail-message-with-attac

1

I had the same problem, but was not at liberty to alter my company's firewall restrictions. Based on the one of the notes on this Google doc, along with erdenetsogt's answer above, I tried using port 25 and it worked. (At first I was concerned that using port 25 might imply that message might not be encrypted; so I set EnableSSL to false, which caused gmail to reject it because the StartTLS was never called. This leads me to believe that gmail is enforcing the Explicit SSL, even over port 25).

kmote
  • 14,865
  • 10
  • 62
  • 84