Chilkat.Mime Class Overview

Chilkat.Mime provides low-level MIME and S/MIME handling. It can load, create, inspect, modify, serialize, and save MIME messages; build multipart structures; manage headers and body encodings; extract attachments; convert MIME to and from XML; sign, verify, encrypt, decrypt, and unwrap PKCS7/CMS S/MIME security layers.

What the Class Is Used For

Use Chilkat.Mime when an application needs direct control over MIME structure and S/MIME security. The class is useful for working with MIME parts, attachments, multipart/alternative or multipart/mixed messages, raw MIME import/export, PKCS7/CMS signatures, encrypted MIME, certificate-based encryption and decryption, and diagnostic inspection of MIME or ASN.1 content.

Build MIME Trees Create multipart/mixed, multipart/alternative, multipart/related, and nested MIME structures using sub-parts.
Read and Modify Headers Add, replace, remove, enumerate, and parse MIME headers and header attributes.
Handle Bodies and Attachments Set or retrieve text, HTML, XML, encoded, binary, file-based, and decoded MIME body content.
S/MIME Security Create detached or opaque signatures, verify signatures, encrypt, decrypt, and recursively unwrap signed/encrypted MIME.

Typical Workflow

  1. Load existing MIME with LoadMime, LoadMimeFile, LoadMimeBd, LoadMimeBytes, or create a new structure with NewMultipartMixed, NewMultipartAlternative, or NewMultipartRelated.
  2. Inspect or set top-level headers using properties such as ContentType, Charset, Encoding, Disposition, Filename, and Name.
  3. Set or retrieve body content with SetBody, SetBodyFromPlainText, SetBodyFromHtml, SetBodyFromXml, GetBodyDecoded, or GetBodyBinary.
  4. Build multipart content by appending parts with AppendPart or AppendPartFromFile.
  5. Traverse multipart structures using NumParts and PartAt.
  6. Apply S/MIME security when needed using signing, encryption, decryption, or verification methods.
  7. Export or save the result with GetMime, GetMimeBytes, SaveMime, GetXml, or SaveXml.

Core Concepts

Concept Meaning Important Members
MIME Header The header section containing fields such as Content-Type, Content-Transfer-Encoding, Content-Disposition, Subject, From, and custom fields. AddHeaderField, SetHeaderField, GetHeaderField, RemoveHeaderField
MIME Body The content following the header. It may be plain text, HTML, XML, binary data, encoded data, or another MIME message. SetBody, SetBodyFromFile, GetBodyDecoded, SaveBody
Multipart MIME A MIME part that contains direct child parts, forming a tree structure with possible nested multiparts. NumParts, PartAt, AppendPart, RemovePart
Boundary The separator string used by multipart MIME. It is the boundary attribute of the Content-Type header. Boundary, NewMultipartMixed, NewMultipartAlternative
S/MIME MIME protected with PKCS7/CMS signing and/or encryption. Encrypt, Decrypt, Verify, UnwrapSecurity
Opaque Signature A PKCS7 signed MIME object where the original content and signature are wrapped together as application/pkcs7-mime or application/x-pkcs7-mime. ConvertToSigned, ConvertToSignedPk
Detached Signature A multipart/signed MIME structure where the original content is one part and the signature is another part. AddDetachedSignature, AddDetachedSignaturePk

Core MIME Properties

Property Header Field / Meaning Example / Guidance
ContentType Value of the Content-Type header, excluding attributes. text/plain, text/html, multipart/mixed, application/pkcs7-mime.
Charset The charset attribute of Content-Type. Examples: utf-8, iso-8859-1, windows-1252.
Encoding Content-Transfer-Encoding header. Examples: base64, quoted-printable, 7bit, 8bit, binary.
Disposition Content-Disposition value, excluding attributes. Commonly attachment or inline.
Filename Filename attribute of Content-Disposition. Used for attachments and by extraction methods such as PartsToFiles.
Name Name attribute of Content-Type. Often used for named attachment content.
Boundary Boundary attribute of multipart Content-Type. Usually generated automatically by multipart creation methods.
NumHeaderFields Number of MIME header fields. Enumerate with GetHeaderFieldName and GetHeaderFieldValue.
NumParts Number of direct child MIME parts. Recursively traverse the MIME tree with PartAt.

Loading and Saving MIME

