263

For some reason neither the accepted answer nor any others work for me for "Sending email in .NET through Gmail". Why would they not work?

UPDATE: I have tried all the answers (accepted and otherwise) in the other question, but none of them work.

I would just like to know if it works for anyone else, otherwise Google may have changed something (which has happened before).

When I try the piece of code that uses SmtpDeliveryMethod.Network, I quickly receive an SmtpException on Send(message). The message is

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" <-- seriously, it ends there.

UPDATE:

This is a question that I asked a long time ago, and the accepted answer is code that I've used many, many times on different projects.

I've taken some of the ideas in this post and other EmailSender projects to create an EmailSender project at Codeplex. It's designed for testability and supports my favourite SMTP services such as GoDaddy and Gmail.

Community
  • 1
  • 1
CVertex
  • 17,997
  • 28
  • 94
  • 124
  • I tried to do this using similar methods in a different language. Encountered the same type of thing: Old documented methods that worked before, did not work for me. So you are left wondering if google changed something, or if you did something wrong. – AaronLS Apr 01 '09 at 08:49
  • 3
    @aaronls the only recent change seems to be related to the 465 port. I tried it while looking for a solution (I was just working on the same), and the 465 port timeouts all the time. If that's your case, try with the 587 port. – eglasius Apr 02 '09 at 00:46
  • 2
    This problem is due to "word verification" (captcha). If you sign in via web interface by hand and fill in captcha your SMTP will start working. – Robert Koritnik Oct 21 '09 at 16:45
  • @cvertex check out my answer re changing password to strong pass, worked for me and a few others, confirmed. Then please accept the answer if it worked for you. Thanks. – Erx_VB.NExT.Coder Sep 19 '11 at 18:43
  • 5
    FWIW, works for me. you need to use 587 and .EnableSSL true. c# 4/.NET 4 does not currently support alternate 465/SSL. gmail demands for [Configuring other mail clients](http://mail.google.com/support/bin/answer.py?answer=13287). – gerryLowry Dec 04 '11 at 19:29
  • I wanted to add for anyone reading this: If your application sends too many emails, Google will suspend it on suspicion of spam. Unfortunately, the error you will get on your application is the same as above. If you start getting this email for not apparent reason, check your gmail account (in my case, a Google App one) and see if it is suspended. – covo Sep 28 '12 at 04:08
  • 2
    Follow @eglasius answer and make sure you turn on the "Allow Less Secure Apps" setting in the Gmail to allow gmail to authenticate your account. – user2713706 Jan 07 '18 at 06:40
  • @eglasius Hello , I have a question, I want to send email from a sender email function , it works separately , but when send to user's email , its body is null. I want to know can I pass ViewBag to send email function with gmail? – hasti.au Sep 27 '22 at 14:17

31 Answers31

314

CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.

Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),
                EnableSsl = true
            };
            client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");
            Console.WriteLine("Sent");
            Console.ReadLine();
        }
    }
}

