我需要将 EmailMessage 转换为 MailMessage 以用于 smtp 邮件发送。但如果附件是 .docx、.txt、.jpg 等文件,它会正确显示。我面临的问题是,每当 EmailMessage 包含电子邮件附件 (.msg) 时,附件就会变成字符串 /stream(Image2)。我添加了附件对象属性的屏幕截图(Image3)。
问题: 我需要在代码中添加什么来确保附件与来自 Microsoft Exchange 电子邮件的原始附件完全相同,例如预期结果 Image1?
我的代码如下:
MailMessage message = new MailMessage();
EmailMessage msg = new EmailMessage(service); //service is Microsoft.Exchange.WebServices.Data
MemoryStream ms = new MemoryStream();
PropertySet propSet = new PropertySet(BasePropertySet.FirstClassProperties,ItemSchema.Attachments, EmailMessageSchema.NormalizedBody, EmailMessageSchema.TextBody);
propSet.RequestedBodyType = BodyType.HTML;
propSet.BlockExternalImages = false;
msg = EmailMessage.Bind(service, emailId, propSet);
foreach (Microsoft.Exchange.WebServices.Data.Attachment attachment in msg.Attachments){
if (attachment is FileAttachment)
{
// Attachments such as .txt, .docx, .xlsx
// This code block for FileAttachment is totally working fine.
FileAttachment fileAttachment = attachment as FileAttachment;
if (fileAttachment != null)
{
fileAttachment.Load();
ms = new MemoryStream(fileAttachment.Content);
attachmentName = fileAttachment.Name;
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(ms, attachmentName);
message.Attachments.Add(att);
}
}
else if (attachment is ItemAttachment)
{
//This is where the EmailMessage attachment gets converted to MailMessage attachment
//Attachment is .msg
//The result here becomes random strings
ItemAttachment itemAttachment = attachment as ItemAttachment;
if (itemAttachment != null)
{
itemAttachment.Load(new PropertySet(ItemSchema.MimeContent));
byte[] itemContent = itemAttachment.Item.MimeContent.Content.ToArray();
ms = new MemoryStream(itemContent);
attachmentName = itemAttachment.Name;
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(ms, attachmentName, attachment.ContentType);
message.Attachments.Add(att);
}
}
}
//Send the MailMessage using SMTP
using (SmtpClient client = new SmtpClient())
{
client.Host = config.smtp_AmazonAWSHost;
client.Port = config.portSMTP;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(config.smtp_Username, config.smtp_Password);
client.EnableSsl = true;
client.Send(message);
}
看来附加信息
ContentDisposition
是Inline
而不是Attachment
。
尝试
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(ms, attachmentName, attachment.ContentType);
ContentDisposition disposition = att.ContentDisposition;
disposition.Inline = false;
message.Attachments.Add(att);