Recently, I upgraded one of our web applications from .NET 3.5 to 4 and surprisingly I started to get some weird errors whenever the application tried to send emails.

If you suddenly get errors like this one and recently upgraded your application to .NET 4 surely it will be caused by the same error:

Failure sending mail.

Inner Exception:
Index was outside the bounds of the array.

EXCEPTION TYPE: IndexOutOfRangeException
at System.Net.Base64Stream.EncodeBytes(Byte[] buffer, Int32 offset, Int32 count, Boolean dontDeferFinalBytes, Boolean shouldAppendSpaceToCRLF)
at System.Net.Base64Stream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Mime.MimePart.Send(BaseWriter writer)
at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer)
at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelop
Stak Trace: at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Web_Utilities.Utils.Mail.SendMail(MailMessage mail)
at System.Net.Base64Stream.EncodeBytes(Byte[] buffer, Int32 offset, Int32 count, Boolean dontDeferFinalBytes, Boolean shouldAppendSpaceToCRLF)
at System.Net.Base64Stream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Mime.MimePart.Send(BaseWriter writer)
at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer)
at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelope)
at System.Net.Mail.SmtpClient.Send(MailMessage message)

It seems that there’s a bug in .NET 4 related to sending emails sized more than 3 MB.

Hopefully it can be fixed using a MS hotfix that you can find here.

Take into consideration that when you apply the hotfix it won’t require any server reboot but your ASP.NET state service will stop. Just restart it and do an IIS reset just to be sure that everything will run ok as on one of my node servers the hotfix didn’t work until I reset the IIS.