-1

I am getting a System.ObjectDisposedException when i try to send an e-mail in a .NET core 6.0 project using the fluent-email library:

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Mail.SmtpClient'.
   at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken)
   at FluentEmail.Smtp.SendMailEx.SendMailExImplAsync(SmtpClient client, MailMessage message, CancellationToken token)

I have tried to inject the smtpclient transient, scoped and as a singleton but neither one of the options fixed this issue.

DI code:

  var smtpClient = new SmtpClient(smtpSenderOptions.Host, smtpSenderOptions.Port)
                {
                    EnableSsl = smtpSenderOptions.EnableSsl
                };

                services.AddSingleton(instance => smtpClient);

Usage (from the fluent-email library (https://github.com/lukencode/FluentEmail)):

    
    // Taken from https://stackoverflow.com/questions/28333396/smtpclient-sendmailasync-causes-deadlock-when-throwing-a-specific-exception/28445791#28445791
    // SmtpClient causes deadlock when throwing exceptions. This fixes that.
    public static class SendMailEx
    {
        public static Task SendMailExAsync(
            this SmtpClient @this,
            MailMessage message,
            CancellationToken token = default(CancellationToken))
        {
            // use Task.Run to negate SynchronizationContext
            return Task.Run(() => SendMailExImplAsync(@this, message, token));
        }

        private static async Task SendMailExImplAsync(
            SmtpClient client,
            MailMessage message,
            CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            var tcs = new TaskCompletionSource<bool>();
            SendCompletedEventHandler handler = null;
            Action unsubscribe = () => client.SendCompleted -= handler;

            handler = async (_, e) =>
            {
                unsubscribe();

                // a hack to complete the handler asynchronously
                await Task.Yield();

                if (e.UserState != tcs)
                    tcs.TrySetException(new InvalidOperationException("Unexpected UserState"));
                else if (e.Cancelled)
                    tcs.TrySetCanceled();
                else if (e.Error != null)
                    tcs.TrySetException(e.Error);
                else
                    tcs.TrySetResult(true);
            };

            client.SendCompleted += handler;
            try
            {
                client.SendAsync(message, tcs);
                using (token.Register(() =>
                {
                    client.SendAsyncCancel();
                }, useSynchronizationContext: false))
                {
                    await tcs.Task;
                }
            }
            finally
            {
                unsubscribe();
            }
        }
    }

My code calling the library:

  var response = await _fluentEmail
                .Subject(emailContents.Subject)
                .To(emailContents.To)
                .Attach(attachments)
                .UsingTemplate(template, emailContents)
                .SendAsync(cancellationToken);
  • You need to include the code of _how_ you're using it. – Martin Costello May 25 '22 at 13:51
  • Since most of the magic is happening inside the fluentemail project I guess I might have done something wrong with all the async stuff. – Wilko van der Veen May 25 '22 at 13:59
  • Looks like you have two clients. The you need to also call constructor for client before each message. You cannot reuse the client. – jdweng May 25 '22 at 14:01
  • ASP.NET Core does not use a synchronization context, the SMTPClient won't deadlock, that implementation is not needed. – Camilo Terevinto May 25 '22 at 14:31
  • 2
    `I have tried to inject the smtpclient transient, scoped and as a singleton but neither one of the options fixed this issue.` => well, of course not, you are always returning the same instance, once it's disposed it cannot be used any longer. – Camilo Terevinto May 25 '22 at 14:33
  • Don't shoot the messenger. I have copied the 'deadlock fix' from the github repo (i will add reference) – Wilko van der Veen May 25 '22 at 14:59

1 Answers1

0

The extensions provided by fluent-email did inject these classes as singleton and I did use another lifetime and therefore this issue occured.

So I forgot to also override the dependency injection container configuration for all dependencies using the System.ObjectDisposedException to use singleton, since I was using a custom implementation of FluentEmail.Smtp.SendMailEx.SendMailExImplAsync.

After overridding the other dependencies in the DI extension, it worked.