Task Methods Use When
Load MIME from memory LoadMime, LoadMimeBytes, LoadMimeBd, LoadMimeSb The MIME source is already in a string, byte array, BinData, or StringBuilder.
Load MIME from file LoadMimeFile Reads a complete MIME or EML-style message from disk.
Export complete MIME GetMime, GetMimeBytes, GetMimeBd, GetMimeSb Returns the full MIME message including headers and all sub-parts.
Save MIME to file SaveMime Saves in MIME format, equivalent to EML-style content.
Get header or body only GetEntireHead, GetEntireBody Useful for inspecting the top-level header or entire body including sub-parts.
Add Content-Length AddContentLength Computes body size and adds or updates a Content-Length header.

Creating Multipart MIME

Multipart Type Method Typical Use
multipart/mixed NewMultipartMixed, ConvertToMultipartMixed General-purpose multipart message, commonly used for attachments.
multipart/alternative NewMultipartAlternative, ConvertToMultipartAlt Multiple representations of the same content, such as plain text and HTML.
multipart/related NewMultipartRelated Related content, such as HTML and inline images.
message/rfc822 NewMessageRfc822 Wraps another MIME message as the body of a message/rfc822 part.
Part Operation Method Behavior
Add an existing MIME object AppendPart Appends a sub-part. If the parent is not already multipart, it is converted to multipart/mixed.
Add a file as a MIME part AppendPartFromFile Creates a part from a file and uses the file extension to determine content type.
Retrieve a sub-part PartAt Retrieves the Nth direct child part. Indexing starts at 0.
Remove a sub-part RemovePart Removes the Nth direct child part.
MIME tree traversal: NumParts counts only direct children. To inspect the whole message, recursively call PartAt on each child and repeat.

Body Content

Body Type Set Methods Retrieve / Save Methods
Plain text SetBody, SetBodyFromPlainText GetBodyDecoded, SaveBody
HTML SetBodyFromHtml GetBodyDecoded, IsHtml
XML SetBodyFromXml GetBodyDecoded, IsXml
Binary data SetBodyFromBinary, SetBodyBd GetBodyBinary, GetBodyBd
Encoded text SetBodyFromEncoded GetBodyEncoded, GetBodyDecoded
File contents SetBodyFromFile SaveBody
Side-effect note: SetBodyFromPlainText, SetBodyFromHtml, and SetBodyFromXml update Content-Type and may set charset or transfer encoding. Use SetBody when the application wants to set body text without intentional header side effects.

Header Management

Need Method Notes
Add a header field AddHeaderField Adds a new MIME header field.
Add or replace a header field SetHeaderField Replaces an existing field or adds it if missing. Passing an empty value removes the header field.
Remove a header field RemoveHeaderField Can remove the first occurrence or all occurrences.
Get header value by name GetHeaderField Header field names are case-insensitive.
Get header attribute GetHeaderFieldAttribute Parses semicolon-separated header attributes, such as the boundary or charset attribute of Content-Type.
Enumerate headers NumHeaderFields, GetHeaderFieldName, GetHeaderFieldValue Use zero-based indexing to inspect every header field.

Inspecting MIME Type and Structure

Question Methods Meaning
Is it multipart? IsMultipart, IsMultipartMixed, IsMultipartAlternative, IsMultipartRelated Identifies multipart structures and common multipart subtypes.
What kind of body content is it? IsText, IsPlainText, IsHtml, IsXml, IsImage, IsAudio, IsVideo, IsApplicationData Tests content-type categories.
Is it an attachment? IsAttachment Returns true when Content-Disposition contains attachment.
Is it S/MIME signed or encrypted? IsSigned, IsEncrypted, ContainsSignedParts, ContainsEncryptedParts Detects PKCS7 signed/encrypted MIME in the current visible MIME structure.
Show the MIME tree GetStructure Returns a structure summary in text or xml format.
Encrypted wrapper note: If a signed MIME message is later encrypted, the signed content is hidden until decryption. In that case, signed parts may not be detectable until UnwrapSecurity decrypts the encrypted layer.

Attachments and Parts

Task Method / Property Guidance
Determine whether a part is an attachment IsAttachment Checks whether Content-Disposition contains attachment.
Get or set attachment filename Filename Maps to the filename attribute of Content-Disposition.
Append file as a new part AppendPartFromFile Uses file extension to determine content type and adds it as a sub-part.
Extract parts with filenames PartsToFiles Recursively traverses the MIME tree and saves parts that have a filename. The saved filenames are returned in a StringTable.
Save current part body SaveBody Saves the body of the current MIME part to a file, decoding base64 or quoted-printable automatically.

S/MIME Signing

