Showing posts with label SMTP. Show all posts
Showing posts with label SMTP. Show all posts

Saturday, July 10, 2021

ASP.Net GMAIL SMTP Error: Failure sending email

GMAIL SMTP Error: Failure sending email

In this article I will explain how to resolve the error Failure sending email in ASP.Net.

Generally the Failure sending email error comes when debugged leads to the following error:

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

Thus this article will cover the common solutions which can resolve the issue.

Error

The following error occurs when you try to send email using Gmail credentials in your ASP.Net application.

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

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Mail.SmtpException: 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

Solutions

1. Incorrect Gmail Username and/or password

First you must check whether the Username and Password supplied are correct.

Though Gmail allows you to sign in with Username instead complete Email but when sending email through code you need to pass the complete Email address as Username.

2. SSL setting

Gmail uses secure channel for sending emails and you need to enable SSL security while sending emails through your application.

In .Net it can be enabled by setting EnableSsl setting of the SmtpClient to True. For more information please refer my article Sendemail using Gmail SMTP Mail Server in ASP.Net.

3. Less Secure Apps setting

If you are sure that your Username and Password are correct, but you still get errors then it means that Gmail has blocked your application.

And in such case you will receive an email similar to what is shown below.

ASP.Net GMAIL SMTP Error: Failure sending email
ASP.Net GMAIL SMTP Error: Failure sending email



Note: If you have not received email then use the following link.

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


Once you visit the link you need to modify the Less Secure Apps setting and Turn On access to Less Secure Apps as shown below.

4. Application Location

If the solutions #1, #2 and #3 are not working for you then it might be the issue with the location of the Application accessing the Gmail account.

Gmail makes sure that your account is not being accessed from some other Country or geographical location which is far from your routine location i.e. your city when you live and access Gmail daily.

Generally the servers are not present in the same country or city where we live in and hence when you host your website on such server and try to send email from your application you might receive error.

Thus to resolve it, you will need to open browser on the server and login into Gmail. This makes Gmail understand that the server and its IP Address belongs to you and it will allow you to send emails through your application.

GMAIL SMTP Server using C# and VB.Net

GMAIL SMTP Server using C# and VB.Net

In this article I will explain with an example, how to send email using GMAIL SMTP Server using C# and VB.Net.

App.Config AppSettings

Following are the SMTP settings which are saved inside the AppSettings section of the App.Config file.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <appSettings>

        <add key="Host" value="smtp.gmail.com"/>

        <add key="Port" value="587"/>

        <add key="SSL" value="true"/>

        <add key="FromEmail" value="sender@gmail.com"/>

        <add key="Username" value="sender@gmail.com"/>

        <add key="Password" value="password"/>

    </appSettings>

</configuration>

Namespaces 

You will need to import the following namespaces.

C#

using System.IO;

using System.Net;

using System.Net.Mail;

using System.Configuration;

 

VB.Net

Imports System.IO

Imports System.Net

Imports System.Net.Mail

Imports System.Configuration

Sending SMTP email using Console Application

When the Program is run, the values of Recipient email address (To), Subject and Body is read as input from the User.

While the Sender email address (from) is read from the FromEmail AppSettings key.

Then all these values are set into an object of the MailMessage class.

Then an object of SmtpClient class is created and the settings of the GMAIL SMTP server i.e. Host, Username, Password and Port are read from the respective AppSetting keys.

Note: It is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be equal to Gmail Username specified in credentials.

Finally the email is sent using the Send function of the SmtpClient class object.

MailMessage Class Properties

Following are the required properties of the MailMessage class.

From – Sender’s email address.

To – Recipient(s) Email Address.

CC – Carbon Copies (if any).

BCC – Blind Carbon Copies (if any).

Subject – Subject of the Email.

Body – Body of the Email.

IsBodyHtml – Specify whether body contains text or HTML mark up.

Attachments – Attachments (if any).

ReplyTo – ReplyTo Email address.

 

SmptClient Class Properties

Following are the properties of the SmtpClient class.

Host – SMTP Server URL (Gmail: smtp.gmail.com).

EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True).

UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.

Credentials – Valid login credentials for the SMTP server (Gmail: email address and password).

Port – Port Number of the SMTP server (Gmail: 587)

C#

namespace Send_Email_Console_CS

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Enter To Address:");

            string to = Console.ReadLine().Trim();

 

            Console.WriteLine("Enter Subject:");

            string subject = Console.ReadLine().Trim();

 

            Console.WriteLine("Enter Body:");

            string body = Console.ReadLine().Trim();

 

            using (MailMessage mm = new MailMessage(ConfigurationManager.AppSettings["FromEmail"], to))

            {

                mm.Subject = subject;

                mm.Body = body;

                mm.IsBodyHtml = false;

                SmtpClient smtp = new SmtpClient();

                smtp.Host = ConfigurationManager.AppSettings["Host"];

                smtp.EnableSsl = true;

                NetworkCredential NetworkCred = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]);

                smtp.UseDefaultCredentials = true;

                smtp.Credentials = NetworkCred;

                smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);

                Console.WriteLine("Sending Email......");

                smtp.Send(mm);

                Console.WriteLine("Email Sent.");

                System.Threading.Thread.Sleep(3000);

                Environment.Exit(0);

            }

        }

    }

}

 

VB.Net

Module Module1

    Sub Main()

        Console.WriteLine("Enter To Address:")

        Dim [to] As String = Console.ReadLine().Trim()

 

        Console.WriteLine("Enter Subject:")

        Dim subject As String = Console.ReadLine().Trim()

 

        Console.WriteLine("Enter Body:")

        Dim body As String = Console.ReadLine().Trim()

 

        Using mm As New MailMessage(ConfigurationManager.AppSettings("FromEmail"), [to])

            mm.Subject = subject

            mm.Body = body

            mm.IsBodyHtml = False

            Dim smtp As New SmtpClient()

            smtp.Host = ConfigurationManager.AppSettings("Host")

            smtp.EnableSsl = True

            Dim NetworkCred As New NetworkCredential(ConfigurationManager.AppSettings("Username"), ConfigurationManager.AppSettings("Password"))

            smtp.UseDefaultCredentials = True

            smtp.Credentials = NetworkCred

            smtp.Port = Integer.Parse(ConfigurationManager.AppSettings("Port"))

            Console.WriteLine("Sending Email......")

            smtp.Send(mm)

            Console.WriteLine("Email Sent.")

            System.Threading.Thread.Sleep(3000)

            Environment.Exit(0)

        End Using

    End Sub

End Module

DotNet Latest Technologies

  I'm not sure exactly what you are looking for or how "recent" the technologies that you might wan to look into are, but I...