SmtpClient发送邮件

时间:2012-05-02 20:51:18

标签: c# email smtp smtpclient

我正在尝试使用以下代码通过gmail发送邮件,但我不断收到错误消息“无法连接到远程主机”。我已经仔细检查了我的配置,一切看起来都很好。有人看到我遗失的东西吗?

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

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

将您的代码与sending-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)
};