Unable to find object when trying to attach mailitem

1

I'm writing a little app on c# to VisualStudio 2017 for Office 2010

Outlook.Application app = new Outlook.Application();
Outlook.MailItem SelectedMessage = (Outlook.MailItem)app.ActiveExplorer().Selection[1];
Outlook.MailItem newmail = app.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;

newmail.Subject = SelectedMessage.SenderEmailAddress + " - " + SelectedMessage.Subject;
newmail.To = SenderEmailVar;

newmail.Body += "Subject : " + SelectedMessage.Subject;
newmail.Body += "Received by : " + SelectedMessage.SendUsingAccount.SmtpAddress;
newmail.Body += "Sent by : " + SelectedMessage.SenderEmailAddress + "\n\n";

MessageBox.Show(SelectedMessage.Body);
newmail.Attachments.Add(SelectedMessage);
newmail.Send();

But I have an exception:

Unable to find object

Sorry it's in French (I tried to translate it).

System.Runtime.InteropServices.COMException occured. HResult=0x8004010F Message=Operation failed. Unable to find object. Source=Microsoft Outlook procedural call tree : Unable to evaluate the procedure call tree of the exception

It occurs on the newmail.Attachments.Add(SelectedMessage); line.

I can have the SelectedMessage.Subject, SelectedMessage.Body fine, so my selection is not empty.

MessageBox working fine, and body&subject of the new message contain the subject, sender, etc... So the selection seems to be working. But the source email is not attached.

What's wrong ?

Regards

c#
vsto
mailitem
asked on Stack Overflow Apr 4, 2017 by FolksR • edited Apr 4, 2017 by Stefan

1 Answer

0

Find a workaround :

First, i save the message locally to the disk

Then, attach this MSG file to the current email.

And delete the mail from the disk.

SelectedMessage.SaveAs(Path.GetTempPath() + "cmail.msg");
newmail.Attachments.Add(Path.GetTempPath() + "cmail.msg");
File.Delete(Path.GetTempPath() + "cmail.msg");

Probably not the best, but working fine. If someone can be better, i'm looking for :)

answered on Stack Overflow Apr 4, 2017 by FolksR

User contributions licensed under CC BY-SA 3.0