在将Exchange电子邮件附件添加为smtp的MailAttachment后,无法正确渲染。

huangapple go评论58阅读模式
英文:

Unable to render the Exchange Email attachment properly after adding as MailAttachment for smtp

问题

我需要将EmailMessage转换为MailMessage以便通过smtp发送邮件。尽管如果附件是.docx、.txt、.jpg等文件,它们会正确显示。我面临的问题是,每当EmailMessage包含电子邮件附件(.msg)时,附件就会变成字符串/流(Image2)。我已经添加了附件对象的属性截图(Image3)。

**问题:**我需要在我的代码中添加什么来确保附件与来自Microsoft Exchange Email的原始附件完全相似,例如期望的结果Image1?

Image1: 附件在通过smtp发送之前的样子。
在将Exchange电子邮件附件添加为smtp的MailAttachment后,无法正确渲染。

Image2: 通过smtp发送后的附件结果。
在将Exchange电子邮件附件添加为smtp的MailAttachment后,无法正确渲染。

Image3: 附件属性截图
在将Exchange电子邮件附件添加为smtp的MailAttachment后,无法正确渲染。

我的代码如下:

MailMessage message = new MailMessage();
EmailMessage msg = new EmailMessage(service); //service是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)
    {
        // .txt、.docx、.xlsx等附件
        // 这段代码对于FileAttachment完全正常工作。
        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)
    {
        // 这是将EmailMessage附件转换为MailMessage附件的地方
        // 附件是.msg
        // 这里的结果变成了随机字符串
        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);
        }
    }
}

// 使用SMTP发送MailMessage
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);
}
英文:

I needed to convert an EmailMessage to MailMessage for smtp mail sending. Although if the attachments are files such as .docx, .txt, .jpg etc it displays correctly. The problem I'm facing is that whenever the EmailMessage contains email attachments (.msg), the attachment become strings /stream(Image2). I have added a screenshot of the properties of the attachment object(Image3).

Question: What do I need to add in my code to make sure that the attachment is exactly similar from the original attachment coming from Microsoft Exchange Email like for example the expected result Image1?

Image1: How the attachment should look like after smtp send.
在将Exchange电子邮件附件添加为smtp的MailAttachment后,无法正确渲染。

Image2: Result of the Attachment after smtp mail sending.
在将Exchange电子邮件附件添加为smtp的MailAttachment后,无法正确渲染。

Image3: attachment properties screenshot
在将Exchange电子邮件附件添加为smtp的MailAttachment后,无法正确渲染。

My Code Below:

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

答案1

得分: 1

由于ContentType message/rfc822 表明消息(附件)采用互联网消息格式,这是邮件服务器通常发送和接收电子邮件的格式,因此您需要将附件的名称从.msg更改为.eml。
Outlook可以轻松打开eml文件。

参考链接:使用EWS Managed API将电子邮件保存为.msg文件

英文:

As the ContentType message/rfc822 indicates the message (attachment) is in the internet-message-format which is the format how mailservers usually send and receive emails, you need to change the attachments name from .msg to .eml.
Outlook can easily open eml files.

See also: saving-an-email-to-a-msg-file-using-ews-managed-api

答案2

得分: 0

我成功解决了这个问题。我在这里添加了我的更新代码,希望能帮到其他人。我尝试了@Heslacher建议的方法。

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;
 
   if (attachment.ContentType.ToString().ToLower().Equals("message/rfc822"))
   {
      // 将扩展名更改为使邮件可读
      // 兼容性:.eml 文件被许多电子邮件客户端和应用程序支持,
      // 使它们成为在不同平台上共享电子邮件消息的更便携和互操作的选择。
      attachmentName = $"{itemAttachment.Name}.eml";
   }
   System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(ms, attachmentName);
   ContentDisposition disposition = att.ContentDisposition;
   disposition.Inline = true;
   att.ContentType.CharSet = "UTF-8";
   message.Attachments.Add(att);
}
英文:

I managed to resolve the issue. I'm adding my updated code here so it can help anyone. I tried what @Heslacher suggested.

ItemAttachment itemAttachment = attachment as ItemAttachment;
if (itemAttachment != null)
{
   itemAttachment.Load(new PropertySet(ItemSchema.MimeContent));
   // Store it inside a memorystream
   byte[] itemContent = itemAttachment.Item.MimeContent.Content.ToArray();
   ms = new MemoryStream(itemContent);
   attachmentName = itemAttachment.Name;
 
   if (attachment.ContentType.ToString().ToLower().Equals("message/rfc822"))
   {
	  //renaming the extension to make the email readable
	  //Compatibility: .eml files are supported by many email clients and applications, 
	  //making them a more portable and interoperable choice for 
	  //sharing email messages across different platforms.
	  attachmentName = $"{itemAttachment.Name}.eml";
   }
   System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(ms, attachmentName);
   ContentDisposition disposition = att.ContentDisposition;
   disposition.Inline = true;
   att.ContentType.CharSet = "UTF-8";
   message.Attachments.Add(att);
}

huangapple
  • 本文由 发表于 2023年7月27日 14:31:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定