Search code examples
c#outlookvstomailitem

How do I save outlook Mailitem as sent mail


I have created an Outlook mail item and want to save it in a folder as a sent mail. I was able to set sender mail using mail.SentOnBehalfofName. How do I add Date field to this. I have some eml emails which I want to add to folder without a paid library. I was able to parse and save it to an outlook folder but the date field is set to None. Can someone help either to set the date field to the outlook mailitem object or a way to create mail Items that can be saved in outlook with all the properties?


Solution

  • Firstly, item's sent state can only be changed before it is saved for the very first time (MAPI limitation). Secondly, Outlook always creates olMailItem objects in the unsent state. The only item created in the sent state is the PostItem (olPostItem). You can create a PostItem, change its MessageClass property to "IPM.Note", save it, then release it using Marshal.ReleaseComObject (to make sure Outlook forgets about it), then reopen it by calingNamespace.GetItemFromID - this time Outlook should return back a MailItem object (instead of the original PostItem).

    Keep in mind that the icon will be wrong, hence the post icon needs to be removed - delete the PR_ICON_INDEX property (DASL name http://schemas.microsoft.com/mapi/proptag/0x10800003) using MailItem.PropertyAccessor.DeleteProperty.

    Also keep in mind that Outlook will not let you set some properties it considers "important" - such as the message dates, sender entry id, etc. And setting just the SentOnBehalfOfName property won't be enough - the sender entry ids must be set, or the user won't be able to correctly reply to that message.

    If using Redemption (I am its author) is an option, creating a message in the sent state is as easy as

      set Session = CreateObject("Redemption.RDOSession")
      Session.MAPIOBJECT = Application.Session.MAPIOBJECT
      set Inbox = Session.GetDefaultFolder(olFolderInbox)
      set Msg = Inbox.Items.Add
      Msg.Sent = true
      set CU = Session.CurrentUser
      set recip = Msg.Recipients.AddEx(CU.Name, CU.SmtpAddress, "SMTP", olTo)
      Msg.Subject = "fake received message"
      Msg.Body = "just a test"
      vSenderEntryId = Session.AddressBook.CreateOneOffEntryID("Joe The Sender", "SMTP", "[email protected]", false, true)
      set vSender = Session.AddressBook.GetAddressEntryFromID(vSenderEntryId)
      Msg.Sender = vSender
      Msg.SentOnBehalfOf = vSender
      Msg.SentOn = Now
      Msg.ReceivedTime = Now
      Msg.Save