[c#] Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

I am using following code to send email. The Code works correctly in my local Machine. But on Production server i am getting the error message

var fromAddress = new MailAddress("[email protected]");
var fromPassword = "xxxxxx";
var toAddress = new MailAddress("[email protected]");

string subject = "subject";
string body = "body";

System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)       
};

using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})

smtp.Send(message);

And on my Gmail A/c I have received the following email after i ran the code from production server

Hi ,

Someone recently used your password to try to sign in to your Google Account [email protected]. This person was using an application such as an email, client or mobile device.

We prevented the sign-in attempt in case this was a hijacker trying to access your account. Please review the details of the sign-in attempt:

Friday, 3 January 2014 13:56:08 o'clock UTC IP Address: xxx.xx.xx.xxx (abcd.net.) Location: Philadelphia PA, Philadelphia, PA, USA

If you do not recognise this sign-in attempt, someone else might be trying to access your account. You should sign in to your account and reset your password immediately.

Reset password

If this was you and you are having trouble accessing your account, complete the troubleshooting steps listed at http://support.google.com/mail?p=client_login

Yours sincerely, The Google Accounts team

This question is related to c# .net smtp gmail

The answer is


You might need to create/generate a specific APP password from gmail. you app or script will then use this new password instead of your regular password. Your regular password will still work fine for you.

That is what did it for me. I still used the same email account but had to generate a new app specific password.

https://support.google.com/accounts/answer/185833?hl=en

Screen shot

Basically you can do it here: https://security.google.com/settings/security/apppasswords


NOVEMBER 2018, have tried everything above with no success.

Below is the solution that worked finally. Unfortunately it's not using SSL, but it works!!!

var fromAddress = new MailAddress([email protected], "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");

const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "aspmx.l.google.com",
    Port = 25,
    EnableSsl = false
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

A comment from Tomasz Madeyski is what fixed my problem... he tells that exists a bug on SetDefaultCredential, him says:

"The issue is that in UseDefaultCredentials setter there is this code: this.transport.Credentials = value ? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials : (ICredentialsByHost) null; which overrides credentials set by Credentials setter. For me it looks like SmtpClient's bug"

if you put smtpClient.UseDefaultCredentials = false after set credentials... this line set to null those credentials...


You need to turn on "Allow less secure apps" from here https://myaccount.google.com/lesssecureapps


just turn on the setting of or gmail. see below given image:

enter image description here


Just follow the step in the google email and enable less secure apps.


I'm a google apps for business subscriber and I spend the last couple hours just dealing with this, even after having all the correct settings (smtp, port, enableSSL, etc). Here's what worked for me and the web sites that were throwing the 5.5.1 error when trying to send an email:

  1. Login to your admin.google.com
  2. Click SECURITY <-- if this isn't visible, then click 'MORE CONTROLS', and add it from the list
  3. Click Basic Settings
  4. Scroll to the bottom of the Basic Settings box, click the link: 'Go to settings for less secure apps'
  5. Select the option #3 : Enforce access to less secure apps for all users (Not Recommended)
  6. Press SAVE at the bottom of the window

After doing this my email forms from the website were working again. Good luck!


I have faced the same problem. It happens when you turn on 2 Step Verification (MFA). Just Turn off 2 Step Verification and your problem should be solved.


What worked for me was to activate the option for less secure apps (I am using VB.NET)

Public Shared Sub enviaDB(ByRef body As String, ByRef file_location As String)
        Dim mail As New MailMessage()
        Dim SmtpServer As New SmtpClient("smtp.gmail.com")
        mail.From = New MailAddress("[email protected]")
        mail.[To].Add("[email protected]")
        mail.Subject = "subject"
        mail.Body = body
        Dim attachment As System.Net.Mail.Attachment
        attachment = New System.Net.Mail.Attachment(file_location)
        mail.Attachments.Add(attachment)
        SmtpServer.Port = 587
        SmtpServer.Credentials = New System.Net.NetworkCredential("user", "password")
        SmtpServer.EnableSsl = True
        SmtpServer.Send(mail)
    End Sub

So log in to your account and then go to google.com/settings/security/lesssecureapps


