有时使用c#从hotmail发送邮件失败

时间:2013-02-26 13:17:28

标签: c# email

我有c#代码发送邮件。该代码适用于gmail,yahoo配置。但对于hotmail,有时会发送邮件,有时邮件不会被发送。我观察到雅虎邮件的响应时间比gmail好。但与yahoo,gmail相比,hotmail的响应非常差。

原因是什么?如何配置hotmail以获得良好的响应。

这是我发送邮件的代码:

 private void button2_Click(object sender, EventArgs e)
 {

            SmtpClient client = new SmtpClient();
            MailMessage message = new MailMessage();

        message.To.Add("user_name");
                message.From = new MailAddress("user_name");
                message.Subject = "Email Confirmation";
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.SubjectEncoding = System.Text.Encoding.UTF8;

    client.Port=587
    client.Host="smtp.live.com";

    System.Net.NetworkCredential nc = new System.Net.NetworkCredential("user_name", "password");
                if (mail_server == "smtp.gmail.com" || mail_server == "smtp.live.com")
                {
                    client.EnableSsl = true;
                }
                client.UseDefaultCredentials = false;
                client.Credentials = nc;

                Ping p = new Ping();
                bool result = false;
                int i = 10;
                do
                {

                    PingReply reply = p.Send("smtp.live.com", 587);
                    if (reply.Status == IPStatus.Success)
                    {
                        result = true;
                    } Thread.Sleep(500);
                    i--;
                } while (result == false && i != 0);

                if (result == true)
                {
                    client.Send(message);
                    MessageBox.Show("Email sent successfully");                    


                }
                else
                {
                    MessageBox.Show("Email not sent");

                }
 }

1 个答案:

答案 0 :(得分:0)

如果您尝试使用上述代码发送电子邮件,它显然无法发送,我不知道您使用Ping课程发送电子邮件的原因。

固定代码:

    SmtpClient client = new SmtpClient();
    MailMessage message = new MailMessage();

    message.To.Add("user_name");
    message.From = new MailAddress("user_name");
    message.Subject = "Email Confirmation";
    message.BodyEncoding = Encoding.UTF8;
    message.SubjectEncoding = Encoding.UTF8;

    client.Port = 587;
    client.Host = "smtp.live.com";

    NetworkCredential nc = new NetworkCredential("user_name", "password");
    string mail_server = "smtp.live.com";
    if (mail_server == "smtp.gmail.com" || mail_server == "smtp.live.com")
        {
            client.EnableSsl = true;
        }
        client.UseDefaultCredentials = false;
        client.Credentials = nc;

    try
    {
        client.Send(message);
    }
    catch (SmtpException exception)
    {
        Console.WriteLine(exception.Message);
    }