I also got it working using a combination of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx and code (because there is no matching EnableSsl in the configuration file :( ).

2021 Update

By default you will also need to enable access for "less secure apps" in your gmail settings page: google.com/settings/security/lesssecureapps. This is necessary if you are getting the exception "`The server response was: 5.5.1 Authentication Required. – thanks to @Ravendarksky

Revious
  • 7,816
  • 31
  • 98
  • 147
eglasius
  • 35,831
  • 5
  • 65
  • 110
  • 1
    Worked brilliantly for me in a C# winforms application. Thanks, Freddy. – Andrew Jun 15 '09 at 13:21
  • 14
    Just remember that code like this is effectively transmitting your gmail credentials in plain text to the user... – Chris Marisic Apr 19 '10 at 13:00
  • 3
    there actually is a matching setting for enableSsl in the web.config, see answer below – Wiebe Tijsma Sep 15 '10 at 12:07
  • 4
    @Zidad that was added in 4.0. – eglasius Sep 15 '10 at 12:23
  • 1
    I was getting the error mentioned in the question because somehow I enabled `defaultCredentials="true"` in my web.config file configuration. It should be `defaultCredentials="false"`. – Leniel Maccaferri Jul 26 '11 at 15:20
  • 1
    @eglasius, I used same code but every time Network Timeout exception is coming....`{"The operation has timed out."} System.Exception {System.Net.Mail.SmtpException}` – vinay Oct 19 '11 at 06:16
  • Code in the answer is still working. Very first thing, confirm the basics, the u/p in the UI, use the same from as the one used on the network credential Or one that is authorized to send in gmail, try a regular email client like outlook. All should confirm either some issue with the data Or one with the environment. Did you try to run it as a console program just like the code above? – eglasius Oct 20 '11 at 10:46
  • I still get the "not authenticated" exception! (And yes, my password is strong.) – Yehuda Shapira Feb 10 '12 at 11:48
  • @Jacob did you try Erx_VB Next.Coder answer? (trying changing your password first, to see if you get any issue reported that way) – eglasius Feb 10 '12 at 15:08
  • @eglasius I checked the strength of my password, and Gmail marks is as 'strong'. – Yehuda Shapira Feb 12 '12 at 08:05
  • @eglasius Great answer. How would this look like if you have two factor authentication enabled? – Stoyan Dimov Nov 25 '14 at 13:22
  • 28
    You may also need to enable access for "less secure apps" in your gmail settings page: https://www.google.com/settings/security/lesssecureapps. This is necessary if you are getting the exception "`The server response was: 5.5.1 Authentication Required. – Ravendarksky Jul 31 '15 at 11:38
  • @Ravendarksky I had 2 step verification added to my gmail account, so yea, this method works only if you generate app password from above link. – harrisunderwork Aug 06 '15 at 10:38
  • I just created new gmail and tried the email it worked in less than 5 min without any change, except credentials ofcourse – shareef Mar 08 '19 at 06:47
  • This is great! Just a few lines of code and easy to understand! Thanks!!! – Andrei Solero Jan 08 '21 at 11:48
  • 1
    Sadly gmail no longer allows "Less secure apps" as of this year – glitchwizard Jun 07 '22 at 17:11
  • Hello , I have a question, I want to send email from a sender email function , it works separately , but when send to user's email , its body is null. I want to know can I pass @viewBag to send email function with Gmail? – hasti.au Sep 27 '22 at 14:12
78

In addition to the other troubleshooting steps above, I would also like to add that if you have enabled two-factor authentication (also known as two-step verification) on your GMail account, you must generate an application-specific password and use that newly generated password to authenticate via SMTP.

To create one, visit: https://www.google.com/settings/ and choose Authorizing applications & sites to generate the password.

John Rasch
  • 62,489
  • 19
  • 106
  • 139
  • 2
    I didnt have 2-step verification enabled, and it didnt matter how secure I made the password, this was the only way I could fix my problem. I was able to use other gmail accounts without 2-step and weaker passwords with no issues... to use the account I really wanted to use I had to enable 2-step and use an application specific password. – Ian Robertson Nov 02 '14 at 11:42
  • 1
    Exactly what I'm doing, yet still the same error :-/ It's acting like my password isn't strong enough, but I'm using the app password which Gmail gave me!!! – Jerry Dodge Jan 30 '17 at 18:11
  • I don't see any such option, maybe share the link to that? – Web Developer Apr 27 '21 at 00:44
  • @WebDeveloper You must enable 2-step-verification first on your account. Then only you are allowed to create application-specific password. [Refer link](https://www.lifewire.com/get-a-password-to-access-gmail-by-pop-imap-2-1171882) – Himalaya Garg Jul 24 '22 at 08:24
76

THE FOLLOWING WILL ALMOST CERTAINLY BE THE ANSWER TO YOUR QUESTION IF ALL ELSE HAS FAILED:

I got the exact same error, it turns out Google's new password strength measuring algorithm has changed deeming my current password as too weak, and not telling me a thing about it (not even a message or warning)... How did I discover this? Well, I chose to change my password to see if it would help (tried everything else to no avail) and when I changed my password, it worked!

Then, for an experiment, I tried changing my password back to my previous password to see what would happen, and Gmail didn't actually allow me to do this, citing the reason "sorry we cannot allow you to save this change as your chosen password is too weak" and wouldn't let me go back to my old password. I figured from this that it was erroring out because either a) you need to change your password once every x amount of months or b). As I said before, their password strength algorithms changed and therefore the weak password I had was not accepted, even though they did not say anything about this when trying to login ANYWHERE! This (number 2) is the most likely scenario, as my weak password was about 4 months old, and it let me use it in Gmail.

