Wednesday, July 21, 2010

BUG: .NET 4.0 (System.Net.Mail) Unable to send emails with large attachments (more than 3MB)

This is probably the first bug reported by customer so far for System.Net.Mail Class in .NET 4.0 Framework, or at least the first one I worked on. This was pretty straight forward repro and I did not had to do much to reproduce the issue locally.

static void Main(string[] args)

       {

           SmtpClient client = new SmtpClient("contoso_smtp_server");
           client.Credentials = new System.Net.NetworkCredential("User1", "Password", "contoso");


           MailMessage msg = new MailMessage("user1@contoso.com", "user2@contoso.com", "Large Attachment Mail", "Large Attachment - Test Body");

           Attachment attachment = new Attachment(@"d:\3mb.dat");
           msg.Attachments.Add(attachment);

           client.Send(msg);

     
       }
That was the simplest code you could possibly write to send out email using SNM but the problem is it Fail with an “Error in sending email” message. So I looked around what was happening and found that the problem was not directly related to SNM but its underlying classes and specifically the Base64Encoding class which was used as default method of encoding emails attachments while sending.

That saved me more troubleshooting and I changed the way the attachments were being encoded from Base64 to 7Bit and it worked like charm.

So all you need to do is add any of the following line to your code to make it work.

// Any "one" of those two code section will work
attachment.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
attachment.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;

Read more: Jive into Messaging world

Posted via email from .NET Info