165

I want to send an email from my application and i have written following code for sending mail

    MailMessage msg = new MailMessage();

    msg.From = new MailAddress("mymailid");
    msg.To.Add("receipientid");
    msg.Subject = "test";
    msg.Body = "Test Content";
    msg.Priority = MailPriority.High;

    SmtpClient client = new SmtpClient();

    client.Credentials = new NetworkCredential("mymailid", "mypassword", "smtp.gmail.com");
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.EnableSsl = true;
    client.UseDefaultCredentials = true;

    client.Send(msg);

I am running it on localhost so what mistake i am doing to send it.

When i send button it gives an error like

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

Code in Web.config file

 <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />   
    <add key="smtpServer" value="smtp.gmail.com" />
    <add key="EnableSsl" value = "true"/>
    <add key="smtpPort" value="587" />
    <add key="smtpUser" value="sender@gmail.com" />
    <add key="smtpPass" value="mypassword" />
    <add key="adminEmail" value="sender@gmail.com" />
  </appSettings>
  <system.net>
    <mailSettings>
      <smtp from="sender@gmail.com">
        <network host="smtp.gmail.com" password="mypassword" port="587" userName="sender@gmail.com"  enableSsl="true"/>
      </smtp>
    </mailSettings>
  </system.net>

what should i do to solve this error and send mail??

meda
  • 45,103
  • 14
  • 92
  • 122
Abhay Andhariya
  • 1,989
  • 3
  • 16
  • 24
  • possible duplicate of [Sending email in .NET through Gmail](http://stackoverflow.com/questions/32260/sending-email-in-net-through-gmail) – Roman R. Aug 29 '13 at 06:45
  • I think you may have to look in to this answer, too : http://stackoverflow.com/a/9572958/1136253 – Bengi Besçeli Sep 22 '13 at 10:11
  • I had the same problem. check [this post][1] [1]: http://stackoverflow.com/a/20186909/709340 – Moslem Hadi Nov 27 '13 at 16:47
  • You should consider to specify SMTP configuration data in config file and do not overwrite them in a code - see SMTP configuration data at http://www.systemnetmail.com/faq/4.1.aspx – Michael Freidgeim Jun 11 '16 at 05:23
  • it's may help you [The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated](https://spgeeks.devoworx.com/the-smtp-server-requires-a-secure-connection-or-the-client-was-not-authenticated-the-server-response-was-5-7-1-client-was-not-authenticated/) – Mohamed Jan 31 '20 at 18:39
  • Update 6/30/2020: With port 587 and EnableSsl = TRUE and Google less secure ON it should works. ALSO ENABLE SSL/TLS support on your host (in your website control panel); For example in Plesk control panel, Add a self-signed SSL/TLS Certificate, then go to Hosting Settings and enable that damn SSL/TLS checkbox. – Ehsan Jun 30 '20 at 11:24

32 Answers32

226

I have the same problem.

I have found this solution:

Google may block sign in attempts from some apps or devices that do not use modern security standards. Since these apps and devices are easier to break into, blocking them helps keep your account safer.

Some examples of apps that do not support the latest security standards include:

  • The Mail app on your iPhone or iPad with iOS 6 or below
  • The Mail app on your Windows phone preceding the 8.1 release
  • Some Desktop mail clients like Microsoft Outlook and Mozilla Thunderbird

Therefore, you have to enable Less Secure Sign-In (or Less secure app access) in your google account.

After sign into google account, go to:

https://www.google.com/settings/security/lesssecureapps
or
https://myaccount.google.com/lesssecureapps

In C#, you can use the following code:

using (MailMessage mail = new MailMessage())
{
    mail.From = new MailAddress("email@gmail.com");
    mail.To.Add("somebody@domain.com");
    mail.Subject = "Hello World";
    mail.Body = "<h1>Hello</h1>";
    mail.IsBodyHtml = true;
    mail.Attachments.Add(new Attachment("C:\\file.zip"));

    using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
    {
        smtp.Credentials = new NetworkCredential("email@gmail.com", "password");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }
}
mjb
  • 7,649
  • 8
  • 44
  • 60
  • 1
    This along with ensuring that SSL was enabled in the code has worked wonders, thanks a lot – Crouch Nov 24 '14 at 12:43
  • 4
    this should be the selected answer – thatOneGuy Aug 13 '15 at 14:44
  • 2
    This was my issue, thank you for going through the trouble and giving out a more explanatory answer. – Bagzli Nov 19 '15 at 00:39
  • Yep. Turns out I had to enable "Less Secure Sign-In" on my target gmail account. Thanks! – SgtRock Feb 15 '16 at 23:14
  • I have turned on "access for less secure apps" - yet it still fails (and logs the failure on the gmail site). Any ideas how I can force it to work? – niico May 06 '16 at 17:42
  • 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:24
  • @MichaelFreidgeim thanks for the sharing, I have added your info into my post – mjb Jun 09 '16 at 01:16
  • Da, this solves my problem. :). Thank you for sharing. – Redplane Jun 16 '16 at 02:39
  • Awesome...... You saved my time. And thanks a ton for the direct link to turn off the switch! – Balaji Birajdar Jan 22 '20 at 10:53
  • This should be the ANSWER. – Mohammad Taherian Sep 21 '20 at 20:40
  • best answer ta. It all comes down to the google less secure sign in, nothing to do with code on the developer side. – markthewizard1234 Nov 08 '20 at 10:57
  • I turned it on before. but it was switched to off again after a while. I turned it on again and it works. thanks. – Hossein Badrnezhad Nov 20 '21 at 07:34
  • Less secure app enabling feature is no longer available in google account for security reasons! Using App Password resolved the problem! As answered by @Roman O https://stackoverflow.com/a/66169647/6836199 – Khalid Bin Sarower Jun 08 '22 at 06:21
  • 4
    As of May 30, 2022 less secure apps are no longer supported from Googlem so you have to use App Passwords. https://support.google.com/accounts/answer/6010255?authuser=1&hl=en-GB&authuser=1&visit_id=637957424028050444-425688120&p=less-secure-apps&rd=1 – Franco Aug 10 '22 at 15:47
  • 1
    solution for gmail is here https://stackoverflow.com/questions/67950293/how-to-fix-gmail-smtp-error-the-smtp-server-requires-a-secure-connection-or-th – kuklei Oct 10 '22 at 10:25
