Search code examples
c#microsoft-graph-api

Sending mail with attachments using microsoft graph api return error Cannot process input of abstract type 'microsoft.graph.attachment'


Here is my code.

private async Task ExecuteSendEmailAsync()
        {
            byte[] fileBytes;
            try
            {
                // Get data
                List<Model.User> receivers = new();
                receivers.Add(
                    new Model.User
                    {
                        EMAIL = "email@email.com"
                    }
                );
                List<Reservation> reservation = new();

                // Preparazione dell'allegato
                // Title and recap
                string contenuto = "<h1 style='text-align:center; font-family: Arial, Helvetica, sans-serif; font-size: 24px;' >Daily report</h1><br>";
                contenuto += @"<br>";

                // Shift
                // HERE I ADD SOME TEXT IN THE CONTENT

                //Create a new document    
                Document document = new(PageSize.A4, 10f, 10f, 10f, 0f);
                HtmlWorker htmlparser = new(document);

                // Using MemoryStream so don't have to save the file
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                    document.Open();
                    htmlparser.Parse(new StringReader(contenuto));
                    document.Close();
                    byte[] bytes = memoryStream.ToArray();
                    memoryStream.Close();                   

                    var requestBody = new Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody
                    {
                        Message = new Message
                        {
                            Subject = "test",
                            Body = new ItemBody
                            {
                                ContentType = BodyType.Text,
                                Content = "Hello, look at the attachment"
                            },
                            Attachments = new List<Microsoft.Graph.Models.Attachment>
                            {
                                new FileAttachment
                                {
                                    OdataType = "#microsoft.graph.fileAttachment",
                                    Name = "Daily_report.pdf",
                                    ContentType = "application/pdf",
                                    ContentBytes = bytes,
                                },
                            }
                        }
                    };

                    // Sends email to all receivers
                    foreach (Model.User rec in receivers)
                    {

                        requestBody.Message.ToRecipients = new List<Recipient>() { new Recipient { EmailAddress = new EmailAddress { Address = rec.EMAIL } } };
                        GraphServiceClient graphClient = GraphHelper.GetAuthenticatedGraphClient("*tenant*"); // tenant is hidden
                        await graphClient.Users["from@email.com"].SendMail.PostAsync(requestBody);
                    }
                }
            }
            catch (Exception e)
            {
                string msg = "Errore durante l'invio di una mail";
                ManageExceptions.ManageLog(e, msg, "ExecuteSendEmail - ReportMensaEmailJob", "Error");
                throw;
            }
}

The graph client gets authenticated correctly, the email is fine, the attachment apparently has something wrong. The email is not send because of the error. What can I try? I couldn't find anything related to my error on internet, i followed the ms guide but needed to use the memorystream since I can't save the file.

UPDATE I'm sending the email to many accounts, apparently the first account of the list works fine, from the second on it does not work.


Solution

  • My mistake was that I was using a foreach to send the email to multiple receivers one by one, that loop broke all the emails apart from the first one.

    I solved the error by creating a list of receivers and removing the foreach, as user2250152 suggested in the comments