【问题标题】:How to get attachment of EmailMessage?如何获取 EmailMessage 的附件?
【发布时间】:2011-07-21 06:51:57
【问题描述】:

我尝试获取可以在 EmailMessage 的附件中找到的图像。但是当我运行代码时,我收到了这个错误:对象引用未设置为对象的实例。

这是代码:

string sHTMLCOntent = item.Body;

FileAttachment[] attachments = null;

if (item.Attachments.Count != 0)
{
    attachments = new FileAttachment[item.Attachments.Count];
    for (int i = 0; i < item.Attachments.Count; i++)
    {
        string sType = item.Attachments[i].ContentType.ToLower();
        if (sType.Contains("image"))
        {
            attachments[i] = (FileAttachment)item.Attachments[i];
            string sID = attachments[i].ContentId;
            sType = sType.Replace("image/", "");
            string sFilename = sID + "." + sType;
            string sPathPlusFilename = Directory.GetCurrentDirectory() + "\\" + sFilename;
            attachments[i].Load(sFilename);
            string oldString = "cid:" + sID;
            sHTMLCOntent = sHTMLCOntent.Replace(oldString, sPathPlusFilename);
        }
    }
}
//string s = System.Text.Encoding.UTF8.GetString(item.MimeContent.Content);
//FreeTextBox1.Text += s;

【问题讨论】:

  • 错误也应该给你一个行号。
  • 第 88 行:字符串 sType = item.Attachments[i].ContentType.ToLower();
  • 那么itemAttachments[i]ContentType 为空,可能是Attachments[i]
  • 你引用的 EmailMessage 对象的类型是什么。它在什么命名空间中?
  • 使用 Microsoft.Exchange.WebServices.Data; item 是一个 EmailMessage 对象

标签: c# asp.net email exchange-server


【解决方案1】:

因为你要炸了

string sType = item.Attachments[i].ContentType.ToLower();

并且您已经检查了附件的长度,则不能设置Attachment对象的内容类型。由于您使用它来执行其余代码,因此您似乎需要它。此消息是如何生成的?

我会添加一些代码来查看附件,可能是 AttachmentType 或 FileName 属性,以确保您拥有附件详细信息并确定操作过程。也许您是自己添加附件,只需要设置内容类型。祝你好运!

【讨论】:

  • 已更新为 Microsoft.Exchange.Data.Transport.Email 命名空间。相同的逻辑适用于任一命名空间
【解决方案2】:

代替

FileAttachment[] attachments = null;

你应该创建它的一个实例:

FileAttachment[] attachments = new FileAttachment[10];

例如

【讨论】:

  • 他做到了,在他的 if 语句中向下四行。
  • 这完全不相关。 attachments 数组被进一步初始化,并且不是 NullReferenceException 抛出的一部分。
  • 我发帖后看到...我的错
猜你喜欢
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-15
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
  • 1970-01-01
相关资源
最近更新 更多