87

First check for gmail's security related issues. You may have enabled double authentication in gmail. Also check your gmail inbox if you are getting any security alerts. In such cases check other answer of @mjb as below

Below is the very general thing that i always check first for such issues

client.UseDefaultCredentials = true;

set it to false.

Note @Joe King's answer - you must set client.UseDefaultCredentials before you set client.Credentials

Community
  • 1
  • 1
Ronak Patel
  • 2,570
  • 17
  • 20
  • 2
    In that case you should share your code. Above answer is for the code in question – Ronak Patel Jul 09 '14 at 07:16
  • 9
    Note @Joe King's answer - you must set client.UseDefaultCredentials *before* you set client.Credentials – Aaron Jul 17 '15 at 02:36
  • 2
    This answer won't work, I think most people faced security on gmail side. see mjb's answer for a proper solution – OKEEngine Feb 24 '16 at 23:24
  • 2
    Also, make sure the "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:24
  • 4
    Setting client.UseDefaultCredentials = false; before client.Credentials and setting client.EnableSsl = true; did the trick in my case. – Stacked Jun 25 '16 at 02:18
  • I had the same problem, it worked after I "Turn on" access to less secure app via gmail alerts – Saad A Oct 24 '16 at 16:11
  • Nops, doesnt work for me either. I have set it to false before the credentials, just after creating the SmtpClient object, no difference. THe docs also says that this is set to false by default, so I guess it was false from the beginning for me. – Ted Nov 07 '16 at 20:11
  • @SaadA said it: Its google who blocked the usage/login. It said it had blocked login attempts, and that I should enable "less secure apps". Which I did, and then it works. – Ted Nov 07 '16 at 20:16
  • Super duper duper duper duper duper dooper thank you. I had been haggling with this for all of today since morning (over 7 hours now) trying out "App Passwords", "Less Secure Accounts" turning them off and on, and a whole lot of other things. Turns out just setting the `client.UseDefaultCredentials = false` *before* setting the `client.Credentials` made it work. That was *all* that the problem was. Holy phew now! – Water Cooler v2 Oct 06 '19 at 12:51
  • First I turned off gmail two step verification. and Allow Less secure app access: ON.. worked for me. – Waqas Javaid Jun 12 '20 at 15:10
  • As of May 30, 2022 less secure apps are no longer supported from Googlem so you have to use App Passwords. https://support.google.com/accounts/answer/6010255?authuser=1&hl=en-GB&authuser=1&visit_id=637957424028050444-425688120&p=less-secure-apps&rd=1 – Franco Aug 10 '22 at 15:50