It's pretty bad that they said nothing about this, but it makes sense. Because most hijacked emails are logged into using software outside of gmail, and I'm guessing you are required to have a stronger password if you want to use Gmail outside of the Gmail environment.

greybeard
  • 2,249
  • 8
  • 30
  • 66
Erx_VB.NExT.Coder
  • 4,838
  • 10
  • 56
  • 92
  • 3
    Thanks, as you say change the password so that it is strong and all will work fine. – Gavin Jul 14 '11 at 21:03
  • 2
    This was exactly my problem - all other suggestions was about config, but my config was correct from the beginning, but I kept on getting the error. Changing the password made all the difference, – André Vermeulen Aug 27 '11 at 15:26
  • 1
    Thanks, finally I was able to sort out this issue, My case was actually even more complicated, I was able to send emails from my dev machine (which is in Georgia, Caucasus), but emails were failing from production servers(UK) After changing password to complex one everything works now :) – Kirill Chilingarashvili Aug 17 '14 at 18:30
  • 1
    Thanks. I had the same problem of my gmail account which did not own a password strength. I updated it with strong one and my codes are working. – Thomas.Benz Oct 16 '15 at 20:54
  • 1
    Thanks, Yes finally it's just change the password to strong one. – Misha Beskin Jun 08 '16 at 06:26
  • 1
    Thank you. Changing my gmail password solved the problem. But the problem was not a more secure password, i just had to change it. Looks like that i have to do this every time i change my hosting. – Jo Smo Jul 09 '16 at 20:54
59

Turn On Access For Less Secure Apps and it will work for all no need to change password.

Link to Gmail Setting

