Using SmtpClient to send an email from Gmail

前端 未结 1 1008
南旧
南旧 2020-12-15 10:26

I\'m trying to connect to my Gmail account through SmtpClient but it seems to not work as should. I specify port 465, enable SSL and define everything, but it t

相关标签:
1条回答
  • 2020-12-15 10:59

    You need to allow "less secure apps":

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

    Code:

    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;
    }
    
    0 讨论(0)
提交回复
热议问题