306

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("mymailid@gmail.com");
var fromPassword = "xxxxxx";
var toAddress = new MailAddress("yourmailid@yourdoamain.com");

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 mymailid@gmail.com. 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

A. Gladkiy
  • 3,134
  • 5
  • 38
  • 82
vcs
  • 3,675
  • 4
  • 17
  • 15
  • Turn off 2-step verification.. – Mangesh Jan 18 '15 at 05:41
  • Please, look at http://stackoverflow.com/questions/34851484/how-to-send-an-email-in-net-according-to-new-google-security-policies –  Jan 20 '16 at 08:27
  • 1
    Also, make sure the google "Captcha" is disabled - this may be necessary if you are running the script on a remote server (not necessary when running on local machine): https://accounts.google.com/DisplayUnlockCaptcha – Jens May 17 '16 at 16:17
  • Encounter the same error for me. After looking couple of post, I tried with changing my existing week password to strong password. Then it worked. After password change, it also asked questions such as are you Ok to access your mail from less secure apps? I said Ok. – venkat May 28 '18 at 05:04
  • Google dropped support for less secure apps. You'll need to generate a password using this method: https://stackoverflow.com/a/72553362 – NTDLS Jun 24 '22 at 01:57

21 Answers21

356

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.

Community
  • 1
  • 1
Roshan Parmar
  • 3,692
  • 1
  • 11
  • 7
223

This generally happens when you try login from different time zone or IP Address Computer. Your production server and the mail id you have used both are in different time zone. Choose either of these two solutions:

1) Log in to production server via remote access, and sign in to gmail once with your credentials. They will ask for the confirmation, confirm it and log out.

Or 2) log in gmail to your local computer, Follow this Link and choose review this activity and take proper actions.

