Microsoft Graph,将多个附件添加到电子邮件

时间:2018-12-03 21:55:35

标签: c# asp.net-core-2.0 microsoft-graph msal

我正在使用.netCore和Microsoft Graph,并尝试将多个附件添加到电子邮件中并发送。电子邮件发送很好,所有内容都在那里(如果我发送2个附件,您会看到有2个附件),但是收件人只能打开第一个附件。 (所有附件的最大大小都小于4MB,所以这不是问题)。

代码是

string content = "{\"message\":{" +
                              "\"subject\":\"" + email.Subject + "\"," +
                               "\"body\":{" +
                                     "\"contentType\": \"HTML\"," +
                                     "\"content\": \"" + email.Msg + "\"" +
                            "}," +
                             "\"toRecipients\": [";
        foreach (var adr in email.SendTo)
        {
            content += "{\"emailAddress\": {\"address\": \"" + adr + "\"} },";
        }
        content += "]";
        if ( email.file != null ) // this is an collection of IFormFile 
        {
            List<EmailAttachment> emailAttachment = new List<EmailAttachment>();
            using (var memoryStream = new MemoryStream())
            {
                foreach (var elem in email.file)
                {
                    await elem.CopyToAsync(memoryStream);
                    emailAttachment.Add(new EmailAttachment
                    {
                        FileName = elem.FileName,
                        AttachmentFile = Convert.ToBase64String(memoryStream.ToArray()),
                        ContentType = elem.ContentType
                    });
                }
            }
            content += ", \"attachments\": [";  //, \"hasAttachments\": true
            emailAttachment.ForEach(elem =>
            {
                content += "{\"@odata.type\": \"#microsoft.graph.fileAttachment\"," +
                            "\"name\":\" " + elem.FileName + "\"," +
                            "\"contentType\":\" " + elem.ContentType +" \"," +
                            "\"contentBytes\":\" " + elem.AttachmentFile + "\"},";
            });
            content += "]";
        }
        content += " }}";

        StringContent contentString = new StringContent(content, Encoding.UTF8, "application/json");

我的代码的下一步是将此httpContent发送到Microsoft图形。

但是,问题是,正如您所看到的,我尝试制作一系列要发送的附件,但是电子邮件的收件人只能打开一个附件(他确实看到全部3个)。 (注意:我安排了一系列收件人来一次发送,效果很好)。

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

许多小时后,答案是我将一个内存流用于多个附件。它必须将所有内容混在一起并且不起作用。现在,我将foreach移出了内存流,并且一切正常。每个附件一个内存流。