使用SmtpClient从Gmail发送电子邮件

时间:2015-07-05 13:49:08

标签: c# smtpclient

我正在尝试通过AsyncTask连接到我的Gmail帐户,但似乎无法正常工作。我指定端口465,启用SSL并定义所有内容,但它需要2分钟,然后只显示一些错误消息未发送。

我在这里做错了什么?

SmtpClient

1 个答案:

答案 0 :(得分:18)

您需要允许“不太安全的应用”:

https://support.google.com/accounts/answer/6010255

代码:

try
{
    new SmtpClient
    {
        Host = "Smtp.Gmail.com",
        Port = 587,
        EnableSsl = true,
        Timeout = 10000,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential("MyMail@Gmail.com", "MyPassword")
    }.Send(new MailMessage {From = new MailAddress("MyMail@Gmail.com", "MyName"), To = {"TheirMail@Mail.com"}, Subject = "Subject", Body = "Message", BodyEncoding = Encoding.UTF8});
    erroremail.Text = "Email has been sent successfully.";
}
catch (Exception ex)
{
    erroremail.Text = "ERROR: " + ex.Message;
}