MailItem вложение неизвестно - PullRequest
0 голосов
/ 17 декабря 2018

У меня есть письмо, содержащее только подпись в виде изображения и вложение, как на скриншоте ниже.

Screenshot

Я сохраняю это письмо как C:\mail.msg, Я пытаюсь затем прочитать его по следующему коду:

var oApp = new Microsoft.Office.Interop.Outlook.Application();
MailItem outlookMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItemFromTemplate(@"C:\mail.msg");

//there are 2 attachments inside
foreach(var att in outlookMsg.Attachments) 
{
    att.SaveAsFile($@"C:\{att.FileName}");
}

Проблема

Есть 2 вложений внутри MailItem named:

-empty.xlsx

-lot4.xlsx

Если изменить расширение lot4.xlsx на lot4.png, его можно открыть как изображениев подписи.

Кто-то видел эту странную ситуацию, когда вложение добавляется с неправильным именем?

Ответы [ 2 ]

0 голосов
/ 18 декабря 2018

С Microsoft EWS , это очень легко сделать:

ссылка: http://johnlabtest.blogspot.com/2014/01/save-attachments-from-exchange-mail-box.html

static void Main(string[] args)
{
      ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
      service.Credentials = new WebCredentials("user1@contoso.com", "password");
      service.TraceEnabled = true;
      service.TraceFlags = TraceFlags.All;
      service.AutodiscoverUrl("user1@contoso.com", RedirectionUrlValidationCallback);

      var messages = new List<EmailMessage>();

      // only get unread emails
      SearchFilter folderSearchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
     // we just need the id in our results
     var itemView = new ItemView(10) {PropertySet = new PropertySet(BasePropertySet.IdOnly)};

     FindItemsResults<Item> findResults = service.FindItems(folder.Id, folderSearchFilter, itemView);

     foreach (Item item in findResults.Items.Where(i => i is EmailMessage))
     {
        EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
        messages.Add(message);
     }

  // loop through messages and call processemail here.
}

public static void ProcessEmail(EmailMessage message)
{
     string saveDir = ConfigurationManager.AppSettings["AttachmentSaveDirectory"];
     if (message.HasAttachments)
     {
        foreach (Attachment attachment in message.Attachments.Where(a=> a is FileAttachment))
        {
            FileAttachment fileAttachment = attachment as FileAttachment;
            fileAttachment.Load(); // populate the content property of the attachment

            using (FileStream fs = new FileStream(saveDir + attachment.Name, FileMode.Create))
            {
               using (BinaryWriter w = new BinaryWriter(fs))
               {
                  w.Write(fileAttachment.Content);
               }
            }
        }
    }
message.IsRead = true;
message.Update(ConflictResolutionMode.AutoResolve); // push changes back to server
}

private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
     // The default for the validation callback is to reject the URL.
     bool result = false;
     Uri redirectionUri = new Uri(redirectionUrl);
     // Validate the contents of the redirection URL. In this simple validation
     // callback, the redirection URL is considered valid if it is using HTTPS
    // to encrypt the authentication credentials. 
    if (redirectionUri.Scheme == "https")
    {
       result = true;
    }
       return result;
}
0 голосов
/ 18 декабря 2018

Вы можете загрузить вложения, используя следующий код:

private void ThisApplication_NewMail()
{
    Outlook.MAPIFolder inBox = this.Application.ActiveExplorer()
        .Session.GetDefaultFolder(Outlook
        .OlDefaultFolders.olFolderInbox);
    Outlook.Items inBoxItems = inBox.Items;
    Outlook.MailItem newEmail = null;
    inBoxItems = inBoxItems.Restrict("[Unread] = true");
    try
    {
        foreach (object collectionItem in inBoxItems)
        {
            newEmail = collectionItem as Outlook.MailItem;
            if (newEmail != null)
            {
                if (newEmail.Attachments.Count > 0)
                {
                    for (int i = 1; i <= newEmail
                       .Attachments.Count; i++)
                    {
                        newEmail.Attachments[i].SaveAsFile
                            (@"C:\TestFileSave\" +
                            newEmail.Attachments[i].FileName);
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        string errorInfo = (string)ex.Message
            .Substring(0, 11);
        if (errorInfo == "Cannot save")
        {
            MessageBox.Show(@"Create Folder C:\TestFileSave");
        }
    }
}

Для получения дополнительной информации перейдите по этой ссылке:

Как: программно сохранять вложения из элементов электронной почты Outlook

...