Attach a multiple files in VBA - vba

Help to modify the following code to be able to attach two file paths as attachments to send mail using MailCDO object in MS Access. Currently it's only attaching first file path only.
I tried using comma, using & sign and nothing seems to work.
Dim sSubject As String
Dim sFrom As String
Dim sTo As String
Dim sCC As String
Dim sBCC As String
Dim sBody As String
Dim sAttach As String
Dim sFilePath As String
Dim MailCDO
sFrom = "abc#abccom"
sCC = ""
sBCC = ""
sTo = "def#def.com"
sFilePath = "E:\Reports\Report1.xlsx"
sAttach = sFilePath
' Want to attach the second sFilePath2
sFilepath2= sFilePath = "E:\Reports\Report2.xlsx"
sSubject = "Subject"
sBody = "<p>Email Body</p>"
Set MailCDO = CreateObject("CDO.Message")
MailCDO.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
MailCDO.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
= "smtp.xxxyyy.com"
MailCDO.Configuration.Fields.Update
MailCDO.Subject = sSubject
MailCDO.FROM = sFrom
MailCDO.To = sTo
MailCDO.CC = sCC
MailCDO.BCC = sBCC
MailCDO.HTMLBody = sBody
MailCDO.AddAttachment sAttach
MailCDO.Send
Set MailCDO = Nothing
End Sub

you should try the with block for clean code
dim sFilepath as string, sFilepath2 as string
sFilePath = "E:\Reports\Report1.xlsx"
sFilepath2= "E:\Reports\Report2.xlsx"
With MailCDO
.Subject = sSubject
.FROM = sFrom
.To = sTo
.CC = sCC
.BCC = sBCC
.HTMLBody = sBody
.Attachments.add sFilePath
.Attachments.add sFilepath2
End with
you can also use for each loop in a collection to attach multiple files just like braX Suggested.

Related

How to get the Body of an email in a selection of emails?

The command to get the Body of the email is not pulling the body from the email, in a selection of emails, being processed in a loop.
How do I set the itm for the sText = itm.Body command?
Dim itm As Outlook.MailItem
Dim currentExplorer As Explorer
Dim Selection As Selection
Dim strFileName As String, strExt As String
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim email_date As Date
Dim date_ext As String
Dim sText As String
Dim Intext_date As String
Dim Mail_date As Date
Dim email_date_temp As String
saveFolder = "C:\elan\Various\email_attachments\"
Set currentExplorer = Application.ActiveExplorer
Set Selection = currentExplorer.Selection
For Each itm In Selection
For Each objAtt In itm.Attachments
strFileName = objAtt.DisplayName
' get the last 5 characters or last 4 for .xls for the file extension
strExt = Right(objAtt.DisplayName, 5)
If Mid(strExt, 1, 1) <> "." Then
strExt = Right(objAtt.DisplayName, 4)
End If
If strExt = ".xls" Or strExt = ".xlsx" Then
' clean the File Name
ReplaceCharsForFileName strFileName, "-"
' Get Body of email
Set itm = ActiveExplorer.Selection.item(1)
sText = itm.Body
Debug.Print sText
There is no need to set the itm object in the code in the following way:
Set itm = ActiveExplorer.Selection.item(1)
In your code the itm object is already assigned with each loop iteration:
For Each itm In Selection
So, the code could look like that:
For Each itm In Selection
For Each objAtt In itm.Attachments
strFileName = objAtt.DisplayName
' get the last 5 characters or last 4 for .xls for the file extension
strExt = Right(objAtt.DisplayName, 5)
If Mid(strExt, 1, 1) <> "." Then
strExt = Right(objAtt.DisplayName, 4)
End If
If strExt = ".xls" Or strExt = ".xlsx" Then
' clean the File Name
ReplaceCharsForFileName strFileName, "-"
' Get Body of email
sText = itm.Body
Debug.Print sText
Remember that you get the message body in the inner loop which means if you have multiple attached files you will get the same message body for each of them.

Saving E-Mails with Meeting Invitation From Outlook

