Save E mail using different path.

Status
Not open for further replies.

Frédéric

Member
Outlook version
Outlook 2010 32 bit
Email Account
Exchange Server
Dear Developpers,

Wonderful website full of information.
I'm currently looking for a way to save email. Problem : Path will be change regarding both information, body and subject.
Each time a mail income in my Inbox, I would like to create a record of this mail on the network but path of recording will depends on a keyword placed in the body and name of the recorded email will depends on words in subject...

i already used this code :

Code:
Public Sub SaveMessageAsMsg()
    Dim oMail As Outlook.MailItem
    Dim objItem As Object
    Dim sPath As String
    Dim dtDate As Date
    Dim sName As String
    Dim enviro As String
    Dim strFolderpath As String
  
    enviro = CStr(Environ("USERPROFILE"))
'Defaults to Documents folder
' get the function at http://slipstick.me/u1a2d

strFolderpath = BrowseForFolder(enviro & "\documents\")
   
   For Each objItem In ActiveExplorer.Selection
   If objItem.MessageClass = "IPM.Note" Then
    Set oMail = objItem
    
  sName = oMail.Subject
  ReplaceCharsForFileName sName, "-"
  
  dtDate = oMail.ReceivedTime
  sName = Format(dtDate, "yyyy.mm.dd", vbUseSystemDayOfWeek, _
    vbUseSystem) & Format(dtDate, " - hh.nn.ss", _
    vbUseSystemDayOfWeek, vbUseSystem) & " - " & sName & ".msg"
      
  sPath = strFolderpath & "\"
  Debug.Print sPath & sName
  oMail.SaveAs sPath & sName, olMsg
   
  End If
  Next

End Sub

Private Sub ReplaceCharsForFileName(sName As String, _
  sChr As String _
)
  sName = Replace(sName, "'", sChr)
  sName = Replace(sName, "*", sChr)
  sName = Replace(sName, "/", sChr)
  sName = Replace(sName, "\", sChr)
  sName = Replace(sName, ":", sChr)
  sName = Replace(sName, "?", sChr)
  sName = Replace(sName, Chr(34), sChr)
  sName = Replace(sName, "<", sChr)
  sName = Replace(sName, ">", sChr)
  sName = Replace(sName, "|", sChr)

End Sub


Function BrowseForFolder(Optional OpenAt As Variant) As Variant
  Dim ShellApp As Object
  Set ShellApp = CreateObject("Shell.Application"). _
BrowseForFolder(0, "Please choose a folder", 0, OpenAt)
 
On Error Resume Next
    BrowseForFolder = ShellApp.self.Path
On Error GoTo 0
 
Set ShellApp = Nothing
    Select Case Mid(BrowseForFolder, 2, 1)
        Case Is = ":"
            If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
        Case Is = "\"
            If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
        Case Else
            GoTo Invalid
    End Select
Exit Function
 
Invalid:
BrowseForFolder = False
End Function
I actually don't need the Browse for Folder part... I would like Outlook decide by itself the path it will be used...Any idea ?

Thanks

Fred
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
If you don't need to browse, replace this with the path -
strFolderpath = "C\newpathhere"

As long as the path is almost always identical, and the keyword in the message is the folder name that changes, you could use something like "C:\path\" & keyword & "\" if they are totally different, you'll need to use either select case or an array to set the path. Using Arrays in Outlook macros
 

Frédéric

Member
Outlook version
Outlook 2010 32 bit
Email Account
Exchange Server
Thanks You Diane

I will explore this option

Thanks !

Fred
 

Frédéric

Member
Outlook version
Outlook 2010 32 bit
Email Account
Exchange Server
Hello Diane,

I would like rather to create one macro for each rules i made.
I still use this Macro

Code:
Public Sub SaveMessageAsMsg()

    Dim oMail As Outlook.MailItem
    Dim objItem As Object
    Dim sPath As String
    Dim dtDate As Date
    Dim sName As String
    Dim enviro As String
    Dim strFolderpath As String
 
    enviro = CStr(Environ("USERPROFILE"))
 
strFolderpath = BrowseForFolder(enviro & "\documents\")
  
   For Each objItem In ActiveExplorer.Selection
   If objItem.MessageClass = "IPM.Note" Then
    Set oMail = objItem
   
  sName = oMail.Subject
  ReplaceCharsForFileName sName, "-"
 
  dtDate = oMail.ReceivedTime
  sName = Format(dtDate, "yyyy.mm.dd", vbUseSystemDayOfWeek, vbUseSystem) & Format(dtDate, " - hh.nn.ss", vbUseSystemDayOfWeek, vbUseSystem) & " - " & sName & ".msg"
     
  sPath = strFolderpath & "\"
  Debug.Print sPath & sName
  oMail.SaveAs sPath & sName, olMsg
  
  End If
  Next

End Sub

Private Sub ReplaceCharsForFileName(sName As String, sChr As String)
  sName = Replace(sName, "'", sChr)
  sName = Replace(sName, "*", sChr)
  sName = Replace(sName, "/", sChr)
  sName = Replace(sName, "\", sChr)
  sName = Replace(sName, ":", sChr)
  sName = Replace(sName, "?", sChr)
  sName = Replace(sName, Chr(34), sChr)
  sName = Replace(sName, "<", sChr)
  sName = Replace(sName, ">", sChr)
  sName = Replace(sName, "|", sChr)

End Sub


Function BrowseForFolder(Optional OpenAt As Variant) As Variant
  Dim ShellApp As Object
  Set ShellApp = CreateObject("Shell.Application"). _
BrowseForFolder(0, "Please choose a folder", 0, OpenAt)

On Error Resume Next
    BrowseForFolder = ShellApp.self.Path
On Error GoTo 0

Set ShellApp = Nothing
    Select Case Mid(BrowseForFolder, 2, 1)
        Case Is = ":"
            If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
        Case Is = "\"
            If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
        Case Else
            GoTo Invalid
    End Select
Exit Function

Invalid:
BrowseForFolder = False
End Function
But i would like to avoid the browse to folder part. I'm looking for a way to change this macro. I don't need to select mail i wish to save and i don't need to tell Outlook where i wish to save. I just need Outlook to save regarding rules i gave to it ;)

Any idea ?

Thanks
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
Replace this line:
strFolderpath = BrowseForFolder(enviro & "\documents\")

with your path -
strFolderpath = enviro & "\documents\"
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
BTW, if you are using more than one rule and more than one path, you could have a lot of stub macros that set the value for strFolderpath (and remove the dim and set for omail, and the dim and set for the folder path) then call the SaveMessageAsMsg and pass the path.

Put this at the top of the module, outside of any macro:
Dim strFolderpath As String

and use this in the rule -
public sub rule1(item as outlook.mailitem)
strfolderpath = "c:\the path"
SaveMessageAsMsg oMail
end sub

rename the macro this:
Public Sub SaveMessageAsMsg(oMail as outlook.mailitem)
 

Frédéric

Member
Outlook version
Outlook 2010 32 bit
Email Account
Exchange Server
Replace this line:
strFolderpath = BrowseForFolder(enviro & "\documents\")

with your path -
strFolderpath = enviro & "\documents\"
Thanks Diane

What do you mean ?

Does it following ok ?

Public Sub SaveMessageAsMsg(oMail as outlook.mailitem)

Dim oMail As Outlook.MailItem
Dim objItem As Object
Dim sPath As String
Dim dtDate As Date
Dim sName As String
Dim enviro As String
Dim strFolderpath As String

enviro = CStr(Environ("USERPROFILE"))

strFolderpath = "H:\Control\07.delegates\02.Admin\Incoming Mails\Globes"
strFolderpath = enviro & "\documents\"

For Each objItem In ActiveExplorer.Selection
.......
...
..
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
you don't need both & the second one is the one outlook uses. If the first path is the path you want to use, delete the second line.
strFolderpath = "H:\Control\07.delegates\02.Admin\Incoming Mails\Globes"
strFolderpath = enviro & "\documents\"
 

Frédéric

Member
Outlook version
Outlook 2010 32 bit
Email Account
Exchange Server
Ok Diane

Thank you very much

So if i summarize, i put this code in a module :

Code:
Dim strFolderpath As String
Public Sub ruleGlobes(item As Outlook.MailItem)

strFolderpath = "H:\Function\07.delegates\02.Admin\Incoming Mails\Globes"
SaveGlobes oMail
End Sub

Public Sub SaveGlobes()

     Dim oMail As Outlook.MailItem
     Dim objItem As Object
     Dim sPath As String
     Dim dtDate As Date
     Dim sName As String
     Dim enviro As String
     Dim strFolderpath As String
 
    strFolderpath = "H:\Function\07.delegates\02.Admin\Incoming Mails\Globes"
 
    For Each objItem In ActiveExplorer.Selection
    If objItem.MessageClass = "IPM.Note" Then
     Set oMail = objItem
  
   sName = oMail.Subject
   ReplaceCharsForFileName sName, "-"

   dtDate = oMail.ReceivedTime
   sName = Format(dtDate, "yyyy.mm.dd", vbUseSystemDayOfWeek, vbUseSystem) & Format(dtDate, " - hh.nn.ss", vbUseSystemDayOfWeek, vbUseSystem) & " - " & sName & ".msg"
    
   sPath = strFolderpath & "\"
   Debug.Print sPath & sName
   oMail.SaveAs sPath & sName, olMsg
 
   End If
   Next

End Sub

Private Sub ReplaceCharsForFileName(sName As String, sChr As String)
   sName = Replace(sName, "'", sChr)
   sName = Replace(sName, "*", sChr)
   sName = Replace(sName, "/", sChr)
   sName = Replace(sName, "\", sChr)
   sName = Replace(sName, ":", sChr)
   sName = Replace(sName, "?", sChr)
   sName = Replace(sName, Chr(34), sChr)
   sName = Replace(sName, "<", sChr)
   sName = Replace(sName, ">", sChr)
   sName = Replace(sName, "|", sChr)

End Sub
then, i create as module as i need without forgeting to update "Globes" and path for others module, and finaly i add Outlook rules the "run a script" function for each of modules/rules...

That's right ?

I just have doubts regarding this line :

For Each objItem In ActiveExplorer.Selection

Because i wish a save for New Email, not for selected.

Fred
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
you need to remove the dim/set for omail and the for each /next lines.

if by this >> I would like rather to create one macro for each rules i made.

you have more than one rule and need to use a different path with each rule, having the macros split will allow you to do it with the least amount of code.

Public Sub rule1(item As Outlook.MailItem)
strFolderpath = "H:\Function\07.delegates\02.Admin\Incoming Mails\Globes"
SaveGlobes oMail
End Sub

Public Sub rule2(item As Outlook.MailItem)
strFolderpath = "H:\Function\07.delegates\02.Admin\Incoming Mails\somethingelse"
SaveGlobes oMail
End Sub



if you are using the same script, it's less useful to break it in two, but can speed up rules because it hands off to another macro.

This should work -

Code:
Dim strFolderpath As String
Public Sub ruleGlobes(item As Outlook.MailItem)

strFolderpath = "H:\Function\07.delegates\02.Admin\Incoming Mails\Globes"
SaveGlobes oMail
End Sub

Public Sub SaveGlobes(oMail as outlook.mailitem)
     Dim sPath As String
     Dim dtDate As Date
     Dim sName As String
   sName = oMail.Subject
   ReplaceCharsForFileName sName, "-"

   dtDate = oMail.ReceivedTime
   sName = Format(dtDate, "yyyy.mm.dd", vbUseSystemDayOfWeek, vbUseSystem) & Format(dtDate, " - hh.nn.ss", vbUseSystemDayOfWeek, vbUseSystem) & " - " & sName & ".msg"
   
   sPath = strFolderpath & "\"
   Debug.Print sPath & sName
   oMail.SaveAs sPath & sName, olMsg
   End If
   Next

End Sub
 

Frédéric

Member
Outlook version
Outlook 2010 32 bit
Email Account
Exchange Server
Thanks Diane !

I try it and come back to you

Fred
 

Frédéric

Member
Outlook version
Outlook 2010 32 bit
Email Account
Exchange Server
Dear Diane,

Here is my code. Whole lines are pasted in "ThisOutlookSession" and i have no other things in the project (no Module, No Class...)

First part is "regle part" (Means Rules Part). I use it for Outlook Rules. For example when an incoming mail with "Flobes" comes, rule runs in order to move .msg in sub-folders and rule is also running a script. In this case, "regle_Flobes" Please note path is longer than showed and replaced by "XXX"

This macro is currently no able to save files... I'm sure i'm not far from. Have you got an idea ?

Thanks very much !

Code:
Sub regle_Tigaga(Mail As Outlook.MailItem)
      Call SavAs_mail_as_msg(oMail, "H:\XXX\Incoming Mails\Tigaga\")
End Sub

Sub regle_Flobes(Mail As Outlook.MailItem)
      Call SavAs_mail_as_msg(oMail, "H:\XXX\Incoming Mails\Flobes\")
End Sub

Sub regle_Venturion(Mail As Outlook.MailItem)
      Call SavAs_mail_as_msg(oMail, "H:\H:\XXX\Incoming Mails\Venturion\")
End Sub

Sub regle_Bultitest(Mail As Outlook.MailItem)
      Call SavAs_mail_as_msg(oMail, "H:\XXX\Incoming Mails\Bultitest\")
End Sub

Sub regle_Neregord(Mail As Outlook.MailItem)
     Call SavAs_mail_as_msg(oMail, "H:\XXX\Incoming Mails\Neregord\")
End Sub
-------------------------------------------------------------------------------------------------------------------------------------
Sub SavAs_mail_as_msg(MyMail As Outlook.MailItem, repertoire)
'---------------------------------------------------------------------------------------
' Procedure : SavAs_mail_as_msg
' Author  : Oliv
  
  dtDate = MyMail.ReceivedTime
  mlSubj = MyMail.Subject
  NomExport = Format(dtDate, "yyyy.mm.dd", vbUseSystemDayOfWeek, vbUseSystem) & " - " & Format(dtDate, "hhnnss", vbUseSystemDayOfWeek, vbUseSystem) & " - " & mlSubj
 
  If Right(repertoire, 1) <> "\" Then repertoire = repertoire & "\"

  Call waaps_creedir(repertoire)
 
  PathNomExport = repertoire & "Email" & Left(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace( _
  NomExport, "\", ""), "/", ""), ":", ""), "*", ""), "?", ""), "<", ""), ">", ""), "|", ""), ".", ""), """", ""), vbTab, ""), Chr(7), ""), 160) & ".msg"
 
  n = 1
  MemPath = PathNomExport
  
  While Dir(PathNomExport) <> ""
  
  MsgBox "Le fichier " & vbCr & PathNomExport & vbCr & "existe déjà", vbInformation
  PathNomExport = Left(MemPath, Len(MemPath) - 4) & "(" & n & ")" & ".msg"
  n = n + 1
 
  Wend
  MyMail.SaveAs PathNomExport, OlSaveAsType.olMsg

End Sub
-----------------------------------------------------------------------------------------
Function waaps_creedir(lerep As String) As Boolean

  Dim FSO As FileSystemObject, i As Integer, retour As Boolean
  Dim rp As String, r
 
  Set FSO = CreateObject("Scripting.filesystemobject")
 
  rp = Replace(lerep, "\", "/")
  rp = Replace(rp, "//", "/")
  rep = Split(rp, "/")
  r = REP_TOP
  retour = True
  For i = 0 To UBound(rep)
  If (rep(i) <> "") Then
  r = r & rep(i) & "\"
  If (Not FSO.FolderExists(r)) Then
  FSO.CreateFolder (CStr(r))
  If (Not FSO.FolderExists(r)) Then retour = False
  End If
  End If
  Next
  Set FSO = Nothing
  waaps_creedir = retour
End Function
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
Does the msgbox show the correct path where the message is to be saved?

MsgBox "Le fichier " & vbCr & PathNomExport & vbCr & "existe déjà", vbInformation
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
ok... using this to tyest it on the selected message
Code:
Sub RunScript()
Dim objApp As Outlook.Application
Dim objItem As MailItem
Set objApp = Application
Set objItem = objApp.ActiveExplorer.Selection.Item(1)
'macro name you want to run goes here
regle_Tigaga objItem
End Sub

And this code - (i got an error on oMail and changed it to Mail)
Code:
Sub regle_Tigaga(Mail As Outlook.MailItem)
      MsgBox Mail.Subject
      Call SavAs_mail_as_msg(Mail, "C:\Users\drcp\Documents\test\")
End Sub
It worked when i removed this line -
'Call waaps_creedir(repertoire)

This is the filename that was saved:
Email20160401 - 002001 - Exchange Messaging Outlook Meeting Request Tracking.msg
 

Frédéric

Member
Outlook version
Outlook 2010 32 bit
Email Account
Exchange Server
Ok Diane, so if i understand, in "ThisOutlookSession" i paste

Code:
Sub RunScript()
Dim objApp As Outlook.Application
Dim objItem As MailItem
Set objApp = Application
Set objItem = objApp.ActiveExplorer.Selection.Item(1)
'macro name you want to run goes here
regle_Tigaga objItem
End Sub
and

Code:
Sub regle_Tigaga(Mail As Outlook.MailItem)
      MsgBox Mail.Subject
      Call SavAs_mail_as_msg(Mail, "C:\Users\drcp\Documents\test\")
End Sub
and

Code:
Sub SavAs_mail_as_msg(MyMail As Outlook.MailItem, repertoire)
'---------------------------------------------------------------------------------------
' Procedure : SavAs_mail_as_msg
' Author    : Oliv
' Date      : 12/02/2016
' Purpose   :
'---------------------------------------------------------------------------------------
'
' exemple repertoire = "c:\mail\"
    'Ici on construit le nom du fichier qui sera créé
 
    dtDate = MyMail.ReceivedTime
    mlSubj = MyMail.Subject
    NomExport = Format(dtDate, "yyyy.mm.dd", vbUseSystemDayOfWeek, vbUseSystem) & " - " & Format(dtDate, "hhnnss", vbUseSystemDayOfWeek, vbUseSystem) & " - " & mlSubj
    'Ici on vérifie le répertoire où l'enregistrer
    If Right(repertoire, 1) <> "\" Then repertoire = repertoire & "\"
    'Ici on supprime les caractères non autorisé dans les noms de fichiers
    PathNomExport = repertoire & "Email" & Left(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace( _
    NomExport, "\", ""), "/", ""), ":", ""), "*", ""), "?", ""), "<", ""), ">", ""), "|", ""), ".", ""), """", ""), vbTab, ""), Chr(7), ""), 160) & ".msg"
    'Ici on vérifie que le fichier n'existe pas déjà sinon il serait écrasé
    n = 1
    MemPath = PathNomExport
    While Dir(PathNomExport) <> ""
        MsgBox "Le fichier " & vbCr & PathNomExport & vbCr & "existe déjà", vbInformation
        PathNomExport = Left(MemPath, Len(MemPath) - 4) & "(" & n & ")" & ".msg"
        n = n + 1
    Wend
    MyMail.SaveAs PathNomExport, OlSaveAsType.olMsg
End Sub
without pasting the "waaps_creedir function"
and i assign "rule_Tigaga" as script in the Tigaga Outlook rule setting.

Right ?

Thanks!

Fred
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
The first macro (RunScript) is used to trigger the run a script macro manually so you don't have to send test messages. Paste it at the bottom of ThisOutlookSession or in a module - run a scripts can either be in a module or in thisoutlooksession (and sometimes work better in a module).

Add a msgbox to the script the rule calls, so you know if it is being triggered (after the first time, you'll want to remove it - it's annoying :)). Select a message, run the RunScript macro - it triggers the script, pops up the message box and calls the savas_mail macro.
 

Frédéric

Member
Outlook version
Outlook 2010 32 bit
Email Account
Exchange Server
Dear Diane,

Thank you to spend time for explaination. I finally found a way (with many help of Diane and Oliv').
This code allows to set scripts to Outlook rules (Règle 1, Régle 2....) and ask Outlook to save incoming mails (.msg) in différent paths, according mail body or subject (depending what you defined in Outlook rule).

Main idea of most of my saving rules are :

Apply this rule after the message arrives
from "sender"
and sent to "recipient"
and with "xxxxxx" in the body
move it to "yyyyyyy" folder
and run Project1.rule_Tigaga


So when a mail incomes, regarding words in body, Outlook will execute rule, which by itself execute VBA Code.

The code :

Code:
'-------------------------------------------------Les scripts devant être associés aux règles Outlook----------------------------
'----------------------Règle 1-------------------------------------------------------------------------------------------------------
Sub rule_Tigaga(Mail As Outlook.MailItem)
    FundType = "MC - Tigaga"
    Call SavMsgFundType(Mail, "H:\XXX\Incoming Mails\MC - Tigaga\", FundType)
End Sub
'----------------------Règle 2-------------------------------------------------------------------------------------------------------
Sub rule_Flobes(Mail As Outlook.MailItem)
    FundType = "MC - Flobes"
    Call SavMsgFundType(Mail, "H:\XXX\Incoming Mails\MC - Flobes\", FundType)
End Sub
'----------------------Règle 3-------------------------------------------------------------------------------------------------------
Sub rule_Venturion(Mail As Outlook.MailItem)
    FundType = "MC - Venturion"
    Call SavMsgFundType(Mail, "H:\XXX\MC - Venturion\", FundType)
End Sub
'----------------------Règle 4-------------------------------------------------------------------------------------------------------
Sub rule_MI(Mail As Outlook.MailItem)
    FundType = "MI"
    Call SavMsgFundType(Mail, "H:\XXX\Incoming Mails\MI\", FundType)
End Sub
'----------------------Règle 5-------------------------------------------------------------------------------------------------------
Sub rule_Alter(Mail As Outlook.MailItem)
    FundType = "MI - Alter"
    Call SavMsgFundType(Mail, "H:\XXX\Incoming Mails\MI - Alter\", FundType)
End Sub
'----------------------Règle 6-------------------------------------------------------------------------------------------------------
Sub rule_HF(Mail As Outlook.MailItem)
    FundType = "Neregord Funds"
    Call SavMsgFundType(Mail, "H:\XXX\Incoming Mails\HF\", FundType)
End Sub
'-------------------------------------------------Les macros étant appelées par les scripts---------------------------------------
'----------------------Macro 1-------------------------------------------------------------------------------------------------------
Sub SavMsgFundType(MyMail As Outlook.MailItem, repertoire, FundType)
'Construction du nom de fichier sauvegardé
    dtDate = MyMail.ReceivedTime
    mlSubj = MyMail.subject
    NomExport = Format(dtDate, "yyyy.mm.dd", vbUseSystemDayOfWeek, vbUseSystem) & " - " & Format(dtDate, "hh.nn.ss", vbUseSystemDayOfWeek, vbUseSystem) & " - " & FundType & " - " & mlSubj
    'Ici on vérifie le répertoire où l'enregistrer
    If Right(repertoire, 1) <> "\" Then repertoire = repertoire & "\"
    'Ici on supprime les caractères non autorisé dans les noms de fichiers
    PathNomExport = repertoire & Left(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace( _
                                                                                                                              NomExport, "\", ""), "/", ""), ":", ""), "*", ""), "?", ""), "<", ""), ">", ""), "|", ""), ".", "."), """", ""), vbTab, ""), Chr(7), ""), 160) & ".msg"
    'Ici on vérifie que le fichier n'existe pas déjà sinon il serait écrasé
    n = 1
    MemPath = PathNomExport
    While Dir(PathNomExport) <> ""
        'MsgBox "Le fichier " & vbCr & PathNomExport & vbCr & "existe déjà", vbInformation
        PathNomExport = Left(MemPath, Len(MemPath) - 4) & "(" & n & ")" & ".msg"
        n = n + 1
    Wend
    MyMail.SaveAs PathNomExport, OlSaveAsType.olMSG
End Sub
Thanks Diana !

Fred
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
Not to break what is working but.... it's recommended that run a script rules only contain conditions, that all actions are in the script. Adding the move to action to the script isn't difficult. Additionally, it would be possible to move either recipient or sender to the script and using just one rule, one script. (Putting both in the script would mean you'd process all mail with the script - which could be slow if you get a lot of mail.)

Apply this rule after the message arrives
from "sender"
and sent to "recipient"
and with "xxxxxx" in the body
move it to "yyyyyyy" folder
and run Project1.rule_Tigaga

This is probably not the best example for your needs, but it shows one way to do it: Outlook AutoReplies: One script, many responses

In your case, I would probably use a Select Case
Select Case olmail.senderemailaddress
Case "a@b.com"
FundType = "MC - Tigaga"
' if the path is always the same down to the last folder, you could just have the folder name here
' if the last folder is always the fund type, you don't this at all.
repertoire = "H:\XXX\Incoming Mails\MC - Tigaga\"

Case "b@c.com"
FundType = "MI"
repertoire = "H:\XXX\Incoming Mails\MI\"

end select

if you just needed the fund type variable, you could set the path in the main macro like this:
repertoire = "H:\XXX\Incoming Mails\" & FundType & "\"
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
This is my version - the rule is running on all messages in my test mailbox (because it's a test mailbox and gets very little mail) and checking the sender address in the macro.

The beauty of this is one rule, one macro. You can easily add more funds as case statements without adding more rules.

If this part changes with each fundtype: H:\XXX\Incoming Mails, then the repertoire line goes in each case.

Code:
Sub SavMsgFundType(Mail As Outlook.MailItem)
'Construction du nom de fichier sauvegardé
    dtDate = Mail.ReceivedTime
    mlSubj = Mail.Subject
    NomExport = Format(dtDate, "yyyy.mm.dd", vbUseSystemDayOfWeek, vbUseSystem) & " - " & Format(dtDate, "hh.nn.ss", vbUseSystemDayOfWeek, vbUseSystem) & " - " & FundType & " - " & mlSubj
    'Ici on vérifie le répertoire où l'enregistrer
   
Select Case Mail.SenderEmailAddress
Case "alias1@slipstick.com"
FundType = "MC - Tigaga"

Case "alias2@cdolive.com"
FundType = "MI"

Case "alias3@slipstick.com"
FundType = "MC"

End Select
   
   
    repertoire = "C:\Users\Diane\Documents\Macro Test\" & FundType & "\"
   
   
    'Ici on supprime les caractères non autorisé dans les noms de fichiers
    PathNomExport = repertoire & Left(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace( _
                                                                                                                              NomExport, "\", ""), "/", ""), ":", ""), "*", ""), "?", ""), "<", ""), ">", ""), "|", ""), ".", "."), """", ""), vbTab, ""), Chr(7), ""), 160) & ".msg"
    'Ici on vérifie que le fichier n'existe pas déjà sinon il serait écrasé
    n = 1
    MemPath = PathNomExport
    While Dir(PathNomExport) <> ""
        'MsgBox "Le fichier " & vbCr & PathNomExport & vbCr & "existe déjà", vbInformation
        PathNomExport = Left(MemPath, Len(MemPath) - 4) & "(" & n & ")" & ".msg"
        n = n + 1
    Wend
    Mail.SaveAs PathNomExport, OlSaveAsType.olMSG
End Sub
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
oops... i forgot the move message lines. (the rule can handle the words in the body part or it can be added to the macro.)

Add this at the end - it assumes the folder name = the fund name and it's under the Inbox (but it can use any folder, we'd just need to set the path). If the folder name is not the fund name or the path varies with each fund, set the folder name variable in the case statement. If it's always the same folder, use objFolder.Folders("folder name")

Set objFolder = Session.GetDefaultFolder(olFolderInbox)
Set objDestFolder = objFolder.Folders(FundType)
Mail.Move objDestFolder



Code:
Sub SavMsgFundType(Mail As Outlook.MailItem)
'Construction du nom de fichier sauvegardé
    dtDate = Mail.ReceivedTime
    mlSubj = Mail.Subject
    NomExport = Format(dtDate, "yyyy.mm.dd", vbUseSystemDayOfWeek, vbUseSystem) & " - " & Format(dtDate, "hh.nn.ss", vbUseSystemDayOfWeek, vbUseSystem) & " - " & FundType & " - " & mlSubj
    'Ici on vérifie le répertoire où l'enregistrer


Select Case Mail.SenderEmailAddress
Case "alias1@slipstick.com"
FundType = "MC - Tigaga"

Case "alias2@cdolive.com"
FundType = "MI"

Case "alias3@slipstick.com"
FundType = "MC"

End Select
  
    repertoire = "C:\Users\Diane\Documents\Macro Test\" & FundType & "\"
  
    'Ici on supprime les caractères non autorisé dans les noms de fichiers
    PathNomExport = repertoire & Left(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace( _
                                                                                                                              NomExport, "\", ""), "/", ""), ":", ""), "*", ""), "?", ""), "<", ""), ">", ""), "|", ""), ".", "."), """", ""), vbTab, ""), Chr(7), ""), 160) & ".msg"
    'Ici on vérifie que le fichier n'existe pas déjà sinon il serait écrasé
    n = 1
    MemPath = PathNomExport
    While Dir(PathNomExport) <> ""
        'MsgBox "Le fichier " & vbCr & PathNomExport & vbCr & "existe déjà", vbInformation
        PathNomExport = Left(MemPath, Len(MemPath) - 4) & "(" & n & ")" & ".msg"
        n = n + 1
    Wend
    Mail.SaveAs PathNomExport, OlSaveAsType.olMSG
  
'Dim objFolder As Outlook.Folder
'Dim objDestFolder As Outlook.Folder
Set objFolder = Session.GetDefaultFolder(olFolderInbox)
Set objDestFolder = objFolder.Folders(FundType)
Mail.Move objDestFolder

End Sub
 
Status
Not open for further replies.
Thread starter Similar threads Forum Replies Date
J Save E-mail attachments in a specific folder Outlook VBA and Custom Forms 0
L Save Mail Message to new folder created automatically Outlook VBA and Custom Forms 1
P How to save sent mail and forward it the next day Exchange Server Administration 3
D VBA Script (Ask to where to save send mail) Outlook VBA and Custom Forms 1
K Ask about a simple script about save a incoming mail as file on local PC Outlook VBA and Custom Forms 3
F CAN'T SAVE OUTLOOK 2010 E-MAIL TEMPLATE (.oft) Using Outlook 1
S Save an attachment back to the original e-mail. Using Outlook 2
C Linking e-mail messages to Business Contact Manager records does not save the attachments in the ema Using Outlook 1
L Can not get Outlook to save e-mail account passwords. If I put passwords in manually system works fine, but when I close Outlook and reopen I have to Using Outlook 1
H Won't save a copy of every piece of sent mail? Using Outlook 7
M how to save incoming mail in TRUE csv format Outlook VBA and Custom Forms 1
B Save e-mail to .msg file Outlook VBA and Custom Forms 4
S how to disable security message in save attachments macro "A programis trying to access e-mail addre Outlook VBA and Custom Forms 5
S Outlook (2016 32bit; Gmail IMAP) - Save sent message to Outllook Folder Outlook VBA and Custom Forms 0
P Outlook pst file is too huge with POP3. How to save more space? Using Outlook 4
D Prevent popup of "Do you want to save changes?" when closing after opening an appointment to view Outlook VBA and Custom Forms 2
A Unable to save recurring Meeting to Documents folder due to error Using Outlook 2
M Outlook 2013 Script Assistance - Save Opened Link with Subject Added Outlook VBA and Custom Forms 1
R Use an ItemAdd to Save Attachments on Arrival Outlook VBA and Custom Forms 0
W Outlook Calendar does not save view any longer! Using Outlook 3
S automate save the .xlxs file to share Network Using Outlook 1
S save email from excel Outlook VBA and Custom Forms 1
Y Open and Save Hyperlink Files in multiple emails Outlook VBA and Custom Forms 9
9 Outlook 2016 How to save an Outlook attachment to a specific folder then delete the email it came from? Using Outlook 1
O Save attachments using hotkey without changing attributes Outlook VBA and Custom Forms 1
geofferyh Cannot get Macro to SAVE more than one message attachment??? Outlook VBA and Custom Forms 5
N Open & Save VBAProject.Otm using VBA Code Outlook VBA and Custom Forms 1
R VBA | Chosing path to save file Outlook VBA and Custom Forms 1
W Save and rename outlook email attachments to include domain name & date received Outlook VBA and Custom Forms 4
V Change default default save location to Quick Access Using Outlook 1
W Save Outlook attachment in network folder and rename to current date and time Outlook VBA and Custom Forms 18
C Change default "Save Sent Item To" folder Outlook VBA and Custom Forms 9
C Outlook - cannot save subject line changes Using Outlook 2
I Outlook 2016 64bit - on receipt convert emails into PDF and save Outlook VBA and Custom Forms 2
V VB script code to save a specific email attachment from a given email Outlook VBA and Custom Forms 14
C Auto save outlook attachments when email is received Outlook VBA and Custom Forms 1
N editing drafts - won't let me save Using Outlook 12
nathandavies Email Details to Excel & Save as .MSG on one macro - combination of 2 macros Outlook VBA and Custom Forms 3
C Need VBA code to automatically save message outside outlook and add date Outlook VBA and Custom Forms 1
D Save Sent Item to Using Outlook 0
Diane Poremsky Save Selected Email Message as .msg File New Slipstick.com Articles 11
Diane Poremsky Export (Save) Outlook Contact photos New Slipstick.com Articles 0
Diane Poremsky Save Messages and Attachments to a New Folder New Slipstick.com Articles 0
B Delete/replace old files and save new attachments Using Outlook 1
E Outlook 2016 and Numerous Prompts to Save Emails Using Outlook 3
Diane Poremsky Save Outlook Email as a PDF New Slipstick.com Articles 0
Diane Poremsky Edit and Save Outlook's Read-Only Attachments New Slipstick.com Articles 0
Diane Poremsky Save Attachments to the Hard Drive New Slipstick.com Articles 2
B VBA Help Email that will save as draft and send as attachment Outlook VBA and Custom Forms 3
C Save Subject of Received Email as a String Outlook VBA and Custom Forms 1
Similar threads


















































Top