Hello again,

How can I count the message size from:

msg.Body = tbText.Text;

?
I need to get KBs.

Dani AI

Generated

A quick practical summary: counting characters is a fast heuristic (as suggested), but it can be wrong because bytes depend on encoding (the point raised). For a reliable KB value convert the string to bytes using the encoding you will send with (UTF‑8 is common) and divide by 1024 (or 1000 if you prefer decimal KB).

Example (C#) to get the body size and an attachment estimate:

using System.Text;
string bodyText = /* your message string */;
long bodyBytes = Encoding.UTF8.GetByteCount(bodyText);
double bodyKB = bodyBytes / 1024.0;

long fileBytes = new System.IO.FileInfo(path).Length;
long base64Bytes = 4 * ((fileBytes + 2) / 3); // 4 * ceil(fileBytes/3)
double attachKB = base64Bytes / 1024.0;

Notes and caveats: UTF-8 is variable-width (non-ASCII chars use multiple bytes; surrogate pairs become 4 bytes), and Encoding.GetByteCount handles that. Attachments transmitted as base64 expand by roughly 33% (the formula above gives exact base64 length ignoring CRLF wrapping). Also add space for headers, MIME boundaries and Content-Transfer-Encoding; these can add a few percent extra. If you need the real-on-the-wire size, save the MailMessage as an .eml (use SMTP pickup directory) and check the resulting file size — that includes headers and actual encodings used.

Reference: Encoding.GetByteCount

Recommended Answers

All 4 Replies

Well, if we assume each character is a byte (generally) then you can use tbText.Text.Length to get the total number of characters (bytes) contained in the text segment you're working with and convert from there.

Hope that helps :) Please remember to mark solved once your issue is resolved.

Oh, if it's so, than it's just a piece of a cake... thank you

Please remember that the character count and byte count are not the same.
The byte count will depend upon the text encoding (ASCII, UTF8 etc.).

commented: Darn you nice catch :P +1

if we assume each character is a byte (generally)

Which is why I said "if we assume" each character is a byte :) Correctly noted that different encoding produces different sizes and as such one should determine the size of each character unit prior to relying on my example.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.