+1 vote

I have an email that contains 12 attachment 9 .png, 2 .xml, 1 pdf.
I only need 3 of them (xml and pdf).
I use for cycle to get pdf and xml. There is any other way to filter attachment before run the cycle.

My code is below

MimeData objmimPDF= null;
string strNomArchivo;
string strNomArchPDF = ""; 
string strRutaArchivo = @"c:\TEST\"; 

foreach (MimeData attachment in email.Attachments)
{
    strNomArchivo = attachment.SafeFileName.ToLower(); 

    if (strNomArchivo.Contains(".xml"))
    {
        attachment.Save(strRutaArchivo + strNomArchivo + ".xml");

        strNomArchPDF = strNomArchivo; //  pdf name to save.

    }
    if (strNomArchivo.Contains(".pdf"))
    {
        objmimPDF = attachment; // get pdf to save later
    }
}

if (objmimPDF != null) 
{
    //save pdf
    objmimPDF.Save(strRutaArchivo + strNomArchPDF + ".pdf");
}
by (260 points)

1 Answer

0 votes

If you already have an IMail instance there are 2 ways of filtering attachments by its content:

Use MimeBase.ContentType:

if (attachment.ContentType == ContentType.ApplicationPdf)
{
    // process attachment as pdf
}

Please note that a sender may use more generic 'application/octet-stream' content type, instead of the more precise one: 'application/pdf'.

Use MimeData.SafeFile and look at the file's extension:

if (Path.GetExtension(attachment.SafeFileName) == ".pdf")
{
    // process attachment as pdf
}

You can use Linq to simplify it:

IMail email = ...;
var pdfs = email.Attachments
    .Where(x => x.ContentType == ContentType.ApplicationPdf);
by (272k points)
edited by
...