jstedfast/MailKit · error · ArgumentNullException

part

Error message

part

What it means

BodyPartCollection.Add(BodyPart) throws ArgumentNullException when the part parameter is null. Collections of BODYSTRUCTURE parts must only contain valid BodyPart instances; adding null would corrupt traversal and indexing of the MIME tree. The message is the parameter name "part".

Solutions

  1. Filter null entries before adding: if (part != null) collection.Add(part)
  2. Use AddRange on a pre-filtered sequence (parts.Where(p => p != null))
  3. Fix the upstream parsing step so it never yields null parts

Example fix

// before
foreach (var p in parts) multipartBodyParts.Add(p); // some p were null
// after
foreach (var p in parts)
	if (p != null) multipartBodyParts.Add(p);
Defensive patterns

Strategy: validation

Validate before calling

if (part == null) return; // or throw with a descriptive message before calling Add

Type guard

static bool IsAddable(BodyPart? p) => p is not null;

Try / catch

try { collection.Add(part); }
catch (ArgumentNullException ex) when (ex.ParamName == "part") { /* log and skip the null part */ }

Prevention

When it happens

Trigger: Calling bodyParts.Add(null) directly, or indirectly from MailKit's internal ParseMultipart/ParseMultipartAsync when building the parsed BODYSTRUCTURE tree for a multipart message.

Common situations: Programmatically constructing a BodyPart tree where a sub-part failed to parse and null was added instead of being skipped; code that maps over a nullable list of parts without filtering nulls.

Related errors


AI-assisted analysis of jstedfast/MailKit@9d3859a785 (2026-09-15). Data as JSON: /api/errors/e0ca2e30b525e409. Report an issue: GitHub.

Appendix: source

Thrown at MailKit/BodyPartCollection.cs:90

		/// <value><see langword="true" /> if this collection is read only; otherwise, <see langword="false" />.</value>
		public bool IsReadOnly {
			get { return false; }
		}

		/// <summary>
		/// Add the specified body part to the collection.
		/// </summary>
		/// <remarks>
		/// Adds the specified body part to the collection.
		/// </remarks>
		/// <param name="part">The body part.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="part"/> is <see langword="null" />.
		/// </exception>
		public void Add (BodyPart part)
		{
			if (part == null)
				throw new ArgumentNullException (nameof (part));

			collection.Add (part);
		}

		/// <summary>
		/// Clears the body part collection.
		/// </summary>
		/// <remarks>
		/// Removes all of the body parts from the collection.
		/// </remarks>
		public void Clear ()
		{
			collection.Clear ();
		}

		/// <summary>
		/// Checks if the collection contains the specified body part.
		/// </summary>

View on GitHub (pinned to 9d3859a785)