I have a secondary exchange account where a server rule is active that forwards every mail it receives to my primary account (on another server). To avoid pointless forwarding headers and to preserve the From and To fields, I forward mails as an attachment and
I have three issues with this code and am a bit stuck, so I'm posting it here to hopefully get some input:
- I'd like to run attachment validation so only actual message types are unpacked to the Inbox. I've found the
.Type
property but this only gives me a number and I can't find the corresponding reference. If any non-message attachments (or no attachments) are found, the forwarding message should be saved or not deleted. - Items are created in the Inbox as drafts instead of received mail items. I can't find any way to change the document type.
- It seems like my code randomly creates empty messages in my Outbox. Perhaps this is due to opening the message from disk and not doing anything with it apart from moving it, but I can't really be sure right now. If an unpacked message has attachments, an empty draft with those attachments can be found in the Outbox.
Below I've posted the entire code, created largely thanks to information from an answer to a related question.
Public Sub unpackAttachedMessage(itm As Outlook.MailItem)
Dim olApp As New Outlook.Application
Dim olNameSpace As Outlook.NameSpace
Dim olTargetFolder As Outlook.Folder
Dim objAtt As Outlook.Attachment
' Program Configuration Variables and Constants
Const saveFolder As String = "C:\Temp\Outlook"
Const messageCategory As String = "CategoryName"
' Runtime Variables
Dim i As Integer
Dim attachmentCount As Integer
i = 1
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
' Folder creation does not seem to work.
If Not fso.FolderExists(saveFolder) Then
fso.CreateFolder (saveFolder)
End If
' For each attachment in the message.
For Each objAtt In itm.Attachments
' Save it to disk as a message.
objAtt.SaveAsFile saveFolder & "\" & i & ".msg"
' Retrieve a message from disk.
Dim message As Outlook.MailItem
Set message = Application.CreateItemFromTemplate(saveFolder & "\" & i & ".msg")
' Modify the Message.
' Note that this and potentially other message options need
' to be set BEFORE you move the item to its destination folder.
' Set the Category.
message.Categories = message.Categories & "," & messageCategory
' Mark as unread.
message.UnRead = True
' MsgBox "Class: " & itm.MessageClass & " --- Attached Item Class: " & message.MessageClass
' Doesn't work
'message.MessageClass = olPostItem
' Save changes to the message.
message.Save
' Move the item to Inbox.
Set olNameSpace = olApp.GetNamespace("MAPI")
Set olTargetFolder = olNameSpace.GetDefaultFolder(olFolderInbox)
message.Move olTargetFolder
' objAtt.DisplayName
Set objAtt = Nothing
i = i + 1
Next
attachmentCount = i
End Sub