Save Outlook Mailitem to local folder - excel

The following code does everything I want: pulls email, saves attachments, extracts files
EXCEPT save the original email to the folder fDest. I seem unable to see the solution.
This seems to be the problematic line as it won't save the email:
"mi.SaveAs fDest2, olMSG"
Sub SaveAttachments()
Dim ol As Outlook.Application
Dim ns As Outlook.Namespace
Dim fol As Outlook.Folder
Dim i As Object
Dim mi As Outlook.MailItem
Dim at As Outlook.Attachment
Dim Inbox As MAPIFolder
Dim strDate As String
Dim oApp As Object
Dim fDest As Variant
Dim j As Variant
Dim sh As String
Dim FileDialog As FileDialog
Dim Tracker As Workbook
Dim fSheet As Sheets
Dim LastRow As Long
Dim strFilePath
Dim fTracker As Workbook
strDate = InputBox("Enter Date in format dd-Mmm-yyyy", "User Date", Format(Now(), "dd-Mmm-yyyy"))
strFilePath = "\\namdfs\CARDS\MWD\GROUPS\GCM_NAM\2021\05 May\"
fTrackerName = "Inquiry.Tracker.SWPA.Violations.May.2021.xlsx" '
On Error Resume Next
Set fTracker = Workbooks(fTrackerName)
'If Err Then Set fTracker = Workbooks.Open(strFilePath & fTrackerName)
On Error GoTo 0
'Windows(fTrackerName).Activate
Set ol = New Outlook.Application
Set ns = ol.GetNamespace("MAPI")
Set fol = ns.Folders("GCMNamLogs").Folders("Inbox")
fDest = "C:\Users\jb76991\Desktop\Violations_Emails\"
fUser = UCase(Environ("username")) & ":" & Chr(10) & Now()
For Each i In fol.Items.Restrict("#SQL=urn:schemas:httpmail:subject LIKE '%" & strDate & "%'")
'Debug.Print fDest & i & ".msg"
If i.Class = olMail Then
Set mi = i
fDest2 = fDest & mi.Subject & ".msg"
mi.SaveAs fDest2, olMSG
For Each at In mi.Attachments
'do something with attachments but i've commented it out
Next at
End If
Next i
MsgBox ("Completed")
End Sub
Can anyone tell me how to save the original emails that are being filtered?

You must be sure there are no invalid characters in the filename. See What characters are forbidden in Windows and Linux directory names? for more information. So, I'd suggest using the Replace method available in VBA before passing anything to the SaveAs method.
Another point is that you need to specify unique file names to each email. Make sure the generated file name is unique for a folder.

Related

How to pull emails from Outlook to Excel starting with the most recent email?

My code takes account of the date of the email versus my threshold. For example, if I set my threshold to 4/1/2020, it will put all emails from 4/1/2020 to today.
My code is slow because it starts with my oldest email. How do I start the indexing with the most recent email?
The code I found online using items.sort "CreationDate", true doesn't work because it removes the date completely.
I've simplified the code:
Sub dateextract()
Dim OutlookApp As Outlook.Application
Dim Outlooknamespace As Namespace
Dim folder As MAPIFolder
Dim subfolder As MAPIFolder
Dim OutlookMail As Variant
Dim i As Long
Dim dates As Date
Dim time As Date
Dim sender As String
Set OutlookApp = New Outlook.Application
Set Outlooknamespace = OutlookApp.GetNamespace("MAPI")
Set folder = Outlooknamespace.GetDefaultFolder(olFolderInbox)
dates = Cells(1, 2).Value
i = 1
For Each OutlookMail In folder.Items
time = OutlookMail.ReceivedTime
If time >= dates Then
'........
Restrict and sort is the usual solution.
Sub dateextract()
' Early binding
' Reference Outlook XX.X Object Library
Dim outlookApp As Outlook.Application
Dim folder As folder
Dim outlookItem As Object
Dim i As Long
Dim dates As Date
Dim fldrItems As Items
Dim strFilter As String
Dim resItems As Items
Set outlookApp = New Outlook.Application
Set folder = Session.GetDefaultFolder(olFolderInbox)
' Unknown value and unknown format
'dates = Cells(1, 2).Value
' dates = Format("2020-01-04", "yyyy-mm-dd") '?
dates = Format("2021-01-04", "yyyy-mm-dd")
Set fldrItems = folder.Items
Debug.Print "fldrItems.Count: " & fldrItems.Count
strFilter = "[CreationTime] > '" & dates & "'"
Debug.Print strFilter
Set resItems = fldrItems.Restrict(strFilter)
Debug.Print "resItems.Count: " & resItems.Count
' Sort collections in memory, not items in folder
resItems.Sort "[CreationTime]", True
For i = 1 To resItems.Count
If resItems(i).Class = olMail Then
Set outlookItem = resItems(i)
Debug.Print i & ") " & outlookItem.CreationTime & ": " & outlookItem.Subject
End If
Next
End Sub