60

Ensure you set SmtpClient.Credentials after calling SmtpClient.UseDefaultCredentials = false.

The order is important as setting SmtpClient.UseDefaultCredentials = false will reset SmtpClient.Credentials to null.

Joseph King
  • 5,089
  • 1
  • 30
  • 37
  • 4
    I've been looking for the solution to this for half an hour, yours is the only little post on the internet I've found that mentions the ordering of this. Thanks mate. –  May 19 '15 at 21:33
  • 4
    @Joe King You are just awesome mate..... was searching for this since 3 hours :) – Jatin May 25 '15 at 02:58
  • 1
    Thank you @Joe King that is vital information missing from the MS docs. This was the solution to my problem sending with username and password also. – Aaron Jul 17 '15 at 02:35
  • 1
    This is easily overlooked but the ordering is important as I just found out. – GatesReign Nov 11 '15 at 15:35
  • 1
    yeah. saved my day. you need to call UseDefaultCredentials = false before setting Credentials. – Rendel Jan 26 '16 at 14:39
  • That is a lifesaving answer! Thanks! – Michael Brennt Apr 12 '16 at 13:42
  • I spent days looking for this answer. note that the order also makes a difference if your smtp client settings are in the web.config. for example: `` – desertchief Aug 18 '19 at 06:34
50

I've searched and tried different things for hours.. To summarize, I had to take into consideration the following points:

  1. Use smtp.gmail.com instead of smtp.google.com
  2. Use port 587
  3. Set client.UseDefaultCredentials = false; before setting credentials
  4. Turn on the Access for less secure apps
  5. Set client.EnableSsl = true;

If these steps didn't help, check this answer.
Perhaps, you can find something useful on this System.Net.Mail FAQ too.

Community
  • 1
  • 1
Stacked
  • 6,892
  • 7
  • 57
  • 73
27

App Passwords helped me.

  1. Go to https://myaccount.google.com/security.
  2. Scroll down to "Signing in to Google".
  3. Enable 2-Step Verification.
  4. Add App Password.
  5. Use the generated password in your code.

You can also use direct link https://myaccount.google.com/apppasswords

Roman O
  • 3,172
  • 30
  • 26
  • Although this solution works, it would send emails right into the Spam folder. Please, double-check this. Thanks. – Joseph L. Sep 13 '21 at 19:59
  • 3
    after 30th May 2022 with removal of less secure option, App Password is working, you'll have to set two step verification first then you can generate app password and use it in your code – dnxit Jul 01 '22 at 18:18
  • @dnxit despite doing both, my program isnt working. Please help. – kedarK Jul 18 '23 at 04:03
13

Try it this way, I just made some light changes:

MailMessage msg = new MailMessage();

msg.From = new MailAddress("mymailid@gmail.com");
msg.To.Add("receipientid@gmail.com");
msg.Subject = "test";
msg.Body = "Test Content";
//msg.Priority = MailPriority.High;


