Problem Sending E-mail in C# App Using GMail

I have been banging my head for couple of days with this issue. I was trying to send e-mail through my C# ASP.NET application, using my GMail account.

Settings in Web.config look something like this:

<system.net>
    <mailSettings>
        <smtp from="TEST" >
            <network host="smtp.gmail.com" port="587" userName="someuser@gmail.com" password="somepassword" defaultCredentials="false" />
        </smtp>
    </mailSettings>
</system.net>

The code is pretty simple:

SmtpSection config = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

MailAddress mailAddressFrom = new MailAddress(config.Network.UserName, config.From);
MailAddress mailAddressTo = new MailAddress(mailTo);

MailMessage message = new MailMessage(mailAddressFrom, mailAddressTo);
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;

SmtpClient mailClient = new SmtpClient(config.Network.Host, config.Network.Port);
mailClient.Credentials = new NetworkCredential(config.Network.UserName, config.Network.Password);
mailClient.UseDefaultCredentials = false;
mailClient.EnableSsl = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.Timeout = 120000;

mailClient.Send(message);

I kept getting 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”.

I’ve browsed many similar examples and they all looked just like mine, couldn’t figure out what was different.

Then, fortunately, I’ve stumbled upon this post: http://stackoverflow.com/a/3797154/1800269! Basically, UseDefaultCredentials property should come before setting actual Credentials:

mailClient.UseDefaultCredentials = false;
mailClient.Credentials = new NetworkCredential(config.Network.UserName, config.Network.Password);

Well, something like this is pretty easy to overlook . Hope this post will save someone’s time.

3 comments

  1. Farhat Ullah

    Great post:
    Kindly always set set defaultcredentials=false before set credentials
    mailClient.UseDefaultCredentials = false;
    ailClient.Credentials = new NetworkCredential(config.Network.UserName, config.Network.Password);

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>