Return individual sender of archived mail for a shared mailbox

I have written a macro which pulls the emails from the 'Sent Items' of a particular mailbox in Outlook. I am using .SenderName property to populate senders name in Excel.
The mailbox is shared by a team, and is labeled as 'ResearchHub'.
The macro is working when I pull out mails for recent days.
When I try to draw the archived mails, the .SenderName property pulls out the sender as 'ResearchHub', not the person who sent the mail.
MailItem.SentOnBehalfOfName property is pulling Research Hub as the sender and not the individual name.
I tried unarchiving the emails by opening them and copying them in a different folder, yet was unsuccessful in fetching the particular user as sender name.
Option Explicit
Sub test()
Dim Result As Object
Dim i As Integer
Dim dstart As Date
Dim dend As Date
Dim lower As String
Dim upper As String
Dim limit As String
dstart = InputBox("Enter Start Date in dd/mmm/yyyy format")
dend = InputBox("Enter End Date in dd/mmm/yyyy format")
lower = "[ReceivedTime] > '" & Format(dstart, "ddddd") & " 12:00 AM" & "'"
upper = "[ReceivedTime] > '" & Format(dend, "ddddd") & " 12:00 AM" & "'"
limit = lower & " AND " & upper
Dim objoutlook As outlook.Application
Dim oStore As outlook.Store
Dim onjNSpace As outlook.Namespace
Dim objFolder As outlook.Folder
Dim oAccount As Account
Set objoutlook = CreateObject("Outlook.Application")
Set objNSpace = objoutlook.GetNamespace("MAPI")
For Each objFolder In objNSpace.Folders
If objFolder.Name = "Research Hub" Then
Dim myfolder As outlook.Folder
Set myfolder = objFolder.Folders("Sent Items")
Dim objitem As Object
Dim irow As Integer
irow = 2
Set Result = myfolder.Items.Restrict(limit)
If Result.Couunt > 0 Then
For i = 1 To Result.Count
Cells(irow, 1) = objitem.SenderName
Cells(irow, 2) = objitem.To
Cells(irow, 3) = objitem.Subject
irow = irow + 1
Next i
End If
End If
Next
Set objoutlook = Nothing
Set objNSpace = Nothing
Set myfolder = Nothing
End Sub
Use the MailItem.SentOnBehalfOfName property instead.

Save Multiple Email Attachments For Current Date Only

I am new to VBA. I have prepared one code to download multiple emails' attachments for current date only but whenever I execute this macro, it's giving me:
Automation Error, The system cannot find the specified path
Can someone look into below pasted code and help me out. Thanks
Sub Outlook_Attachments()
Dim OLOOK As Outlook.Application
Dim OMAIL As Outlook.MailItem
Dim ONS As Outlook.Namespace
Dim FOL As Outlook.Folder
Dim SFOLDER As String
Dim FNAME As String
Set OLOOK = New Outlook.Application
Set OMAIL = OLOOK.CreateItem(olMailItem)
Set ONS = OLOOK.GetNamespace("MAPI")
Set FOL = ONS.GetDefaultFolder(olFolderInbox).Folders("Test")
SFOLDER = "D:\"
FNAME = SFOLDER & Format(Date, "MM/DD/YYYY") & "*"
For Each OMAIL In FOL.Items
For Each ATMT In OMAIL.Attachments
ATMT.SaveAsFile FNAME & ATMT.DisplayName
Next
Next
End Sub
Try this:
Sub Outlook_Attachments()
Dim OLOOK As Outlook.Application
Dim OMAIL As Outlook.MailItem
Dim ONS As Outlook.Namespace
Dim FOL As Outlook.Folder
Dim SFOLDER As String
Dim FNAME As String
Set OLOOK = New Outlook.Application
Set OMAIL = OLOOK.CreateItem(olMailItem)
Set ONS = OLOOK.GetNamespace("MAPI")
Set FOL = ONS.GetDefaultFolder(olFolderInbox).Folders("Test")
SFOLDER = "D:\"
FNAME = SFOLDER & Format(Date, "MM-DD-YYYY") & "-"
For Each OMAIL In FOL.Items
'check email recevied date
If Format(OMAIL.ReceivedTime, "MM-DD-YYYY") = Format(Date, "MM-DD-YYYY") Then
For Each ATMT In OMAIL.Attachments
ATMT.SaveAsFile FNAME & ATMT.DisplayName
Next
End If
Next
End Sub
Using '/' and '*' in file/folder name is forbidden.

