close
Microsoft-Clouds-Pixels-Reuse-696×464

I recently signed up for a office 365 account for my domain. I tried to create a simple C# application that sends emails via SMTP. I was getting the following error “The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [CH2PR18CA0002.namprd18.prod.outlook.com]”. This error also prevented me from setting up database mail in SQL Server. I followed the Microsoft documentation and tried the direct SMTP Auth, direct send, and Office 365 SMTP relay methods. After a ton of Googling and wasting more time then I am willing to admit I finally landed on a solution that worked for me.

 

The Problem

Sending emails via SMTP is considered less secure. It does make sense that email providers like Microsoft and Google have security measures put in place so it does not get abused. However, there are some cases where you may still want to send emails via SMTP. For example, setting up SQL server database mail. Google allows you to enable “less secure applications” to bypass the SMTP restrictions on a account. Microsoft’s setting was a little more buried.

 

The Solution

I used PoweShell to turn on SMTP authorization for my organization within Microsoft. The documentation stated you could turn it on for an individual account using the following command “Set-CASMailbox -Identity {AccountName} -SmtpClientAuthenticationDisabled $false”. I could not get the command to work on an individual account level and was happy just enabling SMTP authorization for my organization.

1. Open up PowerShell ISE as a admin.

2. run the following command, and press yes to any prompts that appear.

Set-ExecutionPolicy RemoteSigned

3. run the following command, and enter your exchange account username and password when the prompt appears.

$UserCredential = Get-Credential

4. run the following command

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking

Get-TransportConfig | Format-List SmtpClientAuthenticationDisabled 

Set-TransportConfig -SmtpClientAuthenticationDisabled $false 

Get-TransportConfig | Format-List SmtpClientAuthenticationDisabled

5. Your PowerShell output should show the Smtp client authentication was disabled, and is now enabled.

SmtpClientAuthenticationDisabled : True

SmtpClientAuthenticationDisabled : False

6. Now retry sending your SMTP message.

 

Alternate Solution

If you do not want to enable SMTP authorization, I did find a solution for C#. This method will only work for your custom code and will not work for other apps such as SQL Server database mail.

1. In Visual Studio, open your NuGet package manger for your solution.

2. Install Microsoft.Exchange.WebServices. At the time of this post the version was 2.2.0.

3. Add the following code to your application

using Microsoft.Exchange.WebServices.Data;
public void SendFromNoReply(Email email)
{
     ExchangeService myservice = new ExchangeService(ExchangeVersion.Exchange2010_SP1)
     {
          Credentials = new WebCredentials(configuration["NoReplyAccount:Username"], configuration["NoReplyAccount:Password"]),
          Url = new Uri(configuration["NoReplyAccount:ExchangeUrl"])
     };
     EmailMessage emailMessage = new EmailMessage(myservice)
     {
          Subject = email.Subject,
          Body = email.Body
     };
     email.Recipients.ForEach(r =>
     {
          emailMessage.ToRecipients.Add(r);
     });
     foreach (KeyValuePair<string, byte[]> attachment in email.Attachments)
     {
          emailMessage.Attachments.AddFileAttachment(attachment.Key, attachment.Value);
     }
     emailMessage.Send();
}
public class Email
{
     public Email()
     {
          Recipients = new List<string>();
          Attachments = new Dictionary<string, byte[]>();
     }
     public Email(string subject, string body, string recipient)
     {
          Subject = subject;
          Body = body;
          Recipients = new List<string> { recipient };
          Attachments = new Dictionary<string, byte[]>();
     }
     public List<string> Recipients { get; set; }
     public Dictionary<string, byte[]> Attachments { get; set; }
     public string Subject { get; set; }
     public string Body { get; set; }
     public bool IsBodyHtml { get; set; } = true;
     public EmailSender EmailSender { get; set; }
     public override string ToString()
     {
          return $"Subject: {Subject}, Body: {Body}, IsBodyHtml: {IsBodyHtml}, Recipients: ({string.Join(",", Recipients)}) ";

Source Teckstack
Chioma Ugochukwu

The author Chioma Ugochukwu

Leave a Response