c# SmtpClient class not able to send email using gmail

前端 未结 7 1105
-上瘾入骨i
-上瘾入骨i 2020-11-27 16:24

I\'m having trouble sending email using my gmail account. Im pulling my hair out.

The same settings work fine in Thunderbird.

Here\'s the code. I\'ve also tr

7条回答
  •  无人及你
    2020-11-27 17:06

    This work's perfectly. Create a mail Template in a separate file MailTemplate.html.

    Add genuine NetworkCredentials - login and Password

    private void SendMail()
        {
        string filename = Server.MapPath("~/MailTemplate.html");
        string username = UserName.Text.ToString();
    
        string mailbody = System.IO.File.ReadAllText(filename);
        mailbody = mailbody.Replace("##NAME##", username);
        string to = Email.Text;
        string from = "test@gmail.com";
    
        MailMessage message = new MailMessage(from, to);
        message.Subject = "Auto Response Email";
        message.Body = mailbody;
        message.BodyEncoding = Encoding.UTF8;
        message.IsBodyHtml = true;
        SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
        System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("test@gmail.com", "test123#");
        client.EnableSsl = true;
        client.UseDefaultCredentials = true;
        client.Credentials = basicCredential;
        try
        {
            client.Send(message);
            SuccessMessage.Text = "Email Sending successfully";
    
        }
        catch (Exception ex)
        {
    
            ErrorMessage.Text = ex.Message.ToString();
        }
    }
    

    MailTemplate.html

    
    
    
        
        Title
    
    
        

    Dear ##NAME##,

提交回复
热议问题