how to save the outlook instant search result emails in hard drive folder

I am trying to save all the emails, resulting out of instant text search into the hard drive folder. the below code is able to perform the search but giving me an error at selectallitems line while selecting each mail and saving them in HD. code is in excel vba;
Dim OlApp As Outlook.Application
Set OlApp = CreateObject("Outlook.Application")
Dim fldrpath As String
fldrpath = "\\mydata\EMAILS\
Check subfolder for messages and exit of none found
txtsearch = "abc#xyz.com, received:4/1/2017..4/30/2017"
OlApp.ActiveExplorer.Search txtsearch, olSearchScopeAllFolders
Dim myitem As Outlook.MailItem
Dim objitem As Object
Set myitem = OlApp.ActiveExplorer.SelectAllItems
Set objitem = myitem
objitem.SaveAs fldrpath & "test" & ".msg", olMSG
Any other alternative code to get the emails saved will also be appreciated.
Thanks in advance !! looking for a quick solution
Saving search results appears to be more easily achieved a different way.
From Outlook, not Excel.
Sub SearchForStr_Save()
Dim strSearch As String
Dim strDASLFilter As String
Dim strScope As String
Dim objItem As Object
Dim objSearch As search
Dim srchFolder As folder
Dim fldrpath As String
strSearch = "abc#xyz.com"
strDASLFilter = "urn:schemas:httpmail:textdescription LIKE '%" & strSearch & "%'"
strScope = "'Inbox'"
Set objSearch = AdvancedSearch(Scope:=strScope, filter:=strDASLFilter, SearchSubFolders:=True, Tag:="SearchFolder")
Set srchFolder = objSearch.Save(strSearch)
'fldrpath = "\\mydata\EMAILS\"
fldrpath = "h:\test\"
For Each objItem In srchFolder.Items
'Debug.Print objItem.subject
If objItem.Class = olMail Then
objItem.SaveAs fldrpath & "test" & ".msg", olMsg
End If
Next
ExitRoutine:
Set objSearch = Nothing
Set srchFolder = Nothing
End Sub

Attach created Word doc to Outlook Message

I have read numerous responses that are close to what I am looking for, but each time it doesn't work in my code.
This should be a pretty basic question, but I am hoping someone can look at this and see my error quickly.
I am using Excel to create a Word Doc which is then saved on the users Desktop in a folder named with the current date.
Everything works perfectly, but now all I am trying to do is add to the Word doc the name of the string "IRN" which is a cell in the Excel worksheet.
I also need to attach the created Word doc to an Outlook message.
I will only include the intro and end of my code as the body should not matter.
Sub TDOutlook()
Dim TD As Word.Application
Dim Doc As Word.Document
Dim path As String
Dim filename As String
Dim StudentName As String
Dim StudentAddress1 As String
Dim City As String
Dim MrMrs As String
Dim StudentLast As String
Dim IRN As String
Dim CourseReq As String
Dim CourseName As String
Dim CourseStart As String
Dim Cost As String
Dim Deferred As String
Dim Graphic As String
Dim Footer1 As Word.Range
Dim Body As Word.Paragraph
Dim OutApp As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
path = Environ("USERPROFILE") & "\Desktop\" & Format(Now, "mm-dd-yyyy")
On Error Resume Next
MkDir path
On Error GoTo 0
'Outlook
Set OutApp = CreateObject("Outlook.Application")
Set objOutlookMsg = OutApp.CreateItem(olMailItem)
objOutlookMsg.SentOnBehalfOfName = "bbb#ppp.edu"
objOutlookMsg.Subject = "FinServ-TD"
objOutlookMsg.HTMLBody = "Testing this macro" & vbCrLf & vbCrLf
'Display Outlook
objOutlookMsg.Display
'Opens Word
Set TD = CreateObject("Word.Application")
'Displays the document
TD.Visible = False
'Add New Document
Set Doc = TD.Documents.Add
filename = path & "\TD" '& IRN
Doc.SaveAs filename
'Attach Word to Outlook
objOutlookMsg.Attachments.Add Doc.filename <----This is broken
Doc.Close
TD.Quit
'Application.ScreenUpdating = True
End Sub
Everything works perfectly, but now all I am trying to do is add to the Word doc the name of the string "IRN" which is a cell in the Excel worksheet.
To get the Cell Value Try this
FileName = Path & "\TD" & Sheets("Sheet1").Range("A1").Text & ".docx"
I also need to attach the created Word doc to an Outlook message.
To attached saved file, change this
objOutlookMsg.Attachments.Add Doc.filename To this
ObjOutlookMsg.Attachments.Add (FileName)

Resources