+1 vote

Hi, I'm looping through Gmail mails attachments and would like to check if attachment contains certain string + is Ms-Word file as decision criteria for saving the attachment to server folder.

I'm using VB.Net script.

Your kind guidance is appreciated.

Thanks!

by

1 Answer

0 votes

You have two options: use MimeData.ContentType property -or- use MimeData.SafeFileName.

I would use the second option as some mail clients may attach word documents using generic 'application/octet-stream' content type, instead of 'application/msword' (doc) or 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' (docx).

Here's the approach with checking the extension:

using(Imap imap = new Imap())
{
    imap.Connect("imap.example.com"); // or ConnectSSL for SSL
    imap.UseBestLogin("user", "password");

    imap.SelectInbox();
    List<long> uids = imap.Search(Flag.Unseen);
    foreach (long uid in uids)
    {
       var eml = imap.GetMessageByUID(uid);
       IMail email = new MailBuilder().CreateFromEml(eml);

       foreach (MimeData mime in email.Attachments)
       {
           string ext = Path.GetExtension(mime.SafeFileName)
                .ToLowerInvariant();
           if (ext == ".doc" || ext == ".docx")
           {
                byte[] data = mime.Data;
                // here you can process ms-word data.
           }
       }
    }
    imap.Close();
}

Not sure what you mean exactly by the certain string in the attachment.
If the attachment is MSWord file you need to process it first by some component/library that knows how to open MSWord documents.

I'm not sure about your scenario, but you probably could use Imap.GetMessageInfoByUID to get all emails' details and fully download only those only those that have attachments matching your needs:
https://www.limilabs.com/blog/get-email-information-from-imap-fast

by (297k points)
...