gpt4 book ai didi

email - 使用 OpenXML 在内存中发送电子邮件附件

转载 作者:行者123 更新时间:2023-12-04 17:59:39 35 4
gpt4 key购买 nike

我有一个使用 OpenXML 2 构建的 Excel 文件,我想将它作为电子邮件附件发送。例如

    System.IO.MemoryStream stream = new System.IO.MemoryStream();
SpreadsheetDocument package = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
AddParts(package); //created using document reflector

使用以下命令将电子表格保存到临时文件
stream.WriteTo(new System.IO.FileStream(@"c:\test.xlsx", System.IO.FileMode.Create));

工作正常。但是尝试将流直接作为电子邮件附件发送失败 - 当我这样做时,只需将一个空文件附加到电子邮件
System.Net.Mail.Attachment file = new System.Net.Mail.Attachment(stream, "MobileBill.xlsx", "application/vnd.ms-excel");

有人知道怎么做吗?

最佳答案

好的,虽然经过了一些努力,但我还是完成了这项工作。创建流:

MemoryStream stream = new MemoryStream();

using (SpreadsheetDocument package = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
{
Excel.CreateSpreadsheet(package, Excel_Methods.CreateSpotQuoteOut(), true);
}

stream.Seek(0, SeekOrigin.Begin);

System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(stream, "spreadsheet.xlsx");

attach.ContentDisposition.CreationDate = DateTime.Now;
attach.ContentDisposition.ModificationDate = DateTime.Now;
attach.ContentDisposition.Inline = false;
attach.ContentDisposition.Size = stream.Length;
attach.ContentType.MediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

此外,我发现我的创建后没有立即发送,原因是“standalone=yes”没有被添加到所有页面的 xml 声明中,所以在我的 AddParts 函数中,在添加部分之后,我将它们传递给这个函数:
private static void AddXMLStandalone(OpenXmlPart part)
{
System.IO.StreamWriter writer = new System.IO.StreamWriter(part.GetStream());

XmlDocument doc = new XmlDocument();
doc.Load(part.GetStream());

doc.InnerXml = doc.InnerXml.Substring(doc.InnerXml.IndexOf("?>") + 2);
doc.InnerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + doc.InnerXml;

part.GetStream().SetLength(doc.InnerXml.Length);
doc.Save(writer);
writer.Flush();
writer.Close();
}

祝你好运!

关于email - 使用 OpenXML 在内存中发送电子邮件附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1044047/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com