SmtpClient send mail

c#, email, smtp, smtpclient

Solution

It's most likely that you have a problem reaching the host and port that you specified. This could be a range of things, one of which is being blocked by a firewall. Start by using the telnet program from a command prompt to connect to the host and port, i.e. `telnet smtp.gmail.com 587`. If it does connect then you can disconnect by pressing ctrl+] and typing `quit` when you get a prompt. If telnet fails to connect start looking into firewall/network related problems.

You can also get a file containing detailed debugging information by adding the following to your application's .config file:

<system.diagnostics>
  <sources>
    <source name="System.Net">
      <listeners>
        <add name="TraceFile"/>
      </listeners>
    </source>
    <source name="System.Net.Sockets" maxdatasize="1024">
      <listeners>
        <add name="TraceFile"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener" initializeData="System.Net.trace.log" traceOutputOptions="DateTime"/>
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose"/>
    <!--<add name="System.Net.Sockets" value="Verbose"/>-->
  </switches>
  <trace autoflush="true" />
</system.diagnostics>

Problem

I'm attempting to send mail through gmail using the below code, but I keep getting an errors stating "Unable to connect to the remote host". I've double-checked my config and everything looks fine to me. Anyone see something I'm missing? ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Mail; using System.Net; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential("mymail@gmail.com", "mypass"); client.Port = 587; client.Host = "smtp.gmail.com"; client.EnableSsl = true; MailMessage mail = new MailMessage(); mail.From = new MailAddress("mymail@gmail.com"); mail.To.Add("tomail@tomail.org"); mail.Subject = "subject thing"; mail.Body = "dubbly doo"; try { client.Send(mail); } catch(SmtpException e) { Console.Write(e.InnerException.Message); Console.ReadLine(); } } } } ```

Original source

Related problems