enter image description here

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Suhail Mumtaz Awan
  • 3,295
  • 8
  • 43
  • 77
  • 1
    This worked for me. Even more, when I tried to send email the above way, I got actually email from Google where they explicitly say that they blocked this attempt from less secure app and they mentioned this way to fix it – Demarsch Mar 27 '17 at 20:40
  • 1
    This is most important key in the puzzle since I had every other setting set up and it seemed to be not working. As soon as I had this setting on, it just worked like a charm. – Lost Mar 12 '18 at 18:51
  • 1
    This worked for me. App Password + SSL + NetworkCredentials. (VB.NET) – CrazyIvan1974 Dec 17 '18 at 18:42
  • 3
    This setting is no longer available. [Learn more](https://support.google.com/accounts?p=less-secure-apps&hl=en) – Himalaya Garg Jul 24 '22 at 08:02
32

I've had some problems sending emails from my gmail account too, which were due to several of the aforementioned situations. Here's a summary of how I got it working, and keeping it flexible at the same time:

  • First of all setup your GMail account:
    • Enable IMAP and assert the right maximum number of messages (you can do so here)
    • Make sure your password is at least 7 characters and is strong (according to Google)
    • Make sure you don't have to enter a captcha code first. You can do so by sending a test email from your browser.
  • Make changes in web.config (or app.config, I haven't tried that yet but I assume it's just as easy to make it work in a windows application):
<configuration>
    <appSettings>
        <add key="EnableSSLOnMail" value="True"/>   
    </appSettings>

    <!-- other settings --> 

    ...

    <!-- system.net settings -->
    <system.net>
        <mailSettings>
            <smtp from="yourusername@gmail.com" deliveryMethod="Network">
                <network 
                    defaultCredentials="false" 
                    host="smtp.gmail.com" 
                    port="587" 
                    password="stR0ngPassW0rd" 
                    userName="yourusername@gmail.com"
                    />
                <!-- When using .Net 4.0 (or later) add attribute: enableSsl="true" and you're all set-->
            </smtp>
        </mailSettings>
    </system.net>
</configuration>
Add a Class to your project:

Imports System.Net.Mail

Public Class SSLMail

    Public Shared Sub SendMail(ByVal e As System.Web.UI.WebControls.MailMessageEventArgs)

        GetSmtpClient.Send(e.Message)

        'Since the message is sent here, set cancel=true so the original SmtpClient will not try to send the message too:
        e.Cancel = True

    End Sub

    Public Shared Sub SendMail(ByVal Msg As MailMessage)
        GetSmtpClient.Send(Msg)
    End Sub

    Public Shared Function GetSmtpClient() As SmtpClient

        Dim smtp As New Net.Mail.SmtpClient
        'Read EnableSSL setting from web.config
        smtp.EnableSsl = CBool(ConfigurationManager.AppSettings("EnableSSLOnMail"))
        Return smtp
    End Function

End Class

And now whenever you want to send emails all you need to do is call SSLMail.SendMail:

e.g. in a Page with a PasswordRecovery control:

Partial Class RecoverPassword
Inherits System.Web.UI.Page

Protected Sub RecoverPwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles RecoverPwd.SendingMail
    e.Message.Bcc.Add("webmaster@example.com")
    SSLMail.SendMail(e)
End Sub

End Class

Or anywhere in your code you can call:

SSLMail.SendMail(New system.Net.Mail.MailMessage("from@from.com","to@to.com", "Subject", "Body"})

I hope this helps anyone who runs into this post! (I used VB.NET but I think it's trivial to convert it to any .NET language.)

BNL
  • 7,085
  • 4
  • 27
  • 32
Sebas
  • 431
  • 4
  • 4
  • +1 "enableSsl="true" - this works for a legacy app which does not specifically set the Smtp.enableSsl property without recompiling the assemblies. Excellent tip! – Metro Smurf Apr 22 '17 at 18:33
  • and don't forget the firewall. Port 587 is not a usual port to open. – Guy Lowe Mar 21 '19 at 23:49
15

Oh...It's amazing... First I Couldn't send an email for any reasons. But after I changed the sequence of these two lines as below, it works perfectly.

//(1)
client.UseDefaultCredentials = true;
//(2)
client.Credentials = new System.Net.NetworkCredential("username@gmail.com", "password");
Web Developer
  • 333
  • 4
  • 17
Wirol
  • 151
  • 1
  • 2
  • 1
    Yes, the order makes the difference. Especially when you set the property Credentials and you don't want to use default credentials. – Stefan Cvetanovski Feb 08 '13 at 16:51
  • 1
    According to the documentation, to use Credentials you need to set UseDefaultCredentials = false. However these two setting seem to be secretly intertwined. If you set UseDefaultCredentials to true or false, it will have the side affect of setting Credentials to null. And it appears setting Credentials may side-effect set UseDefaultCredentials = false. Not documented as doing this though, could be bug or just a lame developer. – Aaron Jul 18 '15 at 01:32
13
Dim SMTPClientObj As New Net.Mail.SmtpClient
SMTPClientObj.UseDefaultCredentials = False
SMTPClientObj.Credentials = New System.Net.NetworkCredential("myusername@gmail.com", "mypwd")
SMTPClientObj.Host = "smtp.gmail.com"
SMTPClientObj.Port = 587
SMTPClientObj.EnableSsl = True
SMTPClientObj.Send("myusername@gmail.com","yourusername@gmail.com","test","testbody")

If you get 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. Learn more at" as I get before this, make sure the line SMTPClientObj.UseDefaultCredentials = False included and this line should before the SMTPClientObj.Credentials.

I did try to switch these 2 lines the opposite way and the 5.5.1 Authentication Required error returned.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Terry Chng
  • 131
  • 1
  • 2
  • This is exactly what happened to me. Who thought order of setting property would fix/break things! – Bill Yang Jan 24 '11 at 20:12
  • This was the issue for me too, I switched around the order as suggested and it works fine - headaches, ugh! – eth0 Mar 07 '11 at 10:02
12

The problem is not one of technical ability to send through gmail. That works for most situations. If you can't get a machine to send, it is usually due to the machine not having been authenticated with a human at the controls at least once.

The problem that most users face is that Google decides to change the outbound limits all the time. You should always add defensive code to your solution. If you start seeing errors, step off your send speed and just stop sending for a while. If you keep trying to send Google will sometimes add extra time to your delay period before you can send again.

What I have done in my current system is to send with a 1.5 second delay between each message. Then if I get any errors, stop for 5 minutes and then start again. This usually works and will allow you to send up to the limits of the account (last I checked it was 2,000 for premier customer logins per day).

Jason Short
  • 5,205
  • 1
  • 28
  • 45
  • 2
    This was the exactly my problem! When I deployed to Production, I got the issue and after I logged into Gmail on the server itself, it start working again. – ThisGuy Jun 16 '12 at 01:30
11

Simple steps to fix this:

1)Sign in to your Gmail

2)Navigate to this page https://www.google.com/settings/security/lesssecureapps & set to "Turn On"

