locked
SendEmailAsync Error ASP.NET MVC (C#) RRS feed

  • Question

  • User-1901014284 posted

    Hi,

    I have the below code to send an email using asp.net MVC (C#) but I am receiving the error message:

    "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 [DB6P195CA0015.EURP195.PROD.OUTLOOK.COM]"

    and is thrown on line 41 of my code below :

    Line 39:             {
    Line 40: 
    Line 41:                 throw ex;
    Line 42:             }
    Line 43:         }

    I have searched online but all seems to be pointing to my email and password details making sure these are correct but I have double checked and all are correct. Any help would be greatly appreciated.

    public async static Task SendEmailAsync(string email, string subject, string message)
    {
    try
    {
    var _email = "myemailaddress";
    var _epass = ConfigurationManager.AppSettings["mypassword"];
    var _dispName = "Jonny";
    MailMessage myMessage = new MailMessage();
    myMessage.To.Add(email);
    myMessage.From = new MailAddress(_email, _dispName);
    myMessage.Subject = subject;
    myMessage.Body = message;
    myMessage.IsBodyHtml = true;

    using (SmtpClient smtp = new SmtpClient())
    {
    smtp.EnableSsl = true;
    smtp.Host = "smtp.office365.com";
    smtp.Port = 587;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential(_email, _epass);
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.SendCompleted += (s, e) => { smtp.Dispose(); };
    await smtp.SendMailAsync(myMessage);
    }
    }
    catch (Exception ex)
    {

    throw ex;
    }

    Please see below the full stack trace of the error:

    [SmtpException: 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 [DB6P195CA0015.EURP195.PROD.OUTLOOK.COM]]
       Training.Models.<SendEmailAsync>d__0.MoveNext() in C:\Users\Administrator\source\repos\Training\Training\Models\MessageServices.cs:41
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
       System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26
       Training.Controllers.<Register>d__19.MoveNext() in C:\Users\Administrator\source\repos\Training\Training\Controllers\AccountController.cs:195
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
       System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
       System.Web.Mvc.Async.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__1(IAsyncResult asyncResult) +17
       System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
       System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
       System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
       System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
       System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
       System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
       System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
       System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
       System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
       System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
       System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
       System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
       System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
       System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) +152
       System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +125
    Wednesday, March 20, 2019 11:51 AM

Answers

  • User-943250815 posted

    @jonnygareth30
    Looking close on your code, seems you have to review UserName in NetworkCredential, usually UserName = EmailAddress.

    var _email = "myemail@mydomain.com";  // <-- Use email address
    var _epass = ConfigurationManager.AppSettings["pass"];
    smtp.Credentials = new NetworkCredential(_email, _epass);
    myMessage.From = new MailAddress(_email, _dispName); // <-- with correct value in "_email", From field will be correct

    I think this fixes any possible wrong Credentials.
    @Yuki Tao, thanks for info and give a clue, but I don´t think he/she want work with Shared Mailbox

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 21, 2019 4:04 PM

All replies

  • User-943250815 posted

    The SMTP server requires a secure connection

    Office365 uses TLS12, you have to enable it before send.
    This line add TLS11 and TLS12 to existing SecurityProtocol. System.Net.ServicePointManager.SecurityProtocol is global, once defined it will be available application wide

        System.Net.ServicePointManager.System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
    

    Wednesday, March 20, 2019 12:13 PM
  • User-1901014284 posted

    Hi  jzero,

    Thank you very much for your response and apologies if this is a stupid question but does the below line of code need to be added to the Global.asax.cs page?

     System.Net.ServicePointManager.System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
    Wednesday, March 20, 2019 12:46 PM
  • User-943250815 posted

    Global.asax is the best place to have it, but is not necessary it can be right on your SendMail routine.
    Just remember that one time set, doesn't matter where, it applies to all app

    Wednesday, March 20, 2019 1:06 PM
  • User-1901014284 posted

    Thank you very much again jzero, unfortunately I have an error on the below line (I have made bold and red the text "System" that the error occurs"):

    "System.Net.ServicePointManager.System.Net.ServicePointManager.SecurityProtocol"

    with the below error message:

    Severity Code Description Project File Line Suppression State
    Error CS0117 'ServicePointManager' does not contain a definition for 'System' Training C:\Users\Administrator\source\repos\Training\Training\Models\MessageServices.cs 15 Active

    Please accept my apologies for the questions.

    Many thanks

    Jonny

    Wednesday, March 20, 2019 2:38 PM
  • User-943250815 posted

    Oops my bad, for some reason I duplicated "System.Net.ServicePointManager"....

    System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

    Wednesday, March 20, 2019 2:43 PM
  • User-1901014284 posted

    Thank you very much again for your help jzero but i am still getting the below error message:

    "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 [DB7PR04CA0016.eurprd04.prod.outlook.com]"

    and this is how I have implemented within my code, have made a mistake? I have tried running with the TLS line of code inbetween the Try also. Please see below code:

    using System;
    using System.Configuration;
    using System.Net;
    using System.Net.Mail;
    using System.Threading.Tasks;

    namespace Training.Models
    {
    class MessageServices
    {
    public async static Task SendEmailAsync(string email, string subject, string message)
    {
    System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

    try
    {
    var _email = "myemail";
    var _epass = ConfigurationManager.AppSettings["pass"];
    var _dispName = "Jonny";
    MailMessage myMessage = new MailMessage();
    myMessage.To.Add(email);
    myMessage.From = new MailAddress(_email, _dispName);
    myMessage.Subject = subject;
    myMessage.Body = message;
    myMessage.IsBodyHtml = true;

    using (SmtpClient smtp = new SmtpClient())
    {
    smtp.EnableSsl = true;
    smtp.Host = "smtp.office365.com";
    smtp.Port = 587;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential(_email, _epass);
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.SendCompleted += (s, e) => { smtp.Dispose(); };
    await smtp.SendMailAsync(myMessage);
    }
    }
    catch (Exception ex)
    {

    throw ex;
    }
    }

    }
    }

    Wednesday, March 20, 2019 4:22 PM
  • User-943250815 posted

    OK, let's see if your issue now is related to Certificate validation.
    AS A TEST ONLY, add this right after Systen.Net.ServicePointManager line, it will bypass Server Certificate validation.
    Like any browser .NET check certificates
    Usually I get messages on Office365, and have to use such bypass, but I use Mailkit, so the exception is applied only when I need, code bellow is application wide

    ServicePointManager.ServerCertificateValidationCallback =
                delegate (
                    object s,
                    X509Certificate certificate,
                    X509Chain chain,
                    SslPolicyErrors sslPolicyErrors
                ) {
                    return true;
                };

    Wednesday, March 20, 2019 5:22 PM
  • User1520731567 posted

    Hi jonnygareth30,

    "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 [DB7PR04CA0016.eurprd04.prod.outlook.com]"

    According to your error message,

    your application does not support SMTP client submission to send email using shared mailbox credential since your application must logon to a mailbox to send a message. 

    For your reference see Error: Client was not authenticated to send anonymous mail during MAIL FROM

    or 

    smtp.Host = "smtp.office365.com";
    smtp.Port = 587;

    make sure that port 587 is allowed in your firewall settings and tls is enabled,

    you could refer to this link:

    https://answers.microsoft.com/en-us/msoffice/forum/all/exception-the-smtp-server-requires-a-secure/147c1a80-315c-4c13-95ff-d813b7715524

    Best Regards.

    Yuki Tao

    Thursday, March 21, 2019 9:19 AM
  • User-943250815 posted

    @jonnygareth30
    Looking close on your code, seems you have to review UserName in NetworkCredential, usually UserName = EmailAddress.

    var _email = "myemail@mydomain.com";  // <-- Use email address
    var _epass = ConfigurationManager.AppSettings["pass"];
    smtp.Credentials = new NetworkCredential(_email, _epass);
    myMessage.From = new MailAddress(_email, _dispName); // <-- with correct value in "_email", From field will be correct

    I think this fixes any possible wrong Credentials.
    @Yuki Tao, thanks for info and give a clue, but I don´t think he/she want work with Shared Mailbox

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 21, 2019 4:04 PM
  • User-1901014284 posted

    Thank you all again for your responses.

    You are right i do not want to work with Shared Mailboxes but having reviewed as you have mentioned. I have also followed/checked the above steps and I am still receiving the same issue.

    The email address iI am using is an Office 365 account, would this cause any issues in what I am trying to do?

    Many thanks

    Jonny

    Friday, March 29, 2019 1:20 PM
  • User-943250815 posted

    All fundamental definitions seems fine for sending mail over SMTP. It was supposed to work unless there are specific rules applied by Office365 that should be reviewed as GMail or HotMail actually have.
    Basically an SMTPs are set to not allow Relay Messages, it allow only Authenticated Users send messages, which I think you doing it right, be sure using correct user ID for authentication.
    But back to specific rules, I found "Office 365 Anti-Spam IP Delist Portal" at https://sender.office.com/
    Also check if there is a 2 Factor authentication, and remove, it should be like GMail "Allow Unsecure App"

    Check this thread, they are dealing with same problem
    https://stackoverflow.com/questions/30342884/5-7-57-smtp-client-was-not-authenticated-to-send-anonymous-mail-during-mail-fr

    Friday, March 29, 2019 2:36 PM
  • User-1901014284 posted

    Thank you very much for all your help. Seemed to be getting no where so I started a new project in VB and run the code which worked with no issues!

    Thanks again, greatly appreciate your help.

    Kind regards

    Jonny

    Monday, April 1, 2019 3:19 PM