CodeChops
  • 1,980
  • 1
  • 20
  • 27
Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61
  • 23
    A little comment: go to https://security.google.com/settings/security/activity and here you'l see blocked connection from your code. Allow them and it should help in this case. – Alex Zhukovskiy Oct 02 '14 at 12:45
  • 72
    This will also help a lot: https://www.google.com/settings/security/lesssecureapps –  Oct 12 '14 at 02:23
  • Yes, the reason is 2 steps verification switched On for gmail account. Select App/Device and click Generate button https://support.google.com/accounts/answer/185833 – smily Dec 25 '15 at 15:34
  • Look at http://stackoverflow.com/questions/34851484/how-to-send-an-email-in-net-according-to-new-google-security-policies –  Jan 20 '16 at 08:27
  • 14
    Also, make sure the google "Captcha" is disabled - this may be necessary if you are running the script on a remote server (not necessary when running on local machine): https://accounts.google.com/DisplayUnlockCaptcha – Jens May 17 '16 at 16:18
  • @Alex that did the trick, I "verified" server by confirming it was my activity now it works! – solujic Jul 19 '18 at 12:00
  • Actually, I also faced the same issue and I had already allowed less secure access. What worked for me is this [link](https://g.co/allowaccess). We need to allow access to each app no matter from which app the user is using from. You can get more details from this [link](https://www.smarterasp.net/support/kb/a1546/send-email-from-gmail-with-smtp-authentication-but-got-5_5_1-authentication-required-error.aspx) – Praveen Jul 04 '19 at 08:26
  • Great answer, thank you. Anyway, I've discovered today that the gmail option to allow unsecure apps will be deprecated from 30 May 2022. – Fabio Pagano Mar 28 '22 at 14:43
133

UPDATE 2022

Less Secure Apps method no longer works

You should migrate to GMail SMTP API

Sending email with just a gmail id and password no longer works. You have to setup the api from Google Cloud Console and create OAuth credentials to do so.

Link to Google Cloud Console

Link to Official Guide

Link to An easy guide

enter image description here

ORIGINAL ANSWER

It is 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

Abdul Saleem
  • 10,098
  • 5
  • 45
  • 45
  • 1
    Also, if you have a custom domain, users first need to be enabled by domain administrator to allow access to less secure apps. If you are a domain admin, go to the following link to enable this https://admin.google.com/AdminHome#ServiceSettings/notab=1&service=securitysetting&subtab=lesssecureappsaccess – user551113 Feb 20 '17 at 11:51
  • 1
    Though this was enabled for me, it was not working initially. Later I turned it off and then turned it on. After turning off refresh the page and then turn it on, this worked for me. – John Feb 10 '21 at 15:22
  • 1
    This no longer works. https://support.google.com/accounts/answer/6010255?authuser=2&hl=en&authuser=2&visit_id=637916937761087007-1739608967&p=less-secure-apps&rd=1 – Crismogram Jun 24 '22 at 18:56
  • whoever commented that OAuth needs to be setup, I am halfway into setting up google oauth but it doesn't make sense why should my webapp user authorize sending of emails from my app with my account?..https://stackoverflow.com/questions/74793364/why-do-i-need-oauth-when-sending-emails-to-my-clients-via-gmail – Samra Dec 14 '22 at 05:56
29

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.

A. Gladkiy
  • 3,134
  • 5
  • 38
  • 82
user1011627
  • 1,741
  • 1
  • 17
  • 25
  • 2
    In my case, I had the same problem as yours, reorderring the code so that Credentials came last worked for me. – Dev Mar 24 '16 at 08:55
  • 1
    I can not believe it but it worked! I have enabled 2-step, because did not want to enable less secure flag, but till I put Credential last before Send it did not want to work. Incredible! – Čikić Nenad Feb 06 '17 at 14:47
  • 7
    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 – Tomasz Madeyski Nov 13 '17 at 14:21
  • @TomaszMadeyski this have to be an answer instead of comment! that is my problem... how the hell I can think that if I set credentials on constructor and then assign to a false value again UseDefaultCredentials = false it overrides the credentials... crazy!! but that happens.... thanks youuuuu – FabianSilva Feb 23 '18 at 10:16
  • 1
    This solution seems to not work anymore! – Sotiris Zegiannis Jun 16 '22 at 12:00
  • I second @SotirisZegiannis ' statement. Does not work for me, either. 2-step authentication enabled. – Marlo C Jun 22 '22 at 22:12
  • @MarloC did you get it through? I am banging my head since 2 days – Samra Dec 14 '22 at 05:50
  • @MarloC - Yes, I got this working, but this thread is 7 years old....google has likely changed a LOT since then. – user1011627 Dec 15 '22 at 18:09
15

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

Barak Rosenfeld
  • 307
  • 1
  • 6
  • 14
  • 1
    So what is the difference than your answer for [above](https://stackoverflow.com/a/27900000/1068538) answer ? Same answer is given before you on Jan 12 '15 at 10:36. – Dush Oct 15 '18 at 11:21
  • 1
    This setting is no longer available in the google account page! – Sotiris Zegiannis Jun 16 '22 at 11:43
  • @SotirisZegiannis this resolved it for me: https://stackoverflow.com/a/72553362 – NTDLS Jun 24 '22 at 01:56
14

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("youremail@gmail.com", "secretpassword"),
            EnableSsl = true
        };

        client.Send("youremail@gmail.com", 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

Jeson Martajaya
  • 6,996
  • 7
  • 54
  • 56
12

Gmail/Google has recently removed (from May 2022) Less Secure app access. This is what they says:

To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.

Now any emailer having direct SMTP email sending will throw error "535-5.7.8 Username and Password not accepted". This is because now Google is asking for app specific password and the email account password isn't app password so they show username/password not accepted.

You need to create and use App specific password. An app password works like an alternate password for your account. It can only be used by the applications you share it with, so it’s more secure than sharing your primary password.

To create app specific password:

  1. Enable 2 Factor Authentication.
  2. Go to Account settings of Gmail and select App Passwords.
  3. Name it whatever you want and create the password.
  4. Use this new 16 digit password along with gmail email for SMTP (At the place of password use this 16 digit password)

Enjoy sending emails..!!

enter image description here

enter image description here

enter image description here

JackSparrow
  • 948
  • 1
  • 11
  • 9
11

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

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Trung
  • 121
  • 1
  • 2
8

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.

fortran
  • 74,053
  • 25
  • 135
  • 175
Anik
  • 91
  • 1
  • 3
6

So as others have stated correctly, since May 30 google no longer supports the use of third-party apps accessing the account.

enter image description here

What i had to do in order to be able to access the account from my code, was first to enable 2-step verification. enter image description here

Once this is done, i created an App password. enter image description here

I then replaced the generated password, with the one i was using to access my account. In other words one needs to remove the gmail account password(the one we use to login to our gmail) with this new app-password and the functionality was back online!

I hope this helps someone:-)

  • Did you replace the newly generated password here? .Credentials = New NetworkCredential(fromEmail, "APP_PWD"), after sending email, my app still throws same smtp error – Samra Dec 14 '22 at 03:58
5

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("fromaddress@gmail.com");
            mail.To.Add("toaddress1@gmail.com");
            mail.To.Add("toaddress2@gmail.com");
            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

  • i am using the same code which is working in my local machine but its not working on server. Getting error **The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.**. – Akshay Chawla Jun 04 '17 at 15:03
  • 2
    i contacted my hosting provider they said : **We could see that you have configure third part SMTP (smtp.gmail.com) which will not support in our shared server environment. Due to excessive abuse of mail function or spamming problem, mail function is not supported. You can send email using PHPMailer, Which is very popular and often used.** but my site is build in mvc c#, so how can i use phpmailer ? – Akshay Chawla Jun 04 '17 at 15:15
4

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("my_user_name@gmail.com", "my_password"); 

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

client.TargetName = "STARTTLS/smtp.gmail.com";
haiiaaa
  • 183
  • 1
  • 7
4

After 30th may 2022 Gmail changed it's policy for external apps which using google SMTP for send e-mail For details. Solition is login google account that you want to send e-mail, enable google two step verification and create a password for external app. For details

cancan
  • 59
  • 6
3

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("from@gmail.com")
        mail.[To].Add("to@gmail.com")
        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

Edgar
  • 489
  • 2
  • 14
3

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...

FabianSilva
  • 405
  • 6
  • 18
3

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(asd@asd.com, "From Name");
var toAddress = new MailAddress("tosend@asd.com", "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);
}
InGeek
  • 2,532
  • 2
  • 26
  • 36
2

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.

Kris Coleman
  • 416
  • 3
  • 11
1

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

samiup
  • 304
  • 2
  • 6
0

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)...
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Walter
  • 11
  • 2
0

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

Hamit YILDIRIM
  • 4,224
  • 1
  • 32
  • 35
-6

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

Host = "smtp.googlemail.com"

that work for me

Vivek S.
  • 19,945
  • 7
  • 68
  • 85