Signature Type Method Result
Detached signature AddDetachedSignature Converts the MIME to multipart/signed. The original content becomes the first sub-part and the signature becomes the second sub-part.
Detached signature with separate private key AddDetachedSignaturePk Use when the certificate and private key are provided separately, such as a .cer plus a .pem.
Detached signature with header-transfer control AddDetachedSignature2, AddDetachedSignaturePk2 Adds control over whether header fields from the calling MIME object are transferred to the content part.
Opaque signature ConvertToSigned Converts the MIME to application/pkcs7-mime or application/x-pkcs7-mime, where the original content and signature are wrapped together.
Opaque signature with separate private key ConvertToSignedPk Use when the certificate and private key are available separately.
Signing Setting Property Purpose
Hash algorithm SigningHashAlg Selects the hash used when creating signed PKCS7 MIME. Possible values include sha1, sha256, sha384, sha512, md5, and md2.
RSA signature algorithm SigningAlg For RSA private keys, choose PKCS1-v1_5 or RSASSA-PSS / pss.
micalg attribute Micalg Sets the micalg attribute for multipart/signed. Prefer SigningHashAlg for choosing the signing hash.
x-pkcs7 vs pkcs7 content types UseXPkcs7 Default true uses x-pkcs7 content types. Set false to use pkcs7.

S/MIME Encryption and Decryption

Need Methods / Properties Guidance
Encrypt for one recipient Encrypt Encrypts using the public key contained in the recipient certificate.
Encrypt for multiple recipients AddEncryptCert, EncryptN, ClearEncryptCerts Add each recipient certificate, then call EncryptN.
Select content encryption algorithm Pkcs7CryptAlg, Pkcs7KeyLength Algorithm choices include aes, aes-gcm, des, 3des, and rc2. Key lengths depend on the algorithm.
Use RSAES-OAEP for recipient encryption OaepPadding, OaepHash, OaepMgfHash Set OaepPadding = true to use RSAES-OAEP instead of RSAES-PKCS1-v1_5. Hash options include sha1, sha256, sha384, and sha512.
Decrypt automatically Decrypt Searches available PFX sources, XML certificate vault, and Windows certificate stores for the required certificate and private key.
Decrypt with explicit cert/key Decrypt2, DecryptUsingCert Use when the decrypting certificate or private key is already known.
Decrypt with explicit PFX DecryptUsingPfxFile, DecryptUsingPfxData Use when the recipient private key is stored in a PFX/P12 file or byte array.

Certificate Sources for S/MIME

Source Methods Use Case
Explicit certificate for decryption AddDecryptCert Makes a certificate and its private key available for decryption.
PFX/P12 file AddPfxSourceFile Adds a PFX file to the search list for certificates and private keys.
PFX/P12 bytes AddPfxSourceData, AddPfxSourceBd Adds an in-memory PFX source, useful when PFX data is stored outside the filesystem.
XML certificate vault UseCertVault Adds a certificate vault for encrypting, decrypting, signing, and verifying. Only one vault is active; repeated calls replace the previous vault.
Explicit verify certificate SetVerifyCert Supplies the certificate to use for signature verification.
Private-key requirement: Decryption and signing require access to the private key. A certificate alone is enough for encryption or verification, but not for decrypting or creating a signature.

Verifying and Unwrapping S/MIME

Task Method / Property Behavior
Verify signed MIME Verify Verifies PKCS7 signed MIME and unwraps it, restoring the original MIME structure before signing. Works with detached and opaque signatures.
Recursively unwrap security layers UnwrapSecurity Recursively decrypts and/or verifies all signed/encrypted layers until no further security wrapping remains.
Check for signed/encrypted content ContainsSignedParts, ContainsEncryptedParts, IsSigned, IsEncrypted Checks whether the current visible MIME structure contains signed or encrypted parts.
Signer certificates NumSignerCerts, LastSignerCert After verification or unwrapping, retrieve certificates used to sign the MIME.
Decrypt certificates NumDecryptCerts, LastDecryptCert, GetDecryptCertInfo After decryption or unwrapping, inspect certificate information related to decryption.
Signature signing time HasSignatureSigningTime, GetSignatureSigningTimeStr Check whether a signature includes a signing-time timestamp and retrieve it in RFC 822 format.
Use UnwrapSecurity for layered S/MIME: When MIME may be both signed and encrypted, or may contain nested signed/encrypted parts, UnwrapSecurity is usually the most complete operation because it traverses and unwraps recursively.

MIME ↔ XML Conversion and Inspection

Task Method Purpose
Convert MIME to XML string GetXml Converts the MIME or S/MIME message to XML for inspection or storage.
Save MIME as XML SaveXml Converts the MIME to XML and writes it to a file.
Load MIME from XML string LoadXml Converts XML to MIME and replaces the object’s contents.
Load MIME from XML file LoadXmlFile Converts an XML file to MIME and replaces the object’s contents.
Inspect ASN.1 body as XML AsnBodyToXml Converts a PKCS7 ASN.1 DER body, usually base64 encoded in a MIME part, to XML for inspection.
Get structure summary GetStructure Produces a MIME structure summary in text or xml format.