using (SmtpClient client = new SmtpClient())
{
    client.EnableSsl = true;
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential("mymailid@gmail.com", "mypassword");
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;

    client.Send(msg);
}

Also please show your app.config file, if you have mail settings there.

meda
  • 45,103
  • 14
  • 92
  • 122
13

Try to login in your gmail account. it gets locked if you send emails by using gmail SMTP. I don't know the limit of emails you can send before it gets locked but if you login one time then it works again from code. make sure your webconfig setting are good.

Shuchita Bora
  • 257
  • 2
  • 5
  • Best answer indeed! I logged in again and it worked ! PS: I had to provide a captcha on Google – Bellash Feb 21 '14 at 09:33
  • I got this error as my Google account is protected with two-factor authentication. I ended up creating a dedicated account to send the email from. – MvdD Apr 19 '14 at 23:41
12

As of May 30, 2022 less secure apps are no longer supported from Google so you have to use App Passwords.

https://support.google.com/accounts/answer/6010255?authuser=1&hl=en-GB&authuser=1&visit_id=637957424028050444-425688120&p=less-secure-apps&rd=1

Here are the steps to set up an app password via google: https://support.google.com/accounts/answer/185833?authuser=1

Then you need to use the 16 character app password for the smtpClient's credentials:

smtpClient = new SmtpClient(emailHost)
{
     Port = port,
     DeliveryMethod = SmtpDeliveryMethod.Network,
     Credentials = new NetworkCredential(fromEmail, emailPassword),
     EnableSsl = true,
 };

The emailpassword should be the 16 character generated App Password.

Port: 587

Emailhost: smtp.gmail.com

Then the rest of the code:

var mailMessage = new MailMessage{
                    From = new MailAddress(fromEmail),
                    Subject = "Yoursubject",
                    Body = $"Your body",
                    IsBodyHtml = true,
                };
                mailMessage.To.Add(newEmail);

                if (smtpClient != null)
                    smtpClient.Send(mailMessage);
Franco
  • 441
  • 3
  • 18
  • 1
    This answer really helped me, except for emailhost which was bit confusing due to upper and lowercase – Samra Dec 11 '22 at 23:56
7

Turn on less secure app from this link and boom...

Behzad Qureshi
  • 546
  • 1
  • 7
  • 16
6

try to enable allow less secure app access.

Here, you can enable less secure app after login with your Gmail.

https://myaccount.google.com/lesssecureapps

Thanks.

Raviteja V
  • 454
  • 5
  • 11
6

For security reasons, Google has discontinued turning on Access for Less Secure Apps, effective from May 30, 2021. Hence, some of the answers here that emphasized enabling access for less secure apps have become obsolete.

Here is an answer I found on VB Forum and it worked for me. I was able to send a mail successfully.

"Please do following steps. In Google Account Activate 2-step verification. Select App Password in Google Account => Security => Signing to Google. In Select App Combo Select Other and Name as Windows App & Click Generate it. Copy Password and use it in place of email password. It will work."

Check out the link to see more answers. https://www.vbforums.com/showthread.php?895413-Sending-Email-via-Gmail-changing-for-May-30

Scroll down and see the answer posted by microbrain

See the code with which I sent my mail below:

