3

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();
            }
        }
    }
}
4

3 回答 3

8

您很可能在访问指定的主机和端口时遇到问题。这可能是一系列事情,其中​​一个被防火墙阻止。首先在命令提示符下使用 telnet 程序连接到主机和端口,即telnet smtp.gmail.com 587. 如果它确实连接,那么您可以通过按 ctrl+] 并quit在收到提示时键入来断开连接。如果 telnet 连接失败,请开始查看与防火墙/网络相关的问题。

您还可以通过将以下内容添加到应用程序的 .config 文件中来获取包含详细调试信息的文件:

<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>
于 2012-05-02T21:38:58.873 回答
1

将您的代码与send-email-in-net-through-gmail的答案进行比较。如果这是问题,则不是肯定的,但是您在创建 SmtpClient 时缺少以下内容:

DeliveryMethod = SmtpDeliveryMethod.Network

链接问题的示例:

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
于 2012-05-02T21:01:17.517 回答
1

您是否设置了您的电子邮件帐户以允许 smtp.gmail.com?

http://support.google.com/mail/bin/answer.py?hl=en&answer=13273

于 2012-05-02T20:55:00.110 回答