Reputation: 5896
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("[email protected]", "mypass");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "subject thing";
mail.Body = "dubbly doo";
try
{
client.Send(mail);
}
catch(SmtpException e)
{
Console.Write(e.InnerException.Message);
Console.ReadLine();
}
}
}
}
Upvotes: 3
Views: 17312
Reputation: 13030
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>
Upvotes: 8
Reputation: 28665
Comparing your code to the answer for sending-email-in-net-through-gmail. Not positive if this is the issue, but you are missing the following when creating the SmtpClient:
DeliveryMethod = SmtpDeliveryMethod.Network
Example from the linked question:
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
Upvotes: 1
Reputation: 7541
have you setup your email account to allow smtp.gmail.com?
http://support.google.com/mail/bin/answer.py?hl=en&answer=13273
Upvotes: 1