Kevin
  • 2,296
  • 21
  • 22
11

I had the same problem, but it turned out to be my virus protection was blocking outgoing "spam" email. Turning this off allowed me to use port 587 to send SMTP email via GMail

user464329
  • 111
  • 1
  • 2
10

If nothing else has worked here for you you may need to allow access to your gmail account from third party applications. This was my problem. To allow access do the following:

  1. Sign in to your gmail account.
  2. Visit this page https://accounts.google.com/DisplayUnlockCaptcha and click on button to allow access.
  3. Visit this page https://www.google.com/settings/security/lesssecureapps and enable access for less secure apps.

This worked for me hope it works for someone else!

Celt
  • 2,469
  • 2
  • 26
  • 43
  • Why did you revert my edit? Stack Overflow tries to keep it's site clean by having a card in the bottom with your info, no-need to under-sign, or wish luck. **Thanks for your understanding!** – Web Developer Apr 29 '21 at 01:10
8

I'm not sure which .NET version is required for this because eglasius mentioned there is no matching enableSsl setting (I'm using .NET 4.0, but I suspect it to work in .NET 2.0 or later), but this configuration justed worked for me (and doesn't require you to use any programmatic configuration):

<system.net>
  <mailSettings>
    <smtp from="myusername@gmail.com" deliveryMethod="Network">
      <network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" port="587" password="password" userName="myusername@gmail.com"/>
    </smtp>
  </mailSettings>
</system.net>

You might have to enable POP or IMAP on your Gmail account first: https://mail.google.com/mail/?shva=1#settings/fwdandpop

I recommend trying it with a normal mail client first...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wiebe Tijsma
  • 10,173
  • 5
  • 52
  • 68
  • 2
    that's new to 4.0, compare versions at -> http://msdn.microsoft.com/en-us/library/ms164242(v=VS.90).aspx – eglasius Sep 15 '10 at 12:22
  • Hi Eglasius... OK thanks for that! Strange they only have the programmatic approach in the pre-4.0. I guess we all forget things now and then :) – Wiebe Tijsma Sep 20 '10 at 11:55
6

I was using corporate VPN connection. It was the reason why I couldn't send email from my application. It works if I disconnect from VPN.

Ned
  • 1,055
  • 9
  • 34
  • 58
5

I was getting the same error and none of the above solutions helped.

My problem was that I was running the code from a remote server, which had never been used to log into the gmail account.

