使用 SmtpClient 从 Gmail 发送电子邮件

Using SmtpClient to send an email from Gmail

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

我做错了什么?

try
{
    MailMessage msg = new MailMessage();
    msg.From = new MailAddress("myemail@gmail.com);
    msg.To.Add(new MailAddress("theiremil@email.com));
    msg.Subject = "This is the subject";
    msg.Body = "This is the body";
    SmtpClient sc = new SmtpClient("smtp.gmail.com", 465);
    sc.EnableSsl = true;
    sc.UseDefaultCredentials = false;
    sc.Credentials = new NetworkCredential("myemail@gmail.com", "pass");
    sc.DeliveryMethod = SmtpDeliveryMethod.Network;
    sc.Send(msg);
    erroremail.Text = "Email has been sent successfully.";
}
catch (Exception ex)
{
    erroremail.Text = "ERROR: " + ex.Message;
}

您需要允许 "less secure apps":

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