无法发送邮件

时间:2015-12-28 15:43:28

标签: c# email smtp gmail

我尝试使用此代码发送邮件:

SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("email@gmail.com", "password");

MailMessage mail = new MailMessage("email@gmail.com", "some1@gmail.com", "Subject", "Body");
mail.BodyEncoding = UTF8Encoding.UTF8;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mail);

它不起作用,错误如下所示:http://scr.hu/5gpw/tv6hn 这段代码有什么问题?

1 个答案:

答案 0 :(得分:1)

我会将代码更改为一个方法并测试传递到端口,主机等等,看看它是否适用于你我只是测试它并且它在我的最终工作得很好。

public void Send(string from, string to,string smtpServer, int smtpPort,string username, string password)
{
    try
    {
        using (MailMessage mm = new MailMessage())
        {
            SmtpClient sc = new SmtpClient();
            mm.From = new MailAddress(from, "Test");
            mm.To.Add(new MailAddress(to));
            mm.IsBodyHtml = true;
            mm.Subject = "Test Message";
            mm.Body = "This is a test email message from Krzysztof Senska";
            mm.BodyEncoding = System.Text.Encoding.UTF8;
            mm.SubjectEncoding = System.Text.Encoding.UTF8;
            NetworkCredential su = new NetworkCredential(username, password);
            sc.Host = smtpServer;
            sc.Port = smtpPort;
            sc.Credentials = su;
            sc.Send(mm);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}