Search code examples
c#microsoft-graph-apiemail-attachmentsmicrosoft-graph-mail

Graph get emails with PDF attachments and download


I have been trying to get this going all day and have gone through most of the questions on here. Can't get it to work I know the emails being pulled have PDF attachments but when I run the code I don't get anything being pulled down. In fact the attachments object often shows up as NULL however HasAttachments returns true and gives me a URL. Anyone have any ideas ?

int i = 0;
var msgs = _graphServiceClient.Users["abc@Turtles.com "].Messages.Request().Filter("(from/emailAddress/address) eq 'noreply@adr.org'").Top(5000).Header("Prefer", "outlook.body-content-type='text'").GetAsync().Result;
foreach (var message in msgs) //.Where(a => a.Subject.Contains("Defense reminder notifications")))
{

    var mesAtt = _graphServiceClient.Users["abc@Turtles.com"].Messages[message.Id].Request().Expand("Attachments").GetAsync();
    
    if (message.HasAttachments == true && message.Attachments != null) { 
        var fileAttachment = message.Attachments.OfType<FileAttachment>().FirstOrDefault(a => a.ContentId == "application/pdf");

    int b = 0;
    if (fileAttachment != null)
    {
        var base64 = fileAttachment.ContentBytes;
        System.IO.FileStream stream = new FileStream(@"C:\TMP\" + b + "file.pdf", FileMode.CreateNew);
        System.IO.BinaryWriter writer =
        new BinaryWriter(stream);
        writer.Write(base64, 0, base64.Length);
        writer.Close();
     }
     b++;
} 

Solution

  • For anyone wondering how I finally ended up getting this to work here it is: Also contrary to Greg's comment the only way I got this to pull back more than 10 records is calling Top()

    var messages = _graphServiceClient.Users["ab2@123.com"].Messages.Request().Top(1000).Filter("(hasAttachments eq true) and ((from/emailAddress/address) eq 'noreply@adr.org')").Expand("attachments").GetAsync().Result;
    int i = 0;
    if (messages.Count > 0)
    {
        foreach (Message message in messages)
        {
           var fileAttachment = message.Attachments.OfType<FileAttachment>().FirstOrDefault(a => a.Name.Contains(".pdf"));
           if (fileAttachment != null)
           {
               var base64 = fileAttachment.ContentBytes;
               System.IO.FileStream stream = new FileStream(@"C:\TMP\" + i + "file.pdf", FileMode.CreateNew);
               System.IO.BinaryWriter writer = new BinaryWriter(stream);
               writer.Write(base64, 0, base64.Length);
               writer.Close();
               i++;
            }
        }
    }