IC Improve Code Recipes

Recipe 9.3 · C#

Attachments and Inline Images

Problem

Reports, invoices and statements go out as attachments. The usual code reads the whole file into a byte array, attaches it with a name built from user data, never disposes the stream, and has no idea how large the message has become until the relay rejects it with a 552 error at month end. Logos are attached as regular files, so they show up as a paper clip instead of in the message.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
var msg = new MailMessage(from, to, subject, body);
foreach (string path in Directory.GetFiles(reportFolder))
{
    msg.Attachments.Add(new Attachment(path));
}
client.Send(msg);

Every file in the folder goes out, including the ones another process is still writing, and file handles stay open until garbage collection runs.

The improved recipe

A composer class wraps MimeKit's BodyBuilder. It tracks the total attachment size against a limit, guesses the media type from the file name, and supports inline images referenced from the HTML by content ID.

C#
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MimeKit;
using MimeKit.Utils;

namespace ImproveCode.Email;

public sealed class EmailComposer
{
    private readonly BodyBuilder _body = new();
    private readonly long _maxAttachmentBytes;
    private long _attachmentBytes;

    public EmailComposer(long maxAttachmentBytes = 10 * 1024 * 1024)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(
            maxAttachmentBytes);
        _maxAttachmentBytes = maxAttachmentBytes;
    }

    public EmailComposer Html(string html)
    {
        _body.HtmlBody = html;
        return this;
    }

    public EmailComposer Text(string text)
    {
        _body.TextBody = text;
        return this;
    }

    public async Task<EmailComposer> AttachAsync(
        string fileName, Stream content, CancellationToken ct = default)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(fileName);
        ArgumentNullException.ThrowIfNull(content);

        var buffer = new MemoryStream();
        await content.CopyToAsync(buffer, ct);
        Reserve(buffer.Length);
        buffer.Position = 0;

        var type = ContentType.Parse(
            MimeTypes.GetMimeType(fileName));
        _body.Attachments.Add(
            Path.GetFileName(fileName), buffer, type, ct);
        return this;
    }

    public string AddInlineImage(string fileName, byte[] data)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(fileName);
        ArgumentNullException.ThrowIfNull(data);
        Reserve(data.Length);

        MimeEntity image = _body.LinkedResources.Add(
            Path.GetFileName(fileName), data);
        image.ContentId = MimeUtils.GenerateMessageId();
        return "cid:" + image.ContentId;
    }

    public MimeMessage Build(MailboxAddress to, string subject)
    {
        ArgumentNullException.ThrowIfNull(to);
        var message = new MimeMessage();
        message.To.Add(to);
        message.Subject = subject;
        message.Body = _body.ToMessageBody();
        return message;
    }

    private void Reserve(long bytes)
    {
        if (_attachmentBytes + bytes > _maxAttachmentBytes)
        {
            throw new InvalidOperationException(
                $"Attachments exceed {_maxAttachmentBytes:N0} bytes. " +
                "Send a download link instead.");
        }
        _attachmentBytes += bytes;
    }
}

A usage snippet showing a statement with a logo and a PDF:

C#
var composer = new EmailComposer();
string logo = composer.AddInlineImage(
    "logo.png", await File.ReadAllBytesAsync(logoPath, ct));
composer.Html($"<img src=\"{logo}\" alt=\"Logo\"><p>Attached.</p>")
        .Text("Your statement is attached.");

await using (var pdf = File.OpenRead(statementPath))
{
    await composer.AttachAsync("Statement-2025-06.pdf", pdf, ct);
}
await sender.SendAsync(composer.Build(to, "June statement"), ct);

How it works

AttachAsync copies the caller's stream into a MemoryStream that the message owns. That makes the lifetime simple: the caller can dispose its file stream as soon as the call returns, and the message can be sent, retried or written to disk later without a closed-stream surprise. The size check runs after the copy, against the real byte count, rather than trusting Stream.Length, which non-seekable streams do not support.

MimeTypes.GetMimeType maps the extension to a media type (application/pdf, image/png) and falls back to application/octet-stream. MimeKit encodes the attachment as base64 and the file name with RFC 2231 encoding, so names with accents or non-Latin characters arrive intact.

AddInlineImage adds the image to LinkedResources and gives it a content ID. BodyBuilder then produces a multipart/related part, and the HTML refers to the image as cid:.... Mail clients show it in place without a download prompt and without a call to an external server, which is also kinder to privacy.

Path.GetFileName strips any folder from the attachment name. A name such as ..\..\report.pdf would not hurt the sender, but it can confuse the receiving client and it leaks your folder structure.

Variations and pitfalls

  • Base64 adds about a third. A 10 MB file becomes roughly 13.5 MB on the wire. Many relays and mailbox providers cap messages somewhere between 10 MB and 35 MB. Above a few megabytes, send a time-limited download link instead.
  • Files still being written. When attaching output from another process, wait for it to finish, or have that process write atomically (Recipe 10.2) so a half-written file is never visible.
  • Sensitive attachments. E-mail is not a secure channel. For payroll, medical or banking documents, send a link to an authenticated portal, not the document.
  • Generated content. You don't need a file at all. Attach a MemoryStream from the CSV, Excel or PDF writers in Chapter 11 directly.