Dim emailTo As String = TxtEmail.Text.Trim()
        If emailTo.Length > 10 Then
            Try
                Dim Smtp_Server As New SmtpClient
                Dim e_mail As New MailMessage()
                Smtp_Server.UseDefaultCredentials = False
                Smtp_Server.Credentials = New Net.NetworkCredential("myemail@gmail.com", "***16-digit-code***")
                Smtp_Server.Port = 587
                Smtp_Server.EnableSsl = True
                Smtp_Server.Host = "smtp.gmail.com"

                e_mail = New MailMessage()
                e_mail.From = New MailAddress("myemailaddress@gmail.com")
                e_mail.To.Add(emailTo)
                e_mail.Subject = "Login OTP"
                e_mail.IsBodyHtml = False
                e_mail.Body = "some text here"
                Smtp_Server.Send(e_mail)
                MessageBox.Show("Your login OTP has been sent to " & emailTo)
                LblOTPSuccess.Visible = True
                TxtOTP.Visible = True
                BtnVerifyOTP.Visible = True
                TxtOTP.Focus()
            Catch error_t As Exception
                MessageBox.Show(error_t.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        Else
            MessageBox.Show("Email address is invalid or too short", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If

Remember to change the parameters in the code to suit you.

John Chidi
  • 91
  • 1
  • 3
5

I encountered the same problem even I set "UseDefaultCredentials" to false. Later I found that the root cause is that I turned on "2-step Verification" in my account. After I turned it off, the problem is gone.

Soros Liu
  • 96
  • 1
  • 5
  • 5
    Don't turn off 2 step verification. It s there for a reason. You can generate an application-specific password in GMail settings and use that in the SmtpClient. You should be doing that regardless rather than exposing a normal password. – Daniel Dyson May 28 '15 at 22:24
4

enter image description here Make sure that Access less secure app is allowed.

        MailMessage mail = new MailMessage();
        mail.From = new MailAddress("xx@gmail.com");
        mail.Sender = new MailAddress("xx@gmail.com");
        mail.To.Add("external@emailaddress");
        mail.IsBodyHtml = true;
        mail.Subject = "Email Sent";
        mail.Body = "Body content from";

        SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
        smtp.UseDefaultCredentials = false;

        smtp.Credentials = new System.Net.NetworkCredential("xx@gmail.com", "xx");
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.EnableSsl = true;

        smtp.Timeout = 30000;
        try
        {

            smtp.Send(mail);
        }
        catch (SmtpException e)
        {
            textBox1.Text= e.Message;
        }
Shivam Srivastava
  • 4,496
  • 2
  • 23
  • 24
  • 1
    The link to toggle the setting for "Access less secure app" is here - https://www.google.com/settings/security/lesssecureapps Changing the setting didn't help me overcome the error – mvark Jul 19 '15 at 05:20
3

In my case, I was facing the same issue. After a long research, don't set UseDefaultCredentials value to false. Because default value of UseDefaultCredentials is false.

Another key point is to set network credential just before the client.send(message) statement.

Wrong Code:

SmtpClient client = new SmtpClient();
client.Host = ServerName; 
var credentials = new System.Net.NetworkCredential(UserName, Password);
client.Credentials = credentials;
client.Port = Port;
client.EnableSsl = EnableSSL;
client.UseDefaultCredentials = false;
client.Send(message);

Wrong Code:

SmtpClient client = new SmtpClient();
client.Host = ServerName; 
var credentials = new System.Net.NetworkCredential(UserName, Password);
client.Credentials = credentials;
client.Port = Port;
client.EnableSsl = EnableSSL;
client.UseDefaultCredentials = true;
client.Send(message);

Correct code

SmtpClient client = new SmtpClient();
client.Host = ServerName; 
var credentials = new System.Net.NetworkCredential(UserName, Password);
client.Credentials = credentials;
client.Port = Port;
client.EnableSsl = EnableSSL;
// client.UseDefaultCredentials = true;
client.Send(message);

Correct code

SmtpClient client = new SmtpClient();
client.Host = ServerName; 
client.Port = Port;
client.EnableSsl = EnableSSL;
client.UseDefaultCredentials = false;
var credentials = new System.Net.NetworkCredential(UserName, Password);
client.Credentials = credentials;
client.Send(message);

Now its working ok with both corrected codes. So in this case sequence matters.

Cheers!

Naimatullah
  • 3,749
  • 2
  • 13
  • 12
2

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 reffer it in Sending mail

1

If it's a new google account, you have to send an email (the first one) through the regular user interface. After that you can use your application/robot to send messages.

1

You should consider to specify SMTP configuration data in config file and do not overwrite them in a code - see SMTP configuration data at http://www.systemnetmail.com/faq/4.1.aspx

<system.net>
            <mailSettings>
                <smtp deliveryMethod="Network" from="admin@example.com">
                    <network defaultCredentials="false" host="smtp.example.com" port="25" userName="admin@example.com" password="password"/>
                </smtp>
            </mailSettings>
        </system.net>
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
1

I have encountered the same problem several times. After enabling less secure app option the problem resolved. Enable less secure app from here: https://myaccount.google.com/lesssecureapps

hope this will help.

Mahmud
  • 369
  • 4
  • 13
1

I created a Microsoft 365 Developer subscription (E5) today morning and used it to send a test email using the following settings

using (SmtpClient client = new SmtpClient())
{
    client.EnableSsl = true;
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential(username, password);
    client.Host = "smtp.office365.com";
    client.Port = 587;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;

    client.Send(msg);
}

It did not work in the beginning, as I kept getting this error message with the exception thrown by this code. Then, I spent about 4+ hours playing with the Microsoft 365 admin centre settings and reading articles to figure out the issue. Ultimately I changed my Microsoft 365 admin centre password and it worked like a charm. So, it is worth to try changing the password when you get this message, before thinking about any advance solution.

Note that the password wasn't invalid for sure as I logged on to my Microsoft 365 account without any issues. however, the password change solved the issue.

Kushan Randima
  • 2,174
  • 5
  • 31
  • 58
1

After going through each of every proposed solution, I realized the correct answer depends on your current server and email client situation. In my case, I have the MX record pointing to my on-premise outbound server. Also, since I'm using G Suite and not Gmail to send my notification emails, I had to follow this configuration: https://support.google.com/a/answer/2956491?hl=en.

Having said this, I found the right way to make this work, is indeed configuring the SMTP relay service first from my G Suite account:

SMTP_Relay Configuration GSuite

Relay Settings Details

IPv6 address is the address of the webserver the MX record is pointing at (example: 1234:454:c88a:d8e7:25c0:2a9a:5aa2:104).

Once this is done, use this code to complement the solution:

 //Set email provider credentials
 SmtpClient smtpClient = new SmtpClient("smtp-relay.gmail.com", "587");                   

 smtpClient.EnableSsl = true;
 smtpClient.UseDefaultCredentials = true;
 
 MailAddress from = new MailAddress("username@yourdomain.com", "EmailFromAlias");
 MailAddress to = new MailAddress("destination@anydomain.com");

 MailMessage = new MailMessage(from, to);

 MailMessage.Subject = subject;
 MyMailMessage.Body = message;

 MyMailMessage.IsBodyHtml = false;

 smtpClient.Send(MyMailMessage);

Please, notice that with this method, smtpClient.UseDefaultCredentials = true; and not false as suggested in other solutions. Also, since we use the IPv6 address to connect to the SMTP client, it's not required to specify the user name or password. Therefore, in my opinion, this is a more secure and safe approach.

Joseph L.
  • 431
  • 6
  • 7
0

some smtp servers (secure ones) requires you to supply both username and email, if its gmail then most chances its the 'Less Secure Sign-In' issue you need to address, otherwise you can try:

public static void SendEmail(string address, string subject, 
    string message, string email, string username, string password, 
    string smtp, int port)
{
    var loginInfo = new NetworkCredential(username, password);
    var msg = new MailMessage();
    var smtpClient = new SmtpClient(smtp, port);

    msg.From = new MailAddress(email);
    msg.To.Add(new MailAddress(address));
    msg.Subject = subject;
    msg.Body = message;
    msg.IsBodyHtml = true;

    smtpClient.EnableSsl = true;
    smtpClient.UseDefaultCredentials = false;
    smtpClient.Credentials = loginInfo;
    smtpClient.Send(msg);
}

notice that the email from and the username are different unlike some implementation that refers to them as the same.

calling this method can be done like so:

SendEmail("to-mail@gmail.com", "test", "Hi it worked!!", 
   "from-mail", "from-username", "from-password", "smtp", 587);
Yakir Manor
  • 4,687
  • 1
  • 32
  • 25
0

If you are in a test environment and do not want to set security settings you have to allow less secure apps via. this link in Gmail.

https://myaccount.google.com/lesssecureapps

Fahad S. Ali
  • 1,284
  • 1
  • 7
  • 7
0

I had the same issue, it was resolved by change password to strong password.

Farzaneh Talebi
  • 835
  • 4
  • 22
  • 47
0

If you face this issue with Office 365 account. In Exchange Online, by default, the SMTP Client Authentication will be disabled for all Office 365 mailbox accounts. You have to manually enable SMTP Auth for the problematic account and check the case again. Check the below threads.

https://morgantechspace.com/2021/01/the-smtp-server-requires-a-secure-connection-or-the-client.html

https://learn.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission

Kevin M
  • 5,436
  • 4
  • 44
  • 46
0

I have used the steps in this question and it worked for me.

My issue was that G suite didn't consider my password as strong and after changing it it worked perfectly.

Simple Code
  • 2,354
  • 2
  • 27
  • 56
0

If all mentioned solutions didn't help, try to use this URL - it helped me to unblock email sending at my website

https://g.co/allowaccess

DonSleza4e
  • 562
  • 6
  • 11
0

that can be if: 1)the user or pass are wrong 2)not enable SSL 3)less secure app is not enable 4)you have not log in into the server with this mail 5)you have not set client.UseDefaultCredentials = false

