使用Graph API发送带有多个附件的邮件

时间:2020-10-06 15:21:31

标签: java microsoft-graph-api microsoft-graph-mail

我正在使用Microsoft-Graph API 1.4版,并尝试使用以下代码发送带有附件的邮件。

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();

引用链接:Graph-Send-Mail

但是,message.attachments需要AttachmentCollectionPage对象而不是LinkedList();

任何人都可以帮助我发送带有多个附件的邮件。

谢谢

1 个答案:

答案 0 :(得分:0)

我找到了使用1.4.0版本在单个邮件中发送多个附件的解决方案。签出以下代码...

val address = EmailAddress()
address.address = "vivek@domain.com"
val recipient = Recipient()
recipient.emailAddress = address

val message = MyMessage()
message.subject = "Test E-Mail"
message.body = getItemBody()
message.toRecipients = Collections.singletonList(recipient)

val att = FileAttachment()
att.contentBytes = File("/home/user/file.pdf").readBytes()
att.contentType = "text/pdf"
att.name = "file.pdf"
att.oDataType = "#microsoft.graph.fileAttachment"

val att2 = FileAttachment()
att2.contentBytes = "hello there! from second file".toByteArray(StandardCharsets.UTF_8)
att2.contentType = "text/plain"
att2.name = "hi2.txt"
att2.oDataType = "#microsoft.graph.fileAttachment"

message.addAttachment(att)
message.addAttachment(att2)

graphClient.me()
.sendMail(message,false)
.buildRequest()
.post();

以上代码可用于发送多个大小小于4 MB的附件。要发送超出限制的邮件,请参阅this

相关问题