Discuss this help topic in SecureBlackbox Forum

MIME: Create message with alternative parts, embedded images and attachment

This is the most complex structure of widely used e-mail messages. Such messages have the following structure:

  • multipart/mixed
    • multipart/alternative
      • text/plain
      • multipart/related
        • text/html
        • image/jpeg or other MIME type
        • and so on for each image referenced in the HTML part
    • application/octet-stream or the specified one
    • and so on for each added attachment

C#:


// create objects; the main part is multipart/mixed
TElMessage message = new TElMessage(new TElMultiPartList(), "My Cool E-mail Client");

// setup message parameters
message.From.AddAddress("Secretary", "sender@company.com");
message.To_.AddAddress("Addressee", "address@domain.com");
message.SetSubject("Test Message");

// create a list for text parts = multipart/alternative
TElMultiPartList textParts = new TElMultiPartList(message);
textParts.SetContentSubtype("alternative");
message.MainPart.AddPart(textParts);

// create a plain text part = text/plain
TElPlainTextPart plainText = new TElPlainTextPart(message);
textParts.AddPart(plainText);
plainText.SetText(@"Just a test message");

// create a list part for html text and images = multipart/related
TElMultiPartList htmlParts = new TElMultiPartList(message);
htmlParts.SetContentSubtype("related");
textParts.AddPart(htmlParts);

// create and setup the HTML part = text/html
TElPlainTextPart htmlText = new TElPlainTextPart(message, message.MainPart);
htmlParts.AddPart(htmlText);
htmlText.SetContentSubtype("html");
htmlPart.SetText(@"<html><head></head><body><cite>Just a test message</cite><p><img src='cid:myImage'></body></html>");

// create and setup the image part = image/jpeg
TElMessagePart image = new TElMessagePart();
htmlParts.AddPart(image);
image.SetContentType("image");
// set an appropriate value corresponding to the image type, i.e. png, gif, etc.
image.SetContentSubtype("jpeg");
// specify the image id as it referenced to in the HTML part
image.SetContentID("myImage");
// specify the image is NOT an attachment
image.SetContentDisposition("inline");
// embed the image data
image.Data = File.ReadAllBytes(@"D:\me.jpg");

// add attachments = application/octet-stream
byte[] data = File.ReadAllBytes(@"D:\cert.cer");
message.AttachData(String.Empty, "my data", data, 0, data.Length);

// assemble and save the message
using (FileStream f = new FileStream(@"D:\test.eml", FileMode.Create, FileAccess.Write, FileShare.Read))
{
    message.AssembleMessage(f);
    f.Close();
}

How To articles about MIME

Discuss this help topic in SecureBlackbox Forum