Encoding and Formatting Utilities

Need Method / Property Guidance
Convert 8bit/binary parts for string export Convert8Bit Changes 8bit or binary MIME subparts to base64 so the MIME can safely be exported as a string with GetMime.
URL-encode body UrlEncodeBody Encodes the body using the specified charset. Charset affects the resulting percent-encoded bytes.
Current RFC 822 date CurrentDateTime Returns the current date/time formatted for MIME-style headers.
Multipart boilerplate body UseMmDescription Controls whether boilerplate text such as “This is a multi-part message in MIME format.” is used as multipart body content.
Unwrap extra informational headers UnwrapExtras Controls whether informative header fields are added when unwrapping security.

Diagnostics

Problem Area Member What to Check
General failure LastErrorText Detailed information about the last method or property access. Check this after failures or unexpected behavior.
S/MIME verification/decryption details GetLastJsonData After methods such as UnwrapSecurity, returns JSON details about algorithms used for signature verification and decryption.
Unexpected MIME tree GetStructure, NumParts, PartAt Inspect the MIME structure before modifying or unwrapping it.
Missing decryption certificate/private key AddDecryptCert, AddPfxSourceFile, AddPfxSourceData, UseCertVault, GetDecryptCertInfo Ensure the required certificate and private key are available from one of the configured sources.
Signature verification certificate issue SetVerifyCert, UseCertVault, LastSignerCert Inspect signer certificates or provide an explicit verification certificate.
Encoded body looks wrong Encoding, Charset, GetBodyEncoded, GetBodyDecoded Confirm the transfer encoding and character set used to decode the body.

Common Pitfalls

Pitfall Better Approach
Assuming NumParts counts every part in the full tree. It counts only direct children. Recursively traverse each child with PartAt.
Setting Content-Type before SetBodyFromFile and expecting it to remain unchanged. SetBodyFromFile updates Content-Type and Content-Transfer-Encoding based on the file. Set required header values after calling it.
Using GetBodyEncoded when decoded content is needed. Use GetBodyDecoded for text or GetBodyBinary for bytes after base64 or quoted-printable decoding.
Expecting signed parts to be visible inside encrypted MIME. Decrypt first or use UnwrapSecurity to unwrap layers recursively.
Trying to decrypt with only a public certificate. Decryption requires the certificate’s private key. Use PFX/P12, certificate vault, Windows store, or an explicit cert/private-key pair.
Assuming opaque and detached signatures are represented the same way. Detached signatures are multipart/signed. Opaque signatures are PKCS7 MIME where content and signature are wrapped together.

Best Practices

Recommendation Reason
Inspect MIME structure before modifying complex messages. GetStructure helps confirm multipart nesting, attachments, and signed/encrypted layers.
Use multipart helpers instead of manually managing boundaries. Methods such as NewMultipartMixed generate unique random boundaries automatically.
Set body content with the method that matches the intended side effects. Use SetBodyFromPlainText, SetBodyFromHtml, or SetBodyFromXml to update Content-Type automatically. Use SetBody for minimal changes.
Use PartsToFiles for recursive attachment extraction. It walks the MIME tree and saves parts that have filenames.
Prefer SigningHashAlg over directly setting Micalg. The reference notes that SigningHashAlg is the preferred way to choose the signing hash algorithm.
Use UnwrapSecurity for unknown or layered S/MIME. It recursively verifies and decrypts until no further signed or encrypted layers remain.
Configure certificate sources before decrypting or verifying. Add PFX sources, certificate vaults, explicit certs, or private keys before calling security operations.
Check LastErrorText and GetLastJsonData after failures. These provide the most useful diagnostics for MIME parsing, encoding, PKCS7/CMS signing, verification, encryption, and decryption.

Summary

Chilkat.Mime is the low-level MIME and S/MIME class for applications that need detailed control over MIME headers, body content, multipart structures, attachments, raw MIME import/export, XML conversion, and PKCS7/CMS security. It can build and transform MIME trees, classify parts, extract files, create detached or opaque signatures, verify and unwrap signed content, encrypt for one or more recipients, decrypt with certificate/private-key sources, and provide diagnostics for S/MIME operations.

For ordinary email composition, a higher-level email class may be more convenient. Use Mime when precise MIME structure, raw MIME manipulation, or S/MIME wrapping/unwrapping is required.