Blog from Saravanan Arumugam

Let us talk about Technologies

Tag Archives: SMTP

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated


When I tried to send an email from .Net code, I got the following exception.

Exception

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated

Solution

This was because the mail was sent from the office network. By default the credentials in the SmtpClient object is null. The issue was resolved by setting SmtpClient.UseDefaultCredentials to true.

mailClient.UseDefaultCredentials = true;
Advertisements

Sending a simple mail from .Net code


Sending mails from .net code is very easy. System.Net.Mail namespace provides classes that support mail.

At a high level, there are only two things we need to do.

  1. Construct a MailMessage object.
  2. Use a SMTPClient object to send the MailMessage object constructed in the previous step.

 

Following are the steps to send a simple mail.

Step 1: Create a MailMessage object

Create a MailMessage object.

MailMessage message = new MailMessage();

 

Step 2: Specify the from and to addresses

From and To addresses can be specified in the constructor itself. If not done in constructor, it can be done at a later point using the MailMessage.From and MailMessage.To properties.

 

Step 3: Specify Subject

Subject can also be specified through the constructor. If not done in constructor, assign a subject string to MailMessage.Subject property.

 

Step 4: Create the body/content

The body of the mail should be a string. This could be a plain text or an HTML. By default the plain text is assumed to be the type of the body content.

If you create the body using html, set MailMessage.IsBodyHtml property to true.

 

Step 5: Create SmtpClient object and use the Send method

Create the mail client and specify the SMTP host for it. Set the SmtpClient.UseDefaultCredentials to true.

Then use the SmtpClient.Send() method to send the MailMessage object we built in the previous steps.

 

Code snippet to send a sample mail

private static void Main(string[] args)
{
    MailMessage message = new MailMessage(@"saravanandss@gmail.com",
        @"saravanandss@gmail.com");
    message.Subject = "Check SMTP Mail";
    message.Body = @"<html><body><h4>Sample mail body.</h4></body></html>";
    message.IsBodyHtml = true;
    using (SmtpClient mailClient = new SmtpClient())
    {
        mailClient.Host = @"smtp.mysite.com";
        mailClient.UseDefaultCredentials = true;
        mailClient.Send(message);
    }
}