开发者

How to get attachment of EmailMessage?

开发者 https://www.devze.com 2023-02-19 00:22 出处:网络
I try to get images which you can find in the Attachment of an EmailMessage. But when I run the code I\'m getting this error: Object reference not set to an instance of an object.

I try to get images which you can find in the Attachment of an EmailMessage. But when I run the code I'm getting this error: Object reference not set to an instance of an object.

This is the code:

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);
       开发者_Python百科 }
    }
}
//string s = System.Text.Encoding.UTF8.GetString(item.MimeContent.Content);
//FreeTextBox1.Text += s;


Since you are blowing up on

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

and you have already checked the lengh of the Attachments, then the content type of the Attachment object must not be set. Since you are using this to perform the rest of your code, looks like this is required for you. How is this message being generated?

I would add some code to take a look at the attachment, maybe the AttachmentType or FileName property, to ensure you have the attachment details, and determine the course of action. Maybe you are adding the attachment yourself and just need to set the contenttype. Good luck!


Instead of

FileAttachment[] attachments = null;

you should make an instance of it:

FileAttachment[] attachments = new FileAttachment[10];

for example

0

精彩评论

暂无评论...
验证码 换一张
取 消