Remove attachments from email

First, there is one thing you must be aware of: neither POP3 nor IMAP protocol provide a way to remove attachments from existing emails. This is because email stored on the server is immutable. With IMAP protocol you can copy email message to different folder, you can apply some flags (\SEEN) to it, but you can’t change any part of the message.

The second important thing is, that attachments are not stored separately from the message text and headers – they are embedded inside the email.

Nevertheless Mail.dll provides an easy way to remove attachments from existing email message.

// C#

IMail email = new MailBuilder().CreateFromEml(eml);
email.RemoveAttachments();

' VB.NET

Dim email As IMail = New MailBuilder().CreateFromEml(eml)
email.RemoveAttachments()

RemoveAttachments method has an overloaded version, that allows you to skip visual elements (content-disposition: inline) or/and alternative email representations:

// C#

IMail email = new MailBuilder().CreateFromEml(eml);

AttachmentRemoverConfiguration configuration = new AttachmentRemoverConfiguration();
configuration.RemoveVisuals = false;

email.RemoveAttachments(configuration);

' VB.NET


Dim email As IMail = New MailBuilder().CreateFromEml(eml)

Dim configuration As New AttachmentRemoverConfiguration()
configuration.RemoveVisuals = False

email.RemoveAttachments(configuration)

The following example illustrates the full process of downloading email from IMAP server,
creating new email, with the same information, but without attachments, and finally uploading it, and removing the original message:

// C#

using(Imap imap = new Imap())
{
    imap.ConnectSSL("imap.example.org");
    imap.UseBestLogin("user", "password");
    imap.SelectInbox();

    foreach (long uid in imap.GetAll())
    {
        var eml = imap.GetMessageByUID(uid);
        IMail email = new MailBuilder().CreateFromEml(eml);
        if (email.Attachments.Count > 0)
        {
            email.RemoveAttachments();

            imap.UploadMessage(email);

            imap.DeleteMessageByUID(uid);
        }
    }
    imap.Close();
}
' VB.NET

Using imap As New Imap()
   imap.ConnectSSL("imap.example.org")
   imap.UseBestLogin("user", "password")
   imap.SelectInbox()

   For Each uid As Long In imap.GetAll()
      Dim eml = imap.GetMessageByUID(uid)
      Dim email As IMail = New MailBuilder().CreateFromEml(eml)
      If email.Attachments.Count > 0 Then
         email.RemoveAttachments()

         imap.UploadMessage(email)

         imap.DeleteMessageByUID(uid)
      End If
   Next
   imap.Close()
End Using

Tags: , , , , ,

Questions?

Consider using our Q&A forum for asking any questions.