I tried all of the suggestions found here, from enabling less secure apps, to trying port 587... nothing worked. Finally I just commented out the line UseDefaultCredentials = false. Everything worked if I didn't touch that boolean.


I have a previously-working code that throws this error now. No issue on password. No need to convert message to base64 either. Turns out, i need to do the following:

  1. Turn off 2-factor authentication
  2. Set "Allow less secure apps" to ON
  3. Login to your gmail account from production server
  4. Go here as well to approve the login activity
  5. Run your app in production server

Working code

    public static void SendEmail(string emailTo, string subject, string body)
    {
        var client = new SmtpClient("smtp.gmail.com", 587)
        {
            Credentials = new NetworkCredential("[email protected]", "secretpassword"),
            EnableSsl = true
        };

        client.Send("[email protected]", emailTo, subject, body);
    }

Turning off 2-factor authentication Turning off 2-factor authentication

Set "Allow less secure apps" to ON (same page, need to scroll to bottom) Allow less secure apps


You should disallow less secure apps to access your google account.

to do:

https://myaccount.google.com/lesssecureapps


I had the same problem for an application deployed to Microsoft Azure.

SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

First I approved all unknown devices (some ip-addresses originating from Ireland) on the following page (signed in as the gmail user): https://security.google.com/settings/u/1/security/secureaccount

I used the following settings for the client:

var client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("[email protected]", "my_password"); 

It started working only after I set the following property on the smtp-client:

client.TargetName = "STARTTLS/smtp.gmail.com";

First, I purchased the domain in GoDaddy, and when I clicked this link https://www.google.com/settings/security/lesssecureapps I didn't have the option, it show this message "The domain administrator manages these settings", so I go to the Admin Console https://admin.google.com/

There is this option enter image description here

Then appears the option that I needed in enter image description here


I used all of the above mentioned solutions but it finally worked only after i enabled IMAP Access from Gmail settings Link to Enable IMAP Access in gmail settings

Of course, the points in the other solutions were required too.


I have really looked at a lot of ideas, the only solution was this way (works with different email Providers):

            try
        {
            ViewProgressbar("Try to connect mail-server...", progressBar1.Value = 20);
            string host = dsProvider.Rows[y]["POP_hostOut"].ToString();
            int port = int.Parse(dsProvider.Rows[y]["POP_portOut"].ToString());  //587
            string[] email = von1.Split('@');
            string userName = (dsProvider.Rows[y]["login"].ToString() == "email[0]@email[1]")? email[0]+"@"+email[1] : email[0];
            string password = layer.getUserPassword(listSender.SelectedValue.ToString());
            SmtpClient client = new SmtpClient(host, port);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            //A idea from MSDN but it not works. You got "The server response was: 5.5.1 Authentication Required."
            //System.Net.NetworkCredential myCreds = new System.Net.NetworkCredential(userName, password, host);
            //System.Net.CredentialCache cache = new System.Net.CredentialCache();
            //cache.Add(host, port, "NTLM", myCreds);
            ///cache.GetCredential(host, port, "NTLM");   //NTLM
            client.Credentials = new System.Net.NetworkCredential(userName, password);
            client.Host = host;
            client.Port = port;
            client.EnableSsl = true;
            client.Send(message);
            ViewProgressbar();
        }
        catch (SmtpException ex)...

try changing the host, this is the new one, I got this configuring mozilla thunderbird

Host = "smtp.googlemail.com"

that work for me


Its a security issue, Gmail by default prevents access for your e-mail account from custom applications. You can set it up to accept the login from your application.

After Logging in to your e-mail, CLICK HERE

This will take you to the following page

Less Secure Apps Page


When you try to send mail from code and you find the error "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required", than the error might occur due to following cases.

case 1: when the password is wrong

case 2: when you try to login from some App

case 3: when you try to login from the domain other than your time zone/domain/computer (This is the case in most of scenarios when sending mail from code)

There is a solution for each

solution for case 1: Enter the correct password.

solution 1 for case 2: go to security settings at the followig link https://www.google.com/settings/security/lesssecureapps and enable less secure apps . So that you will be able to login from all apps.

