44

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 tried port 465 with no luck.

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

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

Heres the error

"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at "

Heres the stack trace

   at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
   at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
   at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at email_example.Program.Main(String[] args) in C:\Users\Vince\Documents\Visual Studio 2008\Projects\email example\email example\Program.cs:line 23
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
Razor
  • 16,811
  • 22
  • 87
  • 137

7 Answers7

61

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?

Razor
  • 16,811
  • 22
  • 87
  • 137
  • 2
    I would say no, because when I changed to UseDefaultCredentials = true, I would want any existing credentials be be overwritten. – kenny Aug 21 '09 at 13:59
  • 1
    Yes but we're encountering the other way here. Overwritten Credentials if you set DefaultCredentials to false. That doesn't sound right. – Bdiem Aug 21 '09 at 14:30
  • 11
    Kenny, it seems a bit counter intuitive that you need to declare properties in the right order. – Razor Aug 22 '09 at 04:15
  • You can still get that error when exceeding sending limits, or if the machine in question has never had a real user logged on before through a browser. It is confusing Google returns that error, but they do. – Jason Short Aug 26 '09 at 06:33
  • 4
    encountered same bug, UseDefaultCredentials must be set first before using Credentials property. a bit counter-intuitive, properties should not depend on order – Michael Buen Mar 29 '10 at 14:19
  • @VincePanuccio I still cant send email even after doing all that you posted above, i get this `Server does not support secure connections.` and when i disable the secure connection, i get this `The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. n58sm2181990een.10`. could you help me with some tips – Smith Feb 07 '12 at 16:40
  • What version of .NET are you using? I understand some changes were made to the Smtp class in .NET 4. Try executing the code above under .NET 2 CLI and see how you go. – Razor Feb 08 '12 at 06:30
  • 2
    @VincePanuccio I examined what's going on using reflector. Setting ss.UseDefaultCredentials = false essentially is resetting Credentials to null. This is why you had troubles. But that also means ss.UseDefaultCredentials = false is not even necessary at all, it doesn't do anything in the end – galets Mar 21 '12 at 20:03
  • It was not working for me on 465 port. I just changed to 587and it worked. SmtpClient smtpClient = new SmtpClient("smpt.gmail.com", Convert.ToInt32(587)); – Gaurang Jadia May 07 '12 at 01:36
  • 2
    Why are you using Convert.ToInt32 on an int? – Casey Feb 11 '14 at 20:44
  • 1
    R#@U#*FH#$*Ih WHY WOULD MICROSOFT DO THIS?! I can't believe that actually worked... – Joshua Pech Mar 17 '15 at 02:08
  • 1
    I can't believe how many hours I wasted on this, thanks for the answer! – Omar Mneimneh Apr 01 '20 at 01:52
5

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.

Community
  • 1
  • 1
Bdiem
  • 566
  • 2
  • 8
2

Work for me only with port 25.

karabara
  • 528
  • 6
  • 24
1

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);
1

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>
Shibu Thomas
  • 2,910
  • 1
  • 21
  • 26
0

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

0

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;
}
FuriousFolder
  • 1,000
  • 10
  • 26
Ahosan Karim Asik
  • 2,995
  • 1
  • 16
  • 27