Graph API Send Mail with Attachments

Vivek Buddhadev 1 Reputation point
2020-10-06T15:12:16.44+00:00

I'm using Microsoft-Graph API version 1.4 and trying to send mail with attachment using following code..

IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();  
  
Message message = new Message();  
message.subject = "Meet for lunch?";  
ItemBody body = new ItemBody();  
body.contentType = BodyType.TEXT;  
body.content = "The new cafeteria is open.";  
message.body = body;  
LinkedList<Recipient> toRecipientsList = new LinkedList<Recipient>();  
Recipient toRecipients = new Recipient();  
EmailAddress emailAddress = new EmailAddress();  
emailAddress.address = "meganb@contoso.onmicrosoft.com";  
toRecipients.emailAddress = emailAddress;  
toRecipientsList.add(toRecipients);  
message.toRecipients = toRecipientsList;  
LinkedList<Attachment> attachmentsList = new LinkedList<Attachment>();  
FileAttachment attachments = new FileAttachment();  
attachments.name = "attachment.txt";  
attachments.contentType = "text/plain";  
attachments.contentBytes = "SGVsbG8gV29ybGQh";  
attachmentsList.add(attachments);  
message.attachments = attachmentsList;  
  
graphClient.me()  
	.sendMail(message,null)  
	.buildRequest()  
	.post();  

Ref.Link: user-sendmail

But, message.attachments requires AttachmentCollectionPage object not LinkedList<Attachment>();

Can anyone help me to send a mail with multiple attachment.

Thanks

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
36,001 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Marc LaFleur 86 Reputation points
    2020-10-06T20:50:56.633+00:00

    You need to case it to an IMessageAttachmentsCollectionPage (note that you also need to encode ContentBytes):

    IMessageAttachmentsCollectionPage Attachments = (IMessageAttachmentsCollectionPage)new List<Attachment>()
    {
      new FileAttachment
      {
        Name = "attachment.txt",
        ContentType = "text/plain",
        ContentBytes = Encoding.ASCII.GetBytes("SGVsbG8gV29ybGQh")
      }
    }