Search code examples
c#microsoft-graph-sdks

Graph file attachment while email forward


I need to attached a file while forwarding the email by using MS Graph. Are there any method to add the attachment in ForwardPostRequestBody?

var graphClient = new GraphServiceClient(requestAdapter);

var requestBody = new Microsoft.Graph.Me.Messages.Item.Forward.ForwardPostRequestBody
{
    Comment = "comment-value",
    ToRecipients = new List<Recipient>
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Name = "name-value",
                Address = "address-value",
            },
        },
    },
};
await graphClient.Me.Messages["{message-id}"].Forward.PostAsync(requestBody);

Solution

  • ForwardPostRequestBody has property Message where you can add Attachments.

    When using Message then do not use Comment and ToRecipients of ForwardPostRequestBody.

    Use ToRecipients and Body properties of the Message.

    var base64String = Convert.ToBase64String(File.ReadAllBytes("FilePath"));
    var stringBytes = Encoding.ASCII.GetBytes(base64String);
    var requestBody = new Microsoft.Graph.Me.Messages.Item.Forward.ForwardPostRequestBody
            {
                Message = new Message
                {
                    Body = new ItemBody
                    {
                        Content = "comment-value"
                    },
                    Attachments = new List<Attachment>
                    {
                        new FileAttachment
                        {
                            Name = "fileName",
                            ContentBytes = stringBytes
                        }
                    },
                    ToRecipients = new List<Recipient>
                    {
                        new Recipient
                        {
                            EmailAddress = new EmailAddress
                            {
                                Name = "name-value",
                                Address = "address-value",
                            },
                        },
                    },
                }
            };
    await graphClient.Me.Messages["{message-id}"].Forward.PostAsync(requestBody);