Search code examples
c#mailkit

Get the MimeMessage size using MailKit


My SMTP server restricts the amount of data that can be sent per smtpclient session as well as some other constraints. For example, I want to send 10 messages but the server may impose a limit of 10Mb total. I would like to calculate the size of the messages so that I know when I need to reinitialize the server connection.

I am using the MailKit library for this effort.

I was considering writing the Message.Body, which would include the attachments, to a MemoryStream, but that seems like overkill just to get the size.

If I have an in memory MimeMessage object, is there a method to determine its complete content length prior to sending?

------UPDATE------

If there was not a native option this was my proposed method:

using (var memory = new MemoryStream())
      {
         await mailMessage.Body.WriteToAsync(memory);
         curMessageLength = Convert.ToBase64String(memory.ToArray()).Length;
       }

Solution

  • What you want can be done like this:

    // Make sure to prepare the message for sending before you call
    // SmtpClient.Send/Async() so that you are getting an accurate size.
    mailMessage.Prepare (EncodingConstraint.SevenBit);
    
    using (var stream = new MimeKit.IO.MeasuringStream ())
    {
        await mailMessage.WriteToAsync (stream);
        curMessageLength = stream.Length;
    }
    

    MimeKit has a convenient MeasuringStream so that you don't need to allocate memory.

    I'm pretty sure you also want to measure the entire message content (including the message headers).

    I don't understand why you were base64 encoding the output message, but I doubt you need or want to do that.