3

Below is the code I'm using. Please advise on how this can be rectified.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Net.Mail;

public partial class mailtest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void SendEmail(object sender, EventArgs e)
{
    lblmsg.Text = "";
    try
    {
        using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
        {
            mm.Subject = txtSubject.Text;
            mm.Body = txtBody.Text;
            //if (fuAttachment.HasFile)
            //{
            //    string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
            //    mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
            //}
            mm.IsBodyHtml = false;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = txtsmtphost.Text.Trim();
            smtp.EnableSsl = false;
            if (chkssl.Checked == true)
            {
                smtp.EnableSsl = true;
            }
            NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = int.Parse(txtport.Text);
            smtp.Send(mm);
            lblmsg.ForeColor = System.Drawing.Color.DarkGreen;
            lblmsg.Text = "Email sent successfuly !!";
            //ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent successfuly !!');", true);
        }
    }
    catch (Exception ex)
    {
        lblmsg.ForeColor = System.Drawing.Color.Red;
        lblmsg.Text = "Failed " + ex.ToString();
        ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Failed');", true);
    }
}}

The error message is:

System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required. Learn more at at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message)

Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38

3 Answers3

15

Since this question keeps coming up as the first on Google, what today worked for me (11 June 2022) is what I will share. This question has been asked many times in similar way and many different things have worked for many people, but that stops now, there are no work around in "code" anymore (assuming your code is perfect but throwing exception as written in the title above)! Why because Google made a change (from https://support.google.com/accounts/answer/6010255):

Less secure apps & your Google Account: 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.

Now what do you do, its simpler then you think, go to https://myaccount.google.com/, Click "Security", enable Two-step Verification, once done, come back to the myaccount Security page, you will see "App passwords", open that, it will give you options for what you are trying to make a password for (a bunch of devices), select "Windows Computer", make a password, copy it, use this password in the NetworkCredential class object in your code, and your emails should start working again through Code.

This wasted so much of my hours yesterday, my Winforms app was working perfect till a couple days back it stopped sending emails.

user734028
  • 1,021
  • 1
  • 9
  • 21
  • As at current date,, this is the appropriate answer. – albertdadze Feb 17 '23 at 14:02
  • 1
    This was the correct answer as of April 2023. Note however, the "App passwords" was found UNDER the 2-step verification page/section when I did it. – ptownbro Apr 15 '23 at 20:12
  • 1
    @ptownbro, I have the same problem when I follow the steps above, but I figured it out where you can get the `App passwords` now. You can find it inside of `2-Step Verification` page, just scrolling down to the bottom :-) Hope it answers your question – CF7 Aug 20 '23 at 03:18
6

The SMTP server requires a secure connection or the client was not authenticated.

To fix this error Go to your google account and generate an apps password

When running your code use the password generated instead of the actual users password.

This happens most often when the account has 2fa enabled.

Example with SmtpClient

using System;
using System.Net;
using System.Net.Mail;

namespace GmailSmtpConsoleApp
{
    class Program
    {
        private const string To = "test@test.com";
        private const string From = "test@test.com";
        
        private const string GoogleAppPassword = "XXXXXXXX";
        
        private const string Subject = "Test email";
        private const string Body = "<h1>Hello</h1>";
        
        
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            
            var smtpClient = new SmtpClient("smtp.gmail.com")
            {
                Port = 587,
                Credentials = new NetworkCredential(From , GoogleAppPassword),
                EnableSsl = true,
            };
            var mailMessage = new MailMessage
            {
                From = new MailAddress(From),
                Subject = Subject,
                Body = Body,
                IsBodyHtml = true,
            };
            mailMessage.To.Add(To);

            smtpClient.Send(mailMessage);
        }
    }
}
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
2

You should enable the less secure app settings on the Gmail account you are using to send emails. You can use this Link to enable the settings.

More information about your problem here.

Andrei Solero
  • 802
  • 1
  • 4
  • 12
  • it's work. But why the "Allow less secure apps" became OFF automatically. I had set it to ON but now it became OFF, why it's happening? – SAGAR SAHA Feb 02 '22 at 16:56
  • because google is saying dont use it, use the 2FA and then generate app passwords as I explained in my post – user734028 Jun 11 '22 at 07:19