Dayannex
  • 51
  • 3
0

Removing the port field worked in my case

Gülsen Keskin
  • 657
  • 7
  • 23
0

Although this question is regarding the error" The server response was: 5.5.1 Authentication Required. We are presented with this result when we search for The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required

Hence this answer is for those who are getting an error:

The server response was: 5.7.0 Authentication Required.

If your C# code is correct, change these 2 settings in your Google Account. This error arises mostly when the code is correct, but the account is not set properly to send emails.

  • Enable 2 Step verification in Your Google Account.

    • In your account settings click Manage your Google Account.

    • Under Security. You'll find How you sign in to Google section. Enable 2 Step verification by following the process.

  • Get App Password from How you sign in to Google section.

Follow this YouTube video for the enabling process.

You can use your own code from official documentation.

Junaid Pathan
  • 3,850
  • 1
  • 25
  • 47
-1

After turning less secure option on and trying other solutions, if you are still facing the same problem try to use this overload:

client.Credentials = new NetworkCredential("mymailid", "mypassword");

instead of:

client.Credentials = new NetworkCredential("mymailid", "mypassword", "smtp.gmail.com");
ssmsexe
  • 209
  • 2
  • 4
  • 10
-1

I was also facing the issue like 'The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.0 Authentication Required' then went through so much internet materials but it didn't helped me fully. How I solved it like

