Calculating the size of an email in .NET
Say I have an email class that has the following properties:
public string From { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public Dictionary<string, byte[]> Attachments { get; set; }
I need to calculate the size of the email and if it is less than 10MB email it otherwise send the conte开发者_StackOverflownt as a fax (to prevent it being bounced from its destination).
I can calculate the size of attachments relatively easily.
Is there an accurate way to calculate the entire email size? I'm guessing I'll need to add the size of the strings as well as any header information that will be appended?
You cannot accurate know the size of the header. Since all servers that pass the mail to the next server might add some data to the header. This can range from one simple line, to the complete score of the spam scanning.
So you will always get it wrong a few bytes.
As for the size of the attachments: They are encoded, so the nr of bytes is not the actual size taken. If you convert them to Base64 and take the length of that string, that's about the size they will take in the email (without attachment header, depending on the attachment name). An estimate is nr of bytes * 1.33.
You can get a good clue, if the mail approaches 10 MB, but when the final and received mail is exactly 10 MB is not known.
The total size will be the length of the strings plus size of the attachments.
If you're serializing this into a proper email format using a stream, you can use the Stream.Length
property to get the length easily.
Instead of using byte[]
to store the attachments in memory, I suggest you use FileInfo
to get the length of the attachments and then use a FileStream
to directly pipe the attachment data into a target email file or network stream:
using System.IO;
...
FileInfo fi = new FileInfo(@"c:\path\to\file");
long fileSize = fi.Length;
...
// assuming List<string> for attachment file names
foreach (string attachFile in attachments)
{
using (FileStream afs = new FileStream(attachFile))
{
byte[] buffer = new byte[1024];
while (!afs.EndOfstream)
{
int br = afs.Read(buffer, 0, 1024);
// assume targetStream is the NetworkStream or FileStream that you want to write to
targetStream.Write(buffer, 0, br);
}
}
}
精彩评论