ComponentPro UltimateMail

Extracting attachments from a message

Language Filter: AllSend comments on this topic to ComponentPro

Attachments in a mail message can either be extracted to file or stream object. The example below shows how to load a mail message and save its attachments to disk:

using System;
using ComponentPro.Net.Mail;

...

/// <summary> 
/// Extracs attachments from a mail file. 
/// </summary> 
/// <param name="fileName">Mail file name.</param> 
/// <returns>A boolean value indicating whether the extraction is successful.</returns> 
private static bool ExtractAttachments(string fileName)
{
    try 
    {
        // Load the mail message from disk 
        MailMessage mail = new MailMessage();
        mail.Load(fileName);

        // DecryptData the message if it is encrypted 
        if (mail.IsEncrypted)
        {
            if (!mail.Decryptable)
            {
                Console.WriteLine("Message cannot be decrypted. You do not have the private key.");
                return false;
            }
            mail.Decrypt();
        }

        // ValidateRequest the signature if the message is signed 
        if (mail.IsSigned)
        {
            MailSignatureValidationResult result = mail.ValidateSignature();
            if (result.Valid)
            {
                Console.WriteLine("The message is signed and the signature is valid.");
            }
            else 
            {
                Console.WriteLine("The message is signed, but the signature is not valid.");                        
            }
        }

        Console.WriteLine("Message contains {0} attachments.", mail.Attachments.Count);

        // If message has no attachments, just exit 
        if (mail.Attachments.Count == 0)
            return false;

        foreach (Attachment attachment in mail.Attachments)
        {
            // Write the file 
            Console.WriteLine("Saving '{0}' ({1}).", attachment.FileName, attachment.MediaType);
            attachment.Save(attachment.FileName);
        }

        return true;
    }
    catch (Exception exc)
    {
        Console.WriteLine("An error occurred: {0}", exc.Message);
    }

    return false;
}