I opened a browser on the remote server and logged into gmail from there. It asked a security question to verify it was me since this was a new location. After doing the security check I was able to authenticate through code.

Vlad Tamas
  • 180
  • 4
  • 9
5

Turn on less secure apps for your account: https://www.google.com/settings/security/lesssecureapps

Mustafa Burak Kalkan
  • 1,132
  • 21
  • 28
5
  1. First check your gmail account setting & turn On from "Access for less secure apps" enter image description here

We strongly recommend that you use a secure app, like Gmail, to access your account. All apps made by Google meet these security standards. Using a less secure app, on the other hand, could leave your account vulnerable. Learn more.

  1. Set

    smtp.UseDefaultCredentials = false;
    

    before

    smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
    
reza.cse08
  • 5,938
  • 48
  • 39
5

@Andres Pompiglio: Yes that's right you must change your password at least once.. this codes works just fine:

//Satrt Send Email Function
public string SendMail(string toList, string from, string ccList,
    string subject, string body)
{

    MailMessage message = new MailMessage();
    SmtpClient smtpClient = new SmtpClient();
    string msg = string.Empty;
    try
    {
        MailAddress fromAddress = new MailAddress(from);
        message.From = fromAddress;
        message.To.Add(toList);
        if (ccList != null && ccList != string.Empty)
            message.CC.Add(ccList);
        message.Subject = subject;
        message.IsBodyHtml = true;
        message.Body = body;
        // We use gmail as our smtp client
        smtpClient.Host = "smtp.gmail.com";   
        smtpClient.Port = 587;
        smtpClient.EnableSsl = true;
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new System.Net.NetworkCredential(
            "Your Gmail User Name", "Your Gmail Password");

        smtpClient.Send(message);
        msg = "Successful<BR>";
    }
    catch (Exception ex)
    {
        msg = ex.Message;
    }
    return msg;
}
//End Send Email Function

AND you can make a call to the function by using:

Response.Write(SendMail(recipient Address, "UserName@gmail.com", "ccList if any", "subject", "body"))
Michał Powaga
  • 22,561
  • 8
  • 51
  • 62
maxcoder
  • 79
  • 1
  • 4
  • 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 – Savas Adar Mar 04 '14 at 12:47
5

I also found that the account I used to log in was de-activated by google for some reason. Once I reset my password (to the same as it used to be), then I was able to send emails just fine. I was getting 5.5.1 message also.

RKL
  • 51
  • 1
  • 1
5

I had also try to many solution but make some changes it will work

host = smtp.gmail.com
port = 587
username = email@gmail.com
password = password
enabledssl = true

with smtpclient above parameters are work in gmail

Michał Powaga
  • 22,561
  • 8
  • 51
  • 62
Suresh
  • 51
  • 1
  • 1
4

Another thing that I've found is that you must change your password at least once. And try to use a secure level password (do not use the same user as password, 123456, etc.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
4