I have the following VBA code macro to save all selected e-mails in .msg format to any folder but it doesn't save emails with meeting invitations. How do I also save mails with meeting invitations? Do I have to include any special objects? Below is the code that I am using to save the e-mails in .msg format:
Option Explicit
Public Sub SaveMessageAsMsg()
Dim xShell As Object
Dim xFolder As Object
Dim strStartingFolder As String
Dim xFolderItem As Object
Dim xMail As MailItem
Dim xObjItem As Object
Dim xPath As String
Dim xFileName As String
Dim xName As String
Dim xDtDate As Date
Set xShell = CreateObject("Shell.Application")
On Error Resume Next
' Bypass error when xFolder is nothing on Cancel
Set xFolder = xShell.BrowseForFolder(0, "Select a folder:", 0, strStartingFolder)
' Remove error bypass as soon as the purpose is served
On Error GoTo 0
If Not TypeName(xFolder) = "Nothing" Then
Set xFolderItem = xFolder.Self
xFileName = xFolderItem.Path
' missing path separator
If Right(xFileName, 1) <> "\" Then xFileName = xFileName & "\"
Else
xFileName = ""
Exit Sub
End If
For Each xObjItem In ActiveExplorer.Selection
If xObjItem.Class = olMail Then
Set xMail = xObjItem
xName = Left(CleanFileName(xMail.Subject), 100)
Debug.Print xName
xDtDate = xMail.ReceivedTime
xName = Format(xDtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
vbUseSystem) & "-" & xName & ".msg"
xPath = xFileName & xName
xMail.SaveAs xPath, olMSG
End If
Next
End Sub
Public Function CleanFileName(strFileName As String) As String
Dim Invalids
Dim e
Dim strTemp As String
Invalids = Array("?", "*", ":", "|", "<", ">", "[", "]", """", "/", "\")
strTemp = strFileName
For Each e In Invalids
strTemp = Replace(strTemp, e, " ")
'strTemp = Replace(strTemp, e, "")
Next
CleanFileName = strTemp
End Function
In the code posted above only mail items are handled:
If xObjItem.Class = olMail Then
There are various object types in Outlook, see OlObjectClass enumeration for more information.
Basically, you need to handle also meeting items:
Dim xMail As Object
If xObjItem.Class = olMail Or xObjItem.Class = olMeetingRequest Then

.Body in Outlook VBA is not getting text of plain text email

.Body of Mailitem is not returning anything
I am using the entryID to get access to the inbound email and set the object using Application.Session.GetItemFromID
strID = olitem.EntryID
Set olitem = Application.Session.GetItemFromID(strID)
Once I set olitem
Set olitem = Application.Session.GetItemFromID(strID)
it shows the email has been accessed, but when sText = olitem.Body is run stext ends up empty.
Here is the entire code that is fired from an Outlook Rule.
Sub ParseEPDMRequest(olitem As Outlook.MailItem)
Dim arr() As String
Dim ECONum As String
Dim ReqID As String
Dim sText As String
Dim strID As String
strID = olitem.EntryID
Set olitem = Application.Session.GetItemFromID(strID)
sText = olitem.Body
arr = Split(olitem.Body, ":")
arr = Split(arr(15), " ")
ECONum = GetECONum(arr(8))
sText = olitem.Subject
ReqID = GetReqId(sText)
Call TEAMtoEPDMPush(ECONum & ".xml", ReqID)
End Sub
Under certain circumstances the message can have no plain text body. You have to check the format of the body (see BodyFormat property):
strID = olitem.EntryID
Set olitem = Application.Session.GetItemFromID(strID)
If olitem.BodyFormat=OlBodyFormat.olFormatPlain Then
sText = olitem.Body
...
ElseIf olitem.BodyFormat=OlBodyFormat.olFormatHTML Then
...

Save emails based on keywords in email text

I want my emails saved to different folders on my hard drive based on what the email is about. Some emails should be saved in two or more folders.
The designated hard drive folders are created as they should, and files are saved with the right filenames, but all emails are saved in all folders.
If there is only one keyword from one 'category' present in the mail body. It seems like the script somehow 'remembers' the previously found keywords, even in the following If-Then statements - resulting in the email being saved in all folders.
I have edited the code based on your comments. It now gives
error 450: Wrong number of arguments.
Private WithEvents InboxItems As Outlook.Items
Option Explicit
Sub Application_Startup()
Dim xNameSpace As Outlook.NameSpace
Set xNameSpace = Outlook.Application.Session
Set InboxItems = xNameSpace.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub InboxItems_ItemAdd(ByVal objItem As Object)
'Define variables
Dim FSO
Dim xFilePath As String
Dim xFilePathAgro As String
Dim xFilePathGras As String
Dim xFilePathIndustrie As String
Dim xFilePathActief As String
Dim xFilePathOppTech As String
Dim xMailItem As Outlook.MailItem
Dim xRegEx
Dim xFileName As String
'Create directories if not existing
xFilePath = CreateObject("WScript.Shell").SpecialFolders(16)
xFilePath = xFilePath & "\MyEmails"
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(xFilePath) = False Then
FSO.CreateFolder (xFilePath)
End If
xFilePathAgro = CreateObject("WScript.Shell").SpecialFolders(16)
xFilePathAgro = xFilePath & "\WBSO 13-01A Agro-reststromen"
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(xFilePathAgro) = False Then
FSO.CreateFolder (xFilePathAgro)
End If
xFilePathGras = CreateObject("WScript.Shell").SpecialFolders(16)
xFilePathGras = xFilePath & "\WBSO 13-01B Grassen"
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(xFilePathGras) = False Then
FSO.CreateFolder (xFilePathGras)
End If
'Change filenames of emails to save
Set xRegEx = CreateObject("vbscript.regexp")
xRegEx.Global = True
xRegEx.IgnoreCase = False
xRegEx.Pattern = "\||\/|\<|\>|""|:|\*|\\|\?" 'Is vereist om de onderwerptitel op te nemen in bestandsnaam
If objItem.Class = olMail Then
Set xMailItem = objItem
xFileName = xRegEx.Replace(xMailItem.Subject, "")
xFileName = xRegEx.Replace(xMailItem.Subject, ":", "")
xFileName = xRegEx.Replace(xMailItem.Subject, "/", "_")
xFileName = xRegEx.Replace(xMailItem.Subject, "\", "")
xFileName = xRegEx.Replace(xMailItem.Subject, "<", "")
xFileName = xRegEx.Replace(xMailItem.Subject, ">", "")
xFileName = xRegEx.Replace(xMailItem.Subject, ";", "")
xFileName = Format(xMailItem.ReceivedTime, "YYYYMMDD hhmm") & " " & xFileName
'saving emails that contain the searchwords in the right folders
If InStr(1, xMailItem.Body, "Agro", vbTextCompare) > 0 Then
MsgBox "Opgeslagen in Agro"
'xMailItem.SaveAs xFilePathAgro & "\" & xFileName & ".msg"
End If
If InStr(1, xMailItem.Body, "Gras", vbTextCompare) > 0 Then
MsgBox "opgeslagen in Gras"
'xMailItem.SaveAs xFilePathGras & "\" & xFileName & ".msg"
End If
End If
End Sub

VBA Excel Macro won't email out - error

I have the following code to test to email out to specified email addresses. At present it won't work.
It says "Label not defined".
Sub GHF()
Dim CDO_Mail As Object
Dim CDO_Config As Object
Dim SMTP_Config As Variant
Dim strSubject As String
Dim strFrom As String
Dim strTo As String
Dim strCc As String
Dim strBcc As String
Dim strBody As String
Set ws = Sheets("Feedback")
ws.Select
strSubject = " Assessment Centre Feedback"
strFrom = "test#email.com"
strTo = Value & Range("M4").Value
strCc = ""
strBcc = ""
strBody = "Dear" & Value & Range("M4").Value & "Thank you for attending assesssment Centre. Please find attached your feedback from the day. Kind Regards, Employer"
Set CDO_Mail = CreateObject("CDO.Message")
On Error GoTo Error_Handling
Set CDO_Config = CreateObject("CDO.Configuration")
CDO_Config.Load -1
Set SMTP_Config = CDO_Config.Fields
With SMTP_Config
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "fermat.axiomtech.co.uk"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Item.Configuration.Fields.Update
End With
With CDO_Mail
Set .Configuration = CDO_Config
End With
End Sub
The name of the spreadsheet where the data sits is called "Feedback" and the Workbook is called "Feedback with Email"
Can anyone help with identifying what's up?
From address & Password
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "xyz#Email.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "123456"