Sending email via On-Prem Exchange fails from IIS machine.

Michael Mastro II 51 Reputation points
2022-06-23T20:33:55.093+00:00

Good afternoon,

I am trying to send an email from an Api during certain actions. While I am working from the Development machine the emails are getting sent. When the code is sent to the Staging IIS server, the emails fail to get sent and produce a 500 error.

When I look at the Event Viewer on the IIS Server I see an error as such:

Connection ID "18230571306091282443", Request ID "80000015-0003-fd00-b63f-84710c7967bb": An unhandled exception was thrown by the application.  
  
Exception:  
Microsoft.Exchange.WebServices.Data.AutodiscoverLocalException: The Autodiscover service couldn't be located.  
   at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.InternalGetLegacyUserSettings[TSettings](String emailAddress, List`1 redirectionEmailAddresses, Int32& currentHop)  
   at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.GetLegacyUserSettings[TSettings](String emailAddress)  
   at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.InternalGetLegacyUserSettings(String emailAddress, List`1 requestedSettings)  
   at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.GetUserSettings(String userSmtpAddress, UserSettingName[] userSettingNames)  
   at Microsoft.Exchange.WebServices.Data.ExchangeService.GetAutodiscoverUrl(String emailAddress, ExchangeVersion requestedServerVersion, AutodiscoverRedirectionUrlValidationCallback validateRedirectionUrlCallback)  
   at Microsoft.Exchange.WebServices.Data.ExchangeService.AutodiscoverUrl(String emailAddress, AutodiscoverRedirectionUrlValidationCallback validateRedirectionUrlCallback)  
   at IdentityApi.EmailLibrary.Helpers.EmailConfigHelper.GetEmailServiceType() in C:\agent\_work\5\s\IdentityApi\IdentityApi.EmailLibrary\Helpers\EmailConfigHelper.cs:line 34  
   at IdentityApi.EmailLibrary.Services.EmailSender.ServiceType() in C:\agent\_work\5\s\IdentityApi\IdentityApi.EmailLibrary\Services\EmailSender.cs:line 35  
   at IdentityApi.EmailLibrary.Services.EmailSender.SendApproval(BaseEmailMessage message) in C:\agent\_work\5\s\IdentityApi\IdentityApi.EmailLibrary\Services\EmailSender.cs:line 79  
   at IdentityApi.WebApi.Controllers.UsersController.UpdateUserStatusesByIdAsync(EditUserStatusInputModel inputModel) in C:\agent\_work\5\s\IdentityApi\IdentityApi.WebApi\Controllers\UsersController.cs:line 456  
   at lambda_method(Closure , Object )  
   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)  
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)  
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)  
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)  
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)  
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)  
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)  
   at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()  

Even though I have TraceEnabled and TraceFlag.All set the trace never gets generated.

Here is my SendEmail code:

public virtual void SendEmail(BaseEmailMessage message)  
    {  
        var service = ServiceType();  
  
        if (service == "Exchange")  
        {  
            ExchangeMessage exchangeMessage = new(message.MailTo, message.Subject, message.Content);  
  
            var emailMessage = CreateExchangeEmailMessage(exchangeMessage);  
  
            emailMessage.SendAndSaveCopy();  
        }  
        else  
        {  
            SmtpMessage smtpMessage = new(message.MailTo, message.Subject, message.Content);  
  
            var emailMessage = CreateSmtpEmailMessage(smtpMessage);  
  
            Send(emailMessage);  
        }  
    }  
  
private EmailMessage CreateExchangeEmailMessage(ExchangeMessage message)  
    {  
        var emailConfiguration = _emailConfigHelper.GetEmailConfiguration();  
        //Get the user sending the email    
        var user = emailConfiguration[0].From;  
        var password = emailConfiguration[2].Password;  
        var domain = emailConfiguration[3].Domain;  
        var traceEnabled = emailConfiguration[7].ExchangeTraceEnabled;  
          
  
        //Initiate the service for Exchange  
        var service = new ExchangeService(ExchangeVersion.Exchange2016)  
        {  
            Credentials = new NetworkCredential(user, password, domain),  
            UseDefaultCredentials = true,  
            TraceListener = new ExchangeTraceListener(),  
            TraceEnabled = traceEnabled,  
            TraceFlags = TraceFlags.All  
        };  
  
        //Pass in the user that is sending  
        service.AutodiscoverUrl(user, URLRedirection.RedirectionUrlValidationCallBack);  
  
        Folder.Bind(service, WellKnownFolderName.SentItems);  
  
        //Create a new EmailMessage to send using the service  
        var emailMessage = new EmailMessage(service)  
        {  
            From = new EmailAddress  
            {  
                Address = user  
            }  
        };  
        emailMessage.ToRecipients.AddRange(message.MailTo);  
        emailMessage.Subject = message.Subject;  
        emailMessage.Body = new TextBody() { Text = message.Content };  
  
        //Pass the message back to where it is called from  
        return emailMessage;  
    }  

for my user variable I have: "no-reply@MRM2Inc.com", for Domain I have "MRM2INC", and lastly TraceEnabled is true in the appsettings.json.

I can ping the "autodiscover.mrm2inc.com" from the IIS server.

Not sure why the IIS server cannot send an email, Does anyone have any thoughts?

Internet Information Services
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,134 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Mastro II 51 Reputation points
    2022-06-28T02:55:39.39+00:00

    Even though I could not get the TraceLogs to write to disk, I was able to finally determine the cause. It was due to the appsettings.json have quotes around a bool value. They are not in there on the file in source, but during the publish to IIS all the bool values in the file got converted to a string. Now they were not in the substitution variable values for the release, but were being converted. I edited the appsettings.json, restarted IIS twice, and restarted the sites twice. Emails were then being sent. I then reconfigured the release tasks and variables, and this time it did not publish the appsettings.json with quotes around the bool values.