Yet another possible solution for you. I was having similar problems connecting to gmail via IMAP. After trying all the solutions that I came across that you will read about here and elsewhere on SO (eg. enable IMAP, enable less secure access to your mail, using https://accounts.google.com/b/0/displayunlockcaptcha and so on), I actually set up a new gmail account once more.

In my original test, the first gmail account I had created, I had connected to my main gmail account. This resulted in erratic behaviour where the wrong account was being referenced by google. For example, running https://accounts.google.com/b/0/displayunlockcaptcha opened up my main account rather than the one I had created for the purpose.

So when I created a new account and did not connect it to my main account, after following all the appropriate steps as above, I found that it worked fine!

I haven't yet confirmed this (ie. reproduced), but it apparently did it for me...hope it helps.

sinewave440hz
  • 1,265
  • 9
  • 22
4

I ran into this same 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" ) and found out that I was using the wrong password. I fixed the login credentials, and it sent correctly.

I know this is late, but maybe this will help someone else.

Albert Bori
  • 9,832
  • 10
  • 51
  • 78
4

One or more reasons are there for these error.

  • Log in with your Gmail( or any other if ) in your local system.

  • Also check for Less Secure App and Set it to "Turn On" here is the Link for GMAIL. https://www.google.com/settings/security/lesssecureapps

  • check for EnableSsl in your Email code, and also set it to true.

    smtp.EnableSsl = true;
    
  • Also check which port are you using currently. 25 is Global, but you can check it for others too like 587. check here. Does all SMTP communication happen over 25?

  • IF YOU ARE ON REMOTE : Check the answer of Vlad Tamas above.

Community
  • 1
  • 1
Bharat
  • 5,869
  • 4
  • 38
  • 58
  • what if i dont want to turn on the less secure app settings, how do other email clients do this why cant i do the same with c#? – user734028 Jan 17 '18 at 17:18
4

If you have 2-Step Verification step up on your Gmail account, you will need to generate an App password. https://support.google.com/accounts/answer/185833?p=app_passwords_sa&hl=en&visit_id=636903322072234863-1319515789&rd=1 Select How to generate an App password option and follow the steps provided. Copy and paste the generated App password somewhere as you will not be able to recover it after you click DONE.

Faith Nassiwa
  • 501
  • 5
  • 6
3

You can also connect via port 465, but due to some limitations of the System.Net.Mail namespace you may have to alter your code. This is because the namespace does not offer the ability to make implicit SSL connections. This is discussed at http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx, and I have supplied an example of how to use the CDO (Collaborative Data Object) in another discussion (GMail SMTP via C# .Net errors on all ports).

Community
  • 1
  • 1
Bryan Allred
  • 606
  • 4
  • 5
3

I had this problem resolved. Aparently that message is used in multiple error types. My problem was that i had reached my maximum of 500 sent mails.

log into the account and manually try to send a mail. If the limit has been reached it will inform you

Don P
  • 519
  • 6
  • 12
3

Google no longer allows "less secure apps", so this is not possible for normal Gmail users.

Changes by Google after May 2022.

For these changes, we have to do the following changes to our code.

  1. First go to Gmail account security.

  2. Enable two-factor authentication.

  3. Configure the App password in the google account.

  4. Use the App password in the application.

         MailMessage mail = new MailMessage();
         mail.To.Add(email.Text.ToString().Trim());
         mail.From = new MailAddress("your_Gmail_address");
         mail.Subject = "Hello test email";
         mail.Body = "<p>hello user<br/> How are you?</p>";
         mail.IsBodyHtml = true;
    
         SmtpClient smtp = new SmtpClient();
         smtp.Port = 587; // 25 465
         smtp.EnableSsl = true;
         smtp.UseDefaultCredentials = false;
         smtp.Host = "smtp.gmail.com";
         smtp.Credentials = new System.Net.NetworkCredential("your_Gmail_address", "Your_gmail_app_password");
         smtp.Send(mail);
    
1
smtp.Host = "smtp.gmail.com"; //host name
smtp.Port = 587; //port number
smtp.EnableSsl = true; //whether your smtp server requires SSL
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
A. Gladkiy
  • 3,134
  • 5
  • 38
  • 82
somesh
  • 3,508
  • 4
  • 16
  • 10
0

Change your gmail password and try again, it should work after that.

Don't know why, but every time you change your hosting you have to change your password.

Jo Smo
  • 6,923
  • 9
  • 47
  • 67
0

This code works for me, and also allows in gmail access from unsecure apps, and removing authentication in 2 steps:

Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(MailAddress, Password)
Rose8525
  • 109
  • 6
0

Google no longer allows "less secure apps", so this is not possible any longer for normal gmail users.

https://support.google.com/accounts/answer/6010255?hl=en#zippy=%2Cif-less-secure-app-access-is-on-for-your-account

From Google:

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.

Important: This deadline does not apply to Google Workspace or Google Cloud Identity customers. The enforcement date for these customers will be announced on the Workspace blog at a later date.

For more information, continue to read.

glitchwizard
  • 421
  • 1
  • 6
  • 23