step1:smtp.gmail.com is gmail server so go to your account gmail settings->click on see all settings->Forwarding and IMAP/POP->check pop and imap is enabled ,if not enable it->Save changes. step2-click on your gmail profile picture->click on Manage your google account->go to security tab->check for Access to less secure apps(this option will be available if you havent opt for two step verification)->by default google will set it as disable, make it enable to use your real gmail password working for sending email. note:-Enabling gmail access for less secure apps,may be dangerous for you so i dont recommend this

step3:-if your account has two step verification enabled or want to use password other than your gmail Real password using app specific password then try this:- click on your gmail profile picture->click on Manage your google account->go to security tab->search for APP PASSWORD->select any app name given->select any device name->click on generate->copy the 16-digit password and paste it into your app where you have to enter a gmail password in place of your real gmail password.

-1

Try it this way and nesessarily enable Less secure apps by clicking this link

        var fromEmail = new MailAddress("your@gmail.com", "Title");
        var toEmail = new MailAddress(emailID);
        var fromEmailPassword = "yourPassword"; 
         

        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
        };
            using (var message = new MailMessage(fromEmail, toEmail)
            {
                Subject = subject,
                Body = body,
                IsBodyHtml = true
            })

                smtp.Send(message);
Gadiyevich
  • 67
  • 1
  • 7