c# SmtpClient class not able to send email using gmail

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-26 20:19:54

You won't belive what fixed my problem.

The Credentials property

ss.Credentials = new NetworkCredential("username", "pass");

must be declared after

ss.UseDefaultCredentials = false;

So the final working code listing is

SmtpClient ss = new SmtpClient("smtp.gmail.com", 587);
ss.EnableSsl = true;
ss.Timeout = 10000;
ss.DeliveryMethod = SmtpDeliveryMethod.Network;
ss.UseDefaultCredentials = false;
ss.Credentials = new NetworkCredential("username", "pass");

MailMessage mm = new MailMessage("donotreply@domain.com", "destination@domain.com", "subject here", "my body");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
ss.Send(mm);

Is this a bug?

Bdiem

Stackoverflow said before

In your case it means you have to send it with the email address you logged into Google with.

Stackoverflow also says

So maybe there's a firewall that interferes with the connection. I'm encountering this problem right now while testing your code. Try the suggested TELNET-Test.

Work for me only with port 25.

This works, but it's not very performance friendly. Check out client.SendAsync: http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx

An example use case:

 var message = new MailMessage("from", "to", "subject", "body");
 var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("login", "password"),
                EnableSsl = true
            };
            client.SendCompleted += (s, e) =>
            {
                client.Dispose();
                message.Dispose();
            };
            client.SendAsync(message, null);

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

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Title</title>
</head>
<body>
    <div style="border: thin solid #0066FF; width: 550px; margin: 25px auto; padding: 15px; font-family: 'Microsoft Himalaya'; font-size: x-large; font-style: normal; color: #0066FF; background-color: #EfEFF2;">
        <br />
        <p style="vertical-align: middle">Dear ##NAME##,</p>
    </div>
</body>
</html>

I can verify that setting UseDefaultCredentials to false MUST be done before the NetworkCredentials is created. I had the same problem.

Ahosan Karim Asik

It works fine in my case:

private void btnTestConnection_Click(object sender, EventArgs e)
     {
    btnTestConnection.Enabled = false;
    SmtpClient ss = new SmtpClient(txtSmtpHostName.Text.Trim(), Convert.ToInt32(numSmtpHostPort.Value));
    ss.EnableSsl = chkSmtpSecureType.Checked;
    ss.Timeout = 10000;
    ss.DeliveryMethod = SmtpDeliveryMethod.Network;
    ss.UseDefaultCredentials = false;
    ss.Credentials = new NetworkCredential(txtSmtpAccount.Text.Trim(), txtSmtpPassword.Text);

    MailMessage mm = new MailMessage(txtSmtpFromEmail.Text.Trim(), "test@domain.com", "subject", "my body");
    mm.BodyEncoding = UTF8Encoding.UTF8;
    mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
    ss.SendCompleted += (s, b) =>
    {
        ss.Dispose();
        mm.Dispose();
    };
    try
    {
        ss.Send(mm);
        ss.Dispose();
        mm.Dispose();
        MessageBox.Show("Connection successfully");
    }
    catch (Exception ep)
    {
        MessageBox.Show("Connection error: " + ep.Message, "Smtp Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    btnTestConnection.Enabled = true;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!