solution 2 for case 2:(see https://stackoverflow.com/a/9572958/52277) enable two-factor authentication (aka two-step verification) , and then generate an application-specific password. Use that newly generated password to authenticate via SMTP.

solution 1 for case 3: (This might be helpful) you need to review the activity. but reviewing the activity will not be helpful due to latest security standards the link will not be useful. So try the below case.

solution 2 for case 3: If you have hosted your code somewhere on production server and if you have access to the production server, than take remote desktop connection to the production server and try to login once from the browser of the production server. This will add excpetioon for login to google and you will be allowed to login from code.

But what if you don't have access to the production server. try the solution 3

solution 3 for case 3: You have to enable login from other timezone / ip for your google account.

to do this follow the link https://g.co/allowaccess and allow access by clicking the continue button.

And that's it. Here you go. Now you will be able to login from any of the computer and by any means of app to your google account.


If your are using gmail.

  • 1-logon to your account

    2- browse this link

    3- Allow less secure apps: ON

Enjoy....


Hi I had the same issue,

what I've done to solve it. is to turn on the less secure app. after connecting to my gmail account. I entered this link: https://www.google.com/settings/security/lesssecureapps

Then I turn on the secure app and, and the it worked. it has been said also above


Below is my code.I also had the same error but the problem was that i gave my password wrong.The below code will work perfectly..try it

            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");             
            mail.From = new MailAddress("[email protected]");
            mail.To.Add("[email protected]");
            mail.To.Add("[email protected]");
            mail.Subject = "Password Recovery ";
            mail.Body += " <html>";
            mail.Body += "<body>";
            mail.Body += "<table>";
            mail.Body += "<tr>";
            mail.Body += "<td>User Name : </td><td> HAi </td>";
            mail.Body += "</tr>";

            mail.Body += "<tr>";
            mail.Body += "<td>Password : </td><td>aaaaaaaaaa</td>";
            mail.Body += "</tr>";
            mail.Body += "</table>";
            mail.Body += "</body>";
            mail.Body += "</html>";
            mail.IsBodyHtml = true;
            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("sendfrommailaddress.com", "password");
            SmtpServer.EnableSsl = true;
            SmtpServer.Send(mail);

You can refer it in my blog


dont put break-point before await smtp.SendMailAsync(mail);

:)

when it waits with a break point giving this error when i remove break point it has worked


After spending a couple of hours today trying every solution here, I was still unable to get past this exact error. I have used gmail many times in this way so I knew it was something dumb, but nothing I did fixed the problem. I finally stumbled across the solution in my case so thought I would share.

First, most of the answers above are also required, but in my case, it was a simple matter of ordering of the code while creating the SmtpClient class.

In this first code snippet below, notice where the Credentials = creds line is located. This implementation will generate the error referenced in this question even if you have everything else set up properly.

System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient
{
    Host = Emailer.Host,
    Port = Emailer.Port,
    Credentials = creds,
    EnableSsl = Emailer.RequireSSL,
    UseDefaultCredentials = false,
    DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network
}

However, if you move the Credentials setter call to the bottom, the email will be sent without error. I made no changes to the surrounding code...ie...the username/password, etc. Clearly, either the EnableSSL, UseDefaultCredentials, or the DeliveryMethod is dependent on the Credentials being set first... I didn't test all to figure out which one it was though.

System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient
{
    Host = Emailer.Host,
    Port = Emailer.Port,
    EnableSsl = Emailer.RequireSSL,
    UseDefaultCredentials = false,
    DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
    Credentials = creds
}

Hope this helps save someone else some headaches in the future.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to smtp

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error PHPMailer - SMTP ERROR: Password command failed when send mail from my server php function mail() isn't working Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required "An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14" SmtpException: Unable to read data from the transport connection: net_io_connectionclosed How to configure SMTP settings in web.config Send mail via CMD console Mail not sending with PHPMailer over SSL using SMTP

Examples related to gmail

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted How to to send mail using gmail in Laravel? HTML image not showing in Gmail Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required Send email from localhost running XAMMP in PHP using GMAIL mail server The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp Gmail: 530 5.5.1 Authentication Required. Learn more at Sending mail attachment using Java Javamail Could not convert socket to TLS GMail Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?