Run a Script Rule: Change Subject then Forward Message

Last reviewed on October 27, 2014   —  224 comments

A visitor to our Outlook Forums wanted to know how to change a subject and forward a message using rules:

I want to create a rule that I can run on a folder containing a number of messages that forwards each message to a new email address (a dropbox for a database). I need to write my own subject line, so that the database will read the subject line and then know to parse the document and extract the required information.

You can do this using either VBA or a Run a Script rule. If you using a rule to move the messages to another folder, the run a script rule is probably the best and can easily forward mail meeting specific conditions. You can run the rule as messages arrive or run it on the messages in the folder at any time using Run Rules Now.

Outlook 2003 users will receive the dreaded "something is trying to access your address book. Allow?" message. To avoid this, install ClickYes or Mapilab's Advanced Security software. Both are free. Mapilab's product will bypass the dialog (after you OK it the very first time), while ClickYes does the clicking for you.

Run a Script Rule

Press Alt+F11 to open the VB Editor and paste the following code into ThisOutlookSession. Create the rule in Outlook and select the script.

Change subject and forward rule

Don't forget to change the subject and email address!

Sub ChangeSubjectForward(Item As Outlook.MailItem)
    Item.Subject = "Test"
 Item.Save
 
Set myForward = Item.Forward
myForward.Recipients.Add "alias@domain.com"

myForward.Send

End Sub

To Delete the Sent Copy of the Message

To delete (or not save) the sent copy after it is forwarded, use myForward.DeleteAfterSubmit = True before the Send command.

Sub ChangeSubjectForward(Item As Outlook.MailItem)

Set myForward = Item.Forward
myForward.Recipients.Add "alias@domain.com"

' To BCC an address or DL, try this:
'myForward.BCC = "alias"

myForward.DeleteAfterSubmit = True

myForward.Send

End Sub

"Change subject then forward" VBA Macro version

If you prefer a macro you can run on all messages in a folder at any time, use this code sample. This macro was put together using the script above and the code sample at Add a file number or keyword to the subject line of messages.

To use, paste into ThisOutlookSession and run, or add to a toolbar, ribbon, or QAT button.

Don't forget to change the subject and email address.

Sub ChangeSubjectThenSend()
Dim myolApp As Outlook.Application
Dim aItem As Object

Set myolApp = CreateObject("Outlook.Application")
Set mail = myolApp.ActiveExplorer.CurrentFolder

For Each aItem In mail.Items
      aItem.Subject = "New Subject"
    aItem.Save
    
    Set myForward = aItem.Forward
    myForward.Recipients.Add "alias@domain.com"
    myForward.Send

Next aItem
End Sub

Find a code in the message body, then forward

This example combines the first script above with the macro at Use RegEx to extract text from an Outlook email message to look for a tracking code in the message body, then forward the message and include the code in the message subject.


Sub CodeSubjectForward(Item As Outlook.MailItem)

' Set reference to VB Script library
' Microsoft VBScript Regular Expressions 5.5

    Dim M1 As MatchCollection
    Dim M As Match
    
    Set Reg1 = New RegExp
        
    With Reg1
        .Pattern = "(Tracking Code\s*(\w*)\s*)"
        .Global = True
    End With
    If Reg1.Test(Item.Body) Then
    
        Set M1 = Reg1.Execute(Item.Body)
        For Each M In M1
        
'allows for multiple matches in the message body
        Item.Subject = M.SubMatches(1) & "; " & Item.Subject
        
        Next
    End If

 Item.Save
  
Set myForward = Item.Forward
myForward.Recipients.Add "alias@domain.com"
 
myForward.Send
 
End Sub

Forward messages in a quarantine mailbox

This macro forwards messages that were sent to a quarantine folder by antispam software back to the original recipient. The original subject is restored.

To use, add the macro to the ribbon or toolbar. Select the message and click the button.

Use myForward.Send to automatically send the message.

You need to set a reference to the VB Script library:
Microsoft VBScript Regular Expressions 5.5 in the VB Editor's Tools, References menu.

Sub ChangeSubjectThenForward()
Dim oItem As Outlook.MailItem
Dim strSendto, strSubject As String
Dim myForward As MailItem
  
' Set reference to VB Script library
' Microsoft VBScript Regular Expressions 5.5
    Dim Reg1 As RegExp
    Dim M1 As MatchCollection
    Dim Reg2 As RegExp
    Dim M2 As MatchCollection
    Dim M As Match
 
Set oItem = ActiveExplorer.Selection.Item(1)
Set myForward = ActiveExplorer.Selection.Item(1).Forward

 ' regex from http://slipstick.me/2k3zf
 ' check the original, not the forward
    Set Reg1 = New RegExp
    With Reg1
        .Pattern = "(To[:](.*))"
        .Global = True
    End With
    If Reg1.test(oItem.Body) Then
     
        Set M1 = Reg1.Execute(oItem.Body)
        For Each M In M1
           strSendto = M.SubMatches(1)
        Next
    End If
    
    Set Reg2 = New RegExp
    With Reg2
        .Pattern = "(Subject[:](.*))"
        .Global = True
    End With
    If Reg2.test(oItem.Body) Then
     
        Set M2 = Reg2.Execute(oItem.Body)
        For Each M In M2
           strSubject = M.SubMatches(1)
        Next
    End If

    myForward.Recipients.Add strSendto
    myForward.Subject = strSubject
    myForward.Display ' change to .send to automatically send 

End Sub


Tools

Advanced Security for Outlook

Use Advanced Security for Outlook to learn what programs are trying to access Outlook and permanently allow or deny access to the program and the next time it requests access, the action you choose will be automatically executed and Outlook Security will not annoy you with messages about trying to access e-mail addresses you have stored in Outlook. Freeware, available in English, German and Russian. Advanced Security is fully compatible with Windows 8 (32-bit and 64-bit editions) and Microsoft Office 2013 (32-bit editions only). The programs button is available on the ribbon in Outlook 2010 and Outlook 2013.

ClickYes Pro

ClickYes Pro is a tuning tool for Microsoft Outlook security settings. It allows you to configure which applications can automatically send emails using Outlook and access email addresses stored in Outlook address book. ClickYes Pro runs as a background task providing a convenient icon in the taskbar notification area to manage allowed applications. It uses an encrypted storage and is highly secure and safe. Client and Server versions available. Works with Outlook 2000 - Outlook 2010.

CodeTwo Outlook WarningDoctor

CodeTwo Outlook WarningDoctor removes the security warnings that appear when sending mail or performing other actions recognized by Microsoft as a "risky" (for example, when you try to read some data using the Outlook or CDO API #. Especially useful for designers of macros, Visual Basic, and programmers of other scripting languages that use the object model.Outlook 2000 and up, including Outlook 2010 64bit.

First: You will need macro security set to low during testing.

To check your macro security in Outlook 2010 or 2013, go to File, Options, Trust Center and open Trust Center Settings, and change the Macro Settings. In Outlook 2007 and older, it’s at Tools, Macro Security.

After you test the macro and see that it works, you can either leave macro security set to low or sign the macro.

Open the VBA Editor by pressing Alt+F11 on your keyboard.

To put the code in a module:

  1. Right click on Project1 and choose Insert > Module
  2. Copy and paste the macro into the new module.

More information as well as screenshots are at How to use the VBA Editor

Written by

Diane Poremsky
A Microsoft Outlook Most Valuable Professional (MVP) since 1999, Diane is the author of several books, including Outlook 2013 Absolute Beginners Book. She also created video training CDs and online training classes for Microsoft Outlook. You can find her helping people online in Outlook Forums as well as in the Microsoft Answers and TechNet forums.

Please post long or more complicated questions at Outlookforums.

224 responses to “Run a Script Rule: Change Subject then Forward Message”

  1. Bob Vance

    I was trying to find a script that would delete the first 42 characters in the subject line (Outlook)from an incoming email address nztr@xtra.co.nz is that possible.....Thanks for any help............Bob

  2. Claus

    I'm trying to run your script rule in Outlook 2007:

    Sub ChangeSubjectForward(Item As Outlook.MailItem)
    Item.Subject = "Test"
    Item.Save

    Set myForward = Item.Forward
    myForward.Recipients.Add "alias@domain.com"

    myForward.Send

    End Sub

    BUT the problem is that it doesn't work for me. I want it to forward a specific message from one email adress to a new email adress containing an image as attachment (a Facebook email adress). If it works it should update my Facebook wall with this attachment containing a changed and edited subject line (which will be them be the image comment at Facebook).

    How do I do this, and why doen't it work?

    thanks
    Claus Rosenblad

  3. jaykayo@hotmail.com

    Is there a way to remove the "FW:" in the subject for the Run the Script Rule?
    Thanks!

  4. Lili

    I am trying to create a macro that will make sure that every new email and every time i reply to email that the subject line contains the statement "Privacy", and if it doesn't to add it

  5. James

    My company's Exchange Server does not allow autoforwarding to an external address via rules. Will this script allow me to autoforward messages, or will the same restrictions apply as-if it were a 'rule'? Thanks!

  6. Luke Byers

    I have implemented the 'Change subject, then forward' script. I am finding that upon Outlook forwarding the email to the the recipient, it also includes my signature, which ends up being the first text at the top of the body seen by the recipient.

    In the forwarded email, the recipient ends up seeing the header and body of the primary email, then my signture, with a blank body.

    Is it possible to:

    1. add a template to the script in place of the signature, and
    2. suppress the signature from showing upon the email being forwarded?

    In respect of #1, some of the relevant parts of a recent script you (Diane) developed, may apply: http://www.slipstick.com/outlook-developer/run-a-script-rule-autoreply-using-a-template/

  7. Jinson

    How would i change the script if i want to add a message to the auto forwarded email?

  8. Douglas Whitehead

    I would like to change the subject line of forwarded emails from FWD: blah blah blah to my Thuraya number which is 0088216********** If possible I would like the email server to do this for me is there an email server that will run this or have I got to write a script in outlook?

  9. Pravin Rane

    can we script to disable the send receive in outlook witin predefined time for e.g. only in 9 AM to 5 PM automatic send receive works

  10. Walter

    Hi Diane, Your script for changing the subject line works great. Is there a way to have it only insert [PGP] into the subject line? and leave the original subject line in as well?

  11. Viviane

    Hi Diane,
    I'm looking for a run a script rule allowing to do the following actions:
    1/ Search for emails having a subject containing the words "validation RH" (ie: "RE: validation RH W3 for Sodex"
    2/ then update the subjet to add always the same code "F59" at the beginning of the subject (ie subject becomes: "F59 RE: validation RH W3 for Sodex")
    3/ then forward this email to a specific address (ie: fwdaddress@bla.com)

    Thanks in advance

  12. Galaxy

    Hi Diane,
    Thanks for your scripts! It works like a miracle.

    Is there anyway that I can reply from the forwarded email (e.g. from gmail) to the original sender. The sender will see that it received the reply from the original email and not from gmail.

    Also is there any way to let the scripts run without running outlook?

    Thanks!

  13. Luke Fultz

    Hello, Thanks sooooo much for the script its saved me a lot of time and frustration! For anyone who reads this interested in forwarding to multiple recipients, it took me a while to get the right syntax but I finally got it. You simply add the email addresses separated by a space but inside quotes:

    myForward.Recipients.Add "alias@domain.com" "alias2@domain.com" alias3@domain.com"

    I still do have a question though. What if I wanted the forwarded email to contain just like one line of text in the body. Is it possible to accomplish this? Thanks again, soo much for your help, you're providing a GREAT service here to your "Community" ;)

  14. V. Nguyen

    Hi Diane, for the change subject then forward script, I have a subject line that I need to have quotes around a couple words; however it won't let me put quotes around certain words. How can I do that? For example, my subject line needs to read: /parse/tag:"facilities" Hopefully that can be done because that would save me a ton of time! Thanks!

  15. V.Nguyen

    One more thing...so here is my dilemma. I have a number of emails that were forwarded to me with a resume in the body of the email. I liked how I could change the subject of the email and then forward to another email address. The only problem is, when I forward that email, I don't want to show the original senders email/sent information. Is there any way to get around that? Hopefully that makes sense. Thank you!

  16. V.Nguyen

    Thank you for the quick reply Diane. It did not work and I got an error message.

  17. V. Nguyen

    Hi Diane, it worked. I accidentally added a quote somewhere. How do I make it so that the "fwd" does not show up in the subject line when forwarding the email? Thank you!

  18. V. Nguyen

    Hi Diane, is this correct? If so, it's not working.

    Set myForward = aItem.Forward

    myForward.Recipients.Add "email address to be added here"

    myForward.Subject = Item.Subject

    myForward.Send

  19. V. Nguyen

    Hi Diane,
    I didn't see my reply posted here so not sure if it went through. I tried the above command, but it did not work. Did I enter it correctly?

    Sub ChangeSubjectThenSend()

    Dim myolApp As Outlook.Application

    Dim aItem As Object

    Set myolApp = CreateObject("Outlook.Application")

    Set mail = myolApp.ActiveExplorer.CurrentFolder

    Dim strFilenum As String

    For Each aItem In mail.Items

    aItem.Subject = "/parse /tag:facilities/source:RCI

    aItem.Save

    Set myForward = aItem.Forward

    myForward.Recipients.Add "enter email address here"

    myForward.Subject = Item.Subject

    myForward.Send

    Next aItem

    End Sub

  20. V. Nguyen

    Sorry for the many emails. I figured it out. Thank you!

  21. Lee.Bailey

    Can you post your solution? I have tried using

    myForward.Subject = Item.Subject to no avail (also tried specifying the subjest, the script simply fails to run

  22. merium

    i want to use 2 codes togather for forwarding all emails from inbox and delete from sent itmes.
    To Delete the Sent Copy of the Message

    To delete (or not save) the sent copy after it is forwarded, use myForward.DeleteAfterSubmit = True before the Send command.

    Sub ChangeSubjectForward(Item As Outlook.MailItem)

    Set myForward = Item.Forward
    myForward.Recipients.Add "alias@domain.com"

    ' To BCC an address or DL, try this:
    'myForward.BCC = "alias"

    myForward.DeleteAfterSubmit = True

    myForward.Send

    End Sub

    AND FOR DOING BCC ALL MESSAGES

    (http://www.slipstick.com/outlook/email/automatically-bcc-all-message/)

    Private Sub Application_ItemSend(ByVal Item As Object, _
    Cancel As Boolean)
    Dim objRecip As Recipient
    Dim strMsg As String
    Dim res As Integer
    Dim strBcc As String
    On Error Resume Next

    ' #### USER OPTIONS ####
    ' address for Bcc -- must be SMTP address
    ' or resolvable to a name in the address book
    strBcc = "address@domain.com"

    Set objRecip = Item.Recipients.Add(strBcc)
    objRecip.Type = olBCC
    If Not objRecip.Resolve Then
    strMsg = "Could not resolve the Bcc recipient. " & _
    "Do you want to send the message?"
    res = MsgBox(strMsg, vbYesNo + vbDefaultButton1, _
    "Could Not Resolve Bcc")
    If res = vbNo Then
    Cancel = True
    End If
    End If

    Set objRecip = Nothing
    End Sub

    KINDLY HELP ME OUT FOR RUNNIGN BOTH CODES AND TELL ME THE SETTING.

  23. Bland O

    Diane,

    I can see you are very helpful to a lot of folks and just maybe you can help me out. I use a special email account for clients to send me weekly information. I then use rules to forward that information to another email address and then move to a folder. All this works great. My question is....is there a way I can move the sending email address in front of the existing subject line before I forward it so that you can easily see who it was sent from without opening each email?

    I hope I made myself clear. If not let me know

  24. Samuel Kwan

    Hello, how can I change the Conversation Title/Subject so that the emails can be grouped by Conversation view in outlook 2010?

  25. Patrick

    I have a manual task at work where I get a certain type of email (from a specific sender, with specific subject line, with essentially the same body). This email is sent to two distribution lists, and one individual email address.
    My task is to reply to all and remove the 'RE:' from the subject, so the email that I send has exactly the same subject as the one I received (and subsequently replied to all).

    This situation sounds like something that would easily lend itself to automation, yet I am having some difficulty.

    Using a combination of Outook Rule and VB Script (attached to outlook rule) I have gotten a solution that is pretty close.

    I hit Alt+F11 in Outlook to access the VB Script and entered the following code:

    Sub ChangeSubjectForward(Item As Outlook.MailItem)
    Item.Subject = "Subject of Email"
    Item.Save

    Set myForward = Item.Forward
    myForward.Recipients.Add "email@email.com"
    myForward.Subject = Item.Subject

    myForward.Send

    End Sub

    - This code works, but there are issues:
    1) how do I send it to more than one recipient? I've read that you can out multiple address, in parenthesis, but when I try that in turns red and is not acceptable. Please offer some advice or suggestions.
    Also, two of the intended recipients are distributions groups. Can I use 'DistributionListName' (ie 'seattle office') - the way I would send it directly if I were manually writing an email in Outlook? Or do I have to do 'distributionlistname@emaildomain.com' (ie seattleoffice@myjob.com)??

    2) The code above uses 'forward', which is a tip I read on something Diane had posted on another site. While this gets to message sent out, I believe it's causing problems with the recipient. Remember, if I do it manually, I'm using the 'reply to all' function in Outlook, not just forwarding the message. Can someone help me out with the correct syntax for actually using 'reply to all' instead of forward in the code above?

    So, I think that's it - I need to use 'reply to all' and want to be able to reply to all to multiple recipients - while keeping the subject the same. Any suggestions, tips, or comments are so greatly appreciated!!!

    Also, thinking outside the box - if you want to suggest a totally different way to accomplish the same end result I'm certainly willing to try it!

    Again, I need to:

    Email comes in. I need to reply to all and change the subject to not contain 'FW:' or 'RE:' - just have it be the same. Then I need to send that email to all of the same recipients that were on the original mail. That's it.

  26. Patrick

    Diane,
    Thank you for your reply, but can I please trouble you for a little more feedback?
    Here is the code I have now:
    Sub ChangeSubjectReplyAll(Item As Outlook.MailItem)
    Item.Subject = "Subject of Email"
    Item.Save
    Set myForward = Item.ReplyAll
    myForward.Recipients.Add "mygmailaddress@gmail.com"
    myForward.Send
    End Sub
    The rule calling the script has been validated, so I'm sure my problem is with the script.
    What am I doing wrong? I made the change you suggested, but don't see any difference.
    Any additional feedback or suggestions would be so great appreciated!

  27. Patrick

    Diane,

    Thank you so much for your feedback and suggestions!!
    Ultimately I was able to get it working with the following script:

    Sub ChangeSubjectReplyAll(Item As Outlook.MailItem)
    Set myReplyAll = Item.ReplyAll
    myReplyAll.Subject = "Hard-coded Subject"
    myReplyAll.Send
    End Sub

  28. William Eadie (@williameadie)

    Thanks for this helpful information. Could not figure out what was wrong until I read the comments and saw your response on macro security level. For us noobs, this might be a helpful item to include in your posts proper.

  29. William Eadie (@williameadie)

    While this works great, I get a macro warning periodically while Outlook is running. "trust everything from this publisher" option is greyed out. This hangs the forwarding, which is a problem in my time-sensitive application. Is there a way to avoid this without lowering security to zero? Can I make "thisoutlooksession" act as a publisher, which I can then "trust"?

    Thanks for all your help and useful information.

  30. William Eadie (@williameadie)

    Just made the Cert (should have read the rest of that page!) and fingers crossed.

    Thanks!

    Will

  31. jimmy greencorn

    I would appreciate some help in regards to this delimea . I need a script that would run a rule on an inbound email with a daily attachment. The goal is to take the attachment, forward it to a distrobution list that is saved in outlook contacts, deleting the original body and subject, add a simple 1-2 line body, the abilty to modify or change the subject line so and ensure that each recepient does not know the identity of the other recipients by using bcc or some other method. I'd also like to have the ability to change the "reply to" email address

  32. vikas

    Hi Folks , All helpful chats up there.

    Can Please Someone help with below

    i get a auto mail from a link and i have set a rule to forward to team .

    now i need an INCIDENT ticket along with the mail i forward to team and the Subject also should get modified . Can anyone please help .

  33. Jon L

    Hi, I was wondering if anybody knows how to automatically insert the words "NOT PROTECTED" in the subject field everytime I send, reply or forward an email?

  34. woodstock99woody@hotmail.com

    Hi, thank you for the script "Change subject then forward". I tried to use it and it works. Unfortunately, I want the original email that I received to retain its original subject. Only the forwarded email has a new subject. How do In do that?

  35. nathan

    Hi,
    thank you for the script "Change subject then forward" VBA Macro version. It works. However I noticed the original email in the inbox has the new subject. How do I restore the original subject to the original email? I only wanted the forwarded email to have a new title.
    Thank you.

  36. Nathan

    Hi, Nathan here again. I used your suggestion and it works! Thank you. However the original email contains a picture embedded. When the script autofrwards the email, the picture becomes an html code in the forwarded email. How do I correct this?

  37. Nathan

    Hi, no, there are html links on the forwarded emails if it is a picture. On the other hand, if it is an excel table on the email, the excel table will lose its format.

  38. Edison

    Hi Diane,
    I am currently looking on this site to find a script that:
    1.) Will search the inbox based on the subject and automatically reply to it.
    2.) The recipient will be read from the text file, loop around all the list until it finishes.
    Unfortunately, I haven't found a script here (or maybe I overlooked it).
    Please can you assist me if there is a script around here.
    Thanks in advance.

  39. Mark

    Hi Diane, Looking to add multiple recipients but the ; separator does not seem to work. Is there a way to use this to send to multiple?

    Thanks!

  40. Mark

    Disregard. I simply added another myForward.Recipients.Add "alias@domain.com" line. Thanks again!

  41. Nathan

    Hi, I got your script running. It now forwards the email to an intended recipient and it can add in a new subject to the forwarded email. However, I now want the forwarded email to be saved in a folder in my network drive or a common folder so that my friends can view the forwarded email in case they couldn't receive the email.

    Here is what I insert

    FwdMsg.Recipients.Add "xxx@hotmail.com"
    FwdMsg.Subject = "Weather for today " & Format$(Date, "dd-mm-yyyy")
    FwdMsg.Send
    FwdMsg.SaveAs (c:\)

    It wont run.

  42. Chris

    Thank you so much for sharing your knowledge. The change "subject and forward script" is very helpful. How would I include the date and time in the Subject field? Or, if that is not possible, is there a way to insert text into the Subject from an external document?

    Again, thank you.

  43. FL Khong

    Hi Diane,

    I am very impressed by your knowledge in this area and I hope you can help me out in this.

    I have this requirement of upon receiving emails of particular format in "Subject", trigger an external program (either batch file or Java code).

    The "Subject" exists in form of "WO=12345 ; Task=1".

    The parameters "12345" and "1" will need to be fed into the external program as variables.

    May I know what is the best way forward to achieve this?

    I also tried the "Change subject then forward" script. On the outlook, it kep asking "Do you want to run the macro?" again and again. How do I make it run only once?

    I also tried to configure email rules in Outlook with "run a script", but I cannot find the newly created "Change subject then send" script. How do I make Outlook see it so that I can make it run according to the criteria set?

    Thanks in advance!

    FL

  44. FL Khong

    Hi Diane,

    Thank you so much for the reply. It works!

    I will have to do further modifications but this is a great start for me.

    Thanks again!

    Regards,
    FL

  45. FL Khong

    Hi Diane,

    In continuation to my question above, I would like to ask further about passing subject and body text into the external program.

    I did this:

    Sub OpenApp(Item As Outlook.MailItem)
    Shell ("External_Program.exe " & Item.Subject & Item.Body), vbNormalFocus
    End Sub

    ...but does not seem to work.

    : (

    Please help!

    Regards,
    FL Khong

  46. FL Khong

    Hi Diane,

    Yes, I am aware of that. In the example above, the native code accepts values.

    I am able to get the subject words, but the "Item.Body" seems to be empty.

    Regards,
    FL Khong

  47. Alex

    Hi Diane,

    I'm looking to create a rule that will change the color of a message when it is copied to another folder (for example, to a folder in Windows Explorer). Is this possible? Thanks in advance.

  48. Pete

    Hi, If i'm bcc'd on an email, how to I find the original email address. If I use 'to'or 'recipients' I can only find my bbc email address

  49. Diane

    Hi Diane,

    I am wondering if it is possible to extract a portion of the text from the body of the email message itself and place it in the subject line before forwarding the message. We receive a canned email from another system and it would be helpful if we could include the req number that is listed in the message in the subject line before forwarding the message.

    Thanks,
    Diane

  50. Colby

    Hi Diane,
    i am stuck wondering why my rule doesn't work when an email comes in. its a script to save an attachment to a mapped network drive folder. If i run the rule manually it works. please let me know if i need to email you my code.

  51. Colby

    'yes and no. it works sometimes.... just not consistently. code in below
    Public Sub SaveAttachments2(mail As Outlook.MailItem)
    On Error GoTo GetAttachments_err
    Dim ns As NameSpace
    Dim Inbox As MAPIFolder
    Dim Item As Object
    Dim Atmt As Attachment
    Dim FileName As String
    Dim i As Integer
    Dim f As String
    Dim strSubject As String
    Dim w As Integer

    Set ns = GetNamespace("MAPI")
    Set Inbox = ns.GetDefaultFolder(olFolderInbox)
    For Each Item In Inbox.Items
    strSubject = Item.Subject
    f = strSubject
    Rem MkDir ("Z:\OPERATIO\AS400_Report\" & f)
    For Each Atmt In Item.AttachmentsFileName = "\\ServerNAMEhere\OPERATIO\AS400_Reports\" & f & "\" & Atmt.FileName
    'popup window to confirm its working for now.
    MsgBox "Attachment and path " & Atmt.FileName, vbOKOnly, "What and Where"
    Atmt.SaveAsFile FileName
    i = i + 1

    'commented out and added rule option to delete the item
    Next Atmt
    'Item.Delete
    GetAttachments_exit:
    Set Atmt = Nothing
    Set Item = Nothing
    Set ns = Nothing
    Exit Sub

    GetAttachments_err:
    MsgBox "An unexpected error has occurred." _
    & vbCrLf & "Please note and report the following information." _
    & vbCrLf & "Macro Name: SaveAttachments2" _
    & vbCrLf & "Error Number: " & Err.Number _
    & vbCrLf & "Error Description: " & Err.Description _
    , vbCritical, "Error!"
    Resume GetAttachments_exit
    Next
    End Sub

  52. Colby

    Excellent! Onto the next part of my task: Checking to see if the path exists and creating the directory. Can that be done in the same script? Or should it have a separate Rule?

  53. Colby

    Thank you so much for your assistance! everything in this script works. Is there a way to have this do two additional things? im new to VBA and not sure what all can be done in this rule. 1) check the path to see if it exists Then create it if it doesnt. 2) check the subkect line for "XX" (our error code) to have the message skipped.

  54. Colby

    the path i need to check is going to be partially set in the above code \OPERATIO\AS400_Report\ and the rest in the subject line '290\2013\Lucky_Charms\' for example.

  55. BholaBhala

    I need some help with this:
    I am trying to move emails from Junk/Trash folders to Inbox, when they contain certain text. So when a message comes in and lands in Trash/Spam folder, this script will immediately move this message to Inbox, upon detecting certain code int he body of the message.Any help will be appreciated.

  56. Colby

    Sorry for the long delay in the response. i need to check for (from above code) to see if it exists. (after my if then for "XX" which works ;-)
    "\\ServerNAMEhere\OPERATIO\AS400_Reports\" & f

    f would equal something like this in the subject of the email.

    290\2013\FARMS\

  57. Kasper

    Hi,

    Great script! Can I make outlook ask for the subject line - so before forwarding, Outlook actually prompts what the subject for the forwarded mail shold be?

  58. Nigel

    Hi Diane,

    Very impressed with the above. I currently have a rule that filters my eBay mail:

    Apply this rule after the message arrives
    from eBay
    and with Confirmation of your order of in the subject
    flag message for Follow up This Week
    and assign it to the eBay category

    The only problem is that the list of items my Task List doesn't have enough room to show the full subject. Is there a way to remove the "Confirmation of your order of " from the subject?

  59. Nigel

    I should add that I tried your code:

    Sub EditSubject(Item As Outlook.MailItem)
    Item.Subject = Mid(Item.Subject, 43)
    Item.Save
    End Sub

    Which changes the email suject, but Outlook flags the message *before* it does so.

  60. Nigel

    And more ...
    If there was a way to change the follow-up to 4 days time, it would be perfect!

  61. Nigel

    >You want to flag the message in the script - the rule should contain only the conditions.

    That was quick!

    So should the script also set the category?

    I'll have to buy something now to try it :)

  62. Frederick Hung

    Hi Diane,

    I am glad that I come to this blog and see all the ariticles you have written.
    I want do write a script rule in Outlook (2010) that allows

    1. Adding a disclosure (few lines of text) at the end of the email
    2. Then foward to particular email address.

  63. Nigel

    Hi Diane,

    Thanks very much, that all works well. Just a thought though: is it possible to set *all* the task parameters? Such as:

    Start date: in 4 days
    Due date: in 4 days
    Reminder: in 4 days at 14:00

  64. Colby

    okay so here is what i took our of it:

    "If Not FSO.FolderExists(StrFolderPath) Then
    FSO.CreateFolder (StrFolderPath)
    End If"

    This works if i only need one folder created. but lets say i need two folders created C:\created1\created2

    I tried adding another if not then but that didn't work: let me know if you need me to repost the current code. I tried adding a loop but got an invalid call of arguments err. im officially Jellybrained

  65. Frederick Hung

    Thanks Diane, this is helpful.
    In the fowarding email, the recipient will see some info in the emal header:

    From: Company XYZ
    Sent: Wednesday, February 26, 2014 3:24 PM
    To: person ABC
    Subject: original subject

    We want to hide this info from the fowarding email, is there anyway to do it using script?

  66. Nik

    Hi Diane,

    I'm glad that I found your site. I went through all the rules provided in the comments but I don't find one that meets my requirement. I wonder if you could help me with the script as I don't know anything about the script.

    1) All incoming emails will be diverted to "Incoming" folder by mail rules.
    2) From "Incoming" folder, the Agent will automatically check the emails in the "Incoming" folder and move them to Inbox (whether or not user opens his Outlook) if subject format (as show below) is valid. Emails that do not match the subject format will be forwarded to “Invalid” folder.

    Valid subject format : ID Number:;
    Example : ID Number:00000261; xxxxxxxxxx xxxxx

    Appreciate if you can help me with this.

  67. Nik

    Hi Diane,

    Just to correct the subject format I posted earlier.

    Valid subject format : ID Number:;
    Example : ID Number:00000261; xxxxxxxxxx xxxxx

  68. CHC

    Hello,

    I think the scripts are great !! (Outlook 2010)

    I am using this part of the script =
    Set myForward = Item.Forward
    myForward.Recipients.Add "myemail@hello.com"
    myForward.DeleteAfterSubmit = True
    myForward.Send

    It works great when it sent a copy of email to the added address above, but I found out it sends another 2 copies of the original email to the original recipient (sends 3 emails).

    What would be needed so that it just sends the original email and then sends it again one time only with forwarded address ?

  69. Gonen

    Hi

    Is there a way to forward an email message when it is moved to the deleted folder ?

    I am looking for a script to forward an email message when it is deleted.

    thanks

  70. CHC

    Hello,

    The copies are deleted in the sent folder and works perfectly.

    But on the original recipient pc(outlook 2010), it shows 2 emails received =
    1- original that was sent, and then another
    2- copy of original email with the recipient's address and forwarded address in the "To:" field

    Thanks for replying !!

  71. CHC

    Pop-up = The original recipient address & forwarded address in the "To" field.

    Type of acct ? = using Outlook to access hosted email

  72. Frederick Hung

    I was looking for a script that can delete the first 3 rows and the last 5 rows of the HTML body before fowarding. Thanks

  73. CHC

    On friend's computer == First email received > "To: friend@mail.com"

    Second email received > "To: friend@mail.com; myemail@hello.com"
    (this email we don't want)
    **************************************************************************************

    On myemail's computer == email received > "To: myemail@hello.com"

  74. Frederick Hung

    Hi Diane,
    I refer to regex tutorial trying to grab those lines but failed... here is my script:

    Sub removeLines(Item As Outlook.MailItem)
    Dim objMsg As MailItem
    Dim Reg1 As RegExp
    Dim M1 As MatchCollection
    Dim M As Match

    Set objMsg = Application.CreateItem(olMailItem)
    objMsg.HTMLBody = Item.HTMLBody
    objMsg.Subject = "This email copy the whole content and sent as a new email.check no header info"
    objMsg.Recipients.Add "ispy8338@gmail.com"

    Set Reg1 = New RegExp
    With Reg1
    .Pattern = "Summary\s*(.*)\s*Contact"
    .Global = False
    End With

    If Reg1.Test(objMsg.HTMLBody) Then
    Set M1 = Reg1.Execute(objMsg.HTMLBody)
    Debug.Print M.SubMatches(1)

    End If
    End Sub

    I wonder if you can help as it doesn't give desired output. Thanks

  75. Nigel

    Hi Diane,

    Checked security settings. At one point the rule got disabled due to an error, but even if I do Run Now it doesn't do anything :(

    Perhaps I have got something mixed up in assembling the parts of the code.

  76. k r

    Hi Diane, I have been assigned the task by management of creating an Outlook 2010 rule to forward an entire email with an attachment using a template. I see your script that detail changing the subject then forwarding to a recipient. I am very new to scripting. Can you point me in the right direction to get me going?

  77. k r

    Thank you Diane,
    The message arrives to the Outlook Client with an attachment, then the message has to be forwarded with that attachment using a template that I have created., The template has special settings that has to be used, that is the reason it cannot just be forwarded to the recipient.. I will take a look at the script and let you know if that works for me.

  78. k r

    Thanks Diane, I responded last night but I wasn't logged in properly and it didn't post. So Here's the process, A Report Server sends a message with the report as an attachment to the Outlook Client. I need to forward the message using a template while retaining the attachment and the message to a list of users. All I need is a script that can forward using the template. The template will do all the work from there. Outlook has a rule that can REPLY WITH TEMPLATE, but not FORWARD WITH TEMPLATE. This is why now I need a script that can do this. Not sure why Microsoft left this out of the built in rules.
    Thanks!

  79. Nigel

    Hi Dianne,

    I did reply to this, no idea where it went. I have checked the settings, all seem OK. I wonder if I made an error stitching the pieces of code together?

  80. Tony F

    Thank you soo much!!!! You just saved me hours and hours of menial work, so I can forward a lot of messages to another email address by running this Macro! There are thousands of messages I would have had to forward!

    -Tony

  81. Bharath

    Hello,

    i misunderstood the concept of ""Change subject then forward" VBA Macro version" in this section and did a blunder. I misunderstood that code for adding subject to all new mail item and applied the code in my VBA window and it replaced subject of all the existing mails in my INBOX. Is there any way that i could get back my mail subjects like before ?

    my code is below :

    Sub addsubject()
    Dim myolapp As Outlook.Application
    Dim aitem As Object

    Set myolapp = CreateObject("Outlook.Application")
    Set mail = myolapp.ActiveExplorer.CurrentFolder

    For Each aitem In mail.Items
    If InStr(aitem.Subject, "[BCD012]") > 0 Then
    aitem.Subject = Left(aitem.Subject, 9)
    aitem.Save
    End If
    Next aitem

    End Sub

  82. Bharath

    Do you think if there is any other way to get the "Subject" back ?

  83. Bharath

    Well, when i do that the it goes with the same subject which is noticed in my inbox and not the REAL subject. Below is my code :

    Sub addsubject()
    Dim myolapp As Outlook.Application
    Dim aitem As Object

    Set myolapp = CreateObject("Outlook.Application")
    Set mail = myolapp.ActiveExplorer.CurrentFolder

    For Each aitem In mail.Items

    Set myforward = aitem.Forward
    myforward.Recipients.Add "bharath-kumar.subramani-ext@sgcib.com"
    myforward.Send

    Next aitem

    End Sub

  84. Ashish

    HI,My query is regarding i need to extract 2 items from a body and need to send to a mail id in the Subject..with provided example i can only able to extract one field at a time..can you help me how can i do it for 2...here is the data i need to extract
    new order 1111

    Phone number: 2222222
    I need to extract order(1111) and number (2222222) and send fwd it to a new mail id mentioning both these in subject..

    PLease help

  85. ashish

    HI,My query is regarding i need to extract 2 items from a body and need to send to a mail id in the Subject..with provided example i can only able to extract one field at a time..can you help me how can i do it for 2...here is the data i need to extract
    new order 1111

    Phone number: 2222222
    I need to extract order(1111) and number (2222222) and send fwd it to a new mail id mentioning both these in subject..

    PLease help

    Here is my code

    Sub CodeSubjectForward(Item As Outlook.MailItem)
    Dim M1 As MatchCollection
    Dim M As Match

    Set Reg1 = New RegExp

    With Reg1
    .Pattern = "(number\s*[:]+\s*(\w*)\s*)"
    .Global = True
    End With

    If Reg1.Test(Item.Body) Then

    Set M1 = Reg1.Execute(Item.Body)
    For Each M In M1
    Item.Subject = M.SubMatches(1) & "; " & Item.Subject

    Next
    End If

    Item.Save
    Set myForward = Item.Forward
    myForward.Recipients.Add "er.ashishbatra@gmail.com"

    myForward.display

    End Sub

  86. Ashish batra

    HI,,Thanks alot for help i have tried to make some changes..its still not working..here is the data from which i need to extract
    ______________________________________________________________
    A new order 12345678 is in the queue for a connectivity test.

    Phone number of technician: 0012999988665544
    ________________________________________________

    i need to extract order number and technician: number from this and send this to a different mail id in subject..

    example of Subject : 12345678-0012999988665544

    as per your advise i have tried to implemt case but it is still not working..here is the script which i have made...

    --------
    Sub CodeSubjectForward(Item As Outlook.MailItem)
    Dim M1 As MatchCollection
    Dim M As Match

    Set Reg1 = New RegExp
    For i = 1 To 2
    With Reg1
    Select Case i

    Case 1
    .Pattern = "(order\s*+\s*(\w*)\s*)"
    .Global = True

    Case 2
    .Pattern = "(technician\s*[:]+\s*(\w*)\s*)"
    .Global = True

    End Select
    End With

    If Reg1.Test(Item.Body) Then

    Set M1 = Reg1.Execute(Item.Body)
    For Each M In M1
    Item.Subject = M.SubMatches(1) & "; " & Item.Subject

    Next
    End If
    Next i
    Set Reg1 = Nothing

    Item.Save
    Set myForward = Item.Forward
    myForward.Recipients.Add "ashish.batra@colt.net"

    myForward.Display

    End Sub

  87. Ashish batra

    HI sorry for disturbing you again...i am facing a stange problem now...Till 2 days ago my script was working but now its not working means not giving any output..its not running at all.

    THis the script which i intially told you was working for me.

    Sub CodeSubjectForward(Item As Outlook.MailItem)
    Dim M1 As MatchCollection
    Dim M As Match

    Set Reg1 = New RegExp
    With Reg1
    .Pattern = "(order\s*(\w*)\s*)"
    .Global = True

    End With

    If Reg1.Test(Item.Body) Then
    Set M1 = Reg1.Execute(Item.Body)
    For Each M In M1
    Item.Subject = M.SubMatches(1) & "; " & Item.Subject

    Next
    End If

    Item.Save
    Set myForward = Item.Forward
    myForward.Recipients.Add "ashish.batra@colt.net"

    myForward.Display
    End Sub
    -----------------------------
    But now its not dispalying any thing to me when i get a message..i am applyin a rule that wheneveri recieve mail with Subject as New....it will run this script..i have already working with library 5.5

    Please help

  88. Ashish batra

    HI..sorry to disturb you once again..but something stange happening with me now...Script which i intially used is stop working..dnt knw why even i have not make any changes...

    This is the script..even i have used script which u have given recently but its still not working...This time not working means not responding at all...Do i nned to make any specific changes in my out look....It worked intially for 1 day and then stopped...

    here is the script which i am using

    ---------------------
    Sub CodeSubjectForward(Item As Outlook.MailItem)
    Dim M1 As MatchCollection
    Dim M As Match

    Set Reg1 = New RegExp

    With Reg1
    .Pattern = "(technician\s*[:]+\s*(\w*)\s*)"
    .Global = True
    End With

    If Reg1.Test(Item.Body) Then

    Set M1 = Reg1.Execute(Item.Body)
    For Each M In M1
    Item.Subject = M.SubMatches(1) & "; " & Item.Subject

    Next
    End If

    Item.Save
    Set myForward = Item.Forward
    myForward.Recipients.Add "ashish.batra@colt.net"

    myForward.Display
    End Sub
    ---------------------------------------------

    Rule i am using is match a word in subject and run script..i am using VB library 5.5

  89. Ashish

    What should ne my Macro setting..sam thing haapened with my colleague..it worked fro me next day he logout from system it stops working...pls suggest the Macro setting which i need to use

  90. ashish

    HI...I have checked my Macro settings its is showing me -- Notifications for digitally signed macros,all other macros disabled

    is it the correct one or do i need to change them

  91. Nathan

    Hi,
    I am able to run a script that autoforward the original email to a new list of recipents and that new email has a new subject.

    However, some information on the original email is sensitive and needs to be omitted before sending. Could you guide me on how to locate a specific field or sentences in the body of the original email, delete it and then forward the remaining contents of the body to a new recipent?
    Thank you

  92. Nathan

    Hi,
    here is my code.
    I have a bunch of sentences between the word Impact: and Corrective Action that I need to remove.

    Dim pattern As String
    pattern = "Impact:([\S\S]+)Correct"
    Dim MsgInput As String
    MsgInput = FwdMsg.HTMLBody
    Dim replacement As String
    replacement = "Email me if you require the impact of this incident."
    Dim result As String = rgx.Replace(input, replacement)

    It doesnt run. Any idea?

  93. Nathan

    I have successfully written a script that can change the subject and then forward to a new recipient. My current script is as such

    enter code here
    With FwdMsg NewLine = "Dear users,Please note that we are affected by the incident below and will be corrected after systems recovers. Please email the team for more information.Thank you." FwdMsg.HTMLBody = NewLine & FwdMsg.HTMLBody

    FwdMsg.Recipients.Add "john@gmail.com" FwdMsg.Subject = "Incident affecting you" & Format$(Now, " dd-mm-yyyy hh.mmam/pm") FwdMsg.send

    However I now need to delete certain sentences in the email and replace them with " please call me."

    This is my email body

    Impact: ABCD EFG RSTUV ASDFT Corrective Action

    I need to remove the AABCD EFG RSTUV ASDFT and replace with a sentence "please call me" such that the new email body is

    Impact:

    please call me with this number

    Corrective Action

    How do I do that with regex?

    I tried this but it doesnt seem to work

    enter code here
    Dim pattern As String
    pattern = "Impact:.*Correction"
    Msginput " " & pattern
    Dim Msginput As String
    Msginput = FwdMsg.HTMLBody
    MsgBox " " & Msginput
    Dim replacement As String
    replacement = "please call me"
    Dim rgx As New RegExp
    Dim result As String
    result = rgx.Replace(Msginput, replacement)
    FwdMsg.HTMLBody = result

  94. Eric

    I want to make a script that will execute a cleanup rule if I send myself an email with a subject of "Clean-UP" Basically If i send myself a message with a specific subject line I want outlook to exceute a set of predefined rules already in my outlook client.

  95. Derek Patrick Daya

    Hi Diane,

    Can you help me on this request. I am currently planning on creating a rule that will auto forward an email to a another email address. before it forwards it, it needs to check the subject or the body if it contains a Job Portal. If it does, lets say jobsDB. It should add on JobsDB on the subject + the original subject. Lets says original subject is "Test" then before it forwards it to the other email address it the subject should be change to "JobsDB Test". Email that should only be forwarded are new email and which has an attachment.

    Please please. Thanks!

    1. Derek Patrick Daya

      Hi Diane,

      I did what you have advised but still it's not working.

      Sub ForwardEmail(Item As Outlook.MailItem)

      Set myForward = Item.Forward

      If InStr(Item.Subject, "Indeed") Then
      myForward.Subject = Item.Subject & ("Indeed")

      If InStr(Item.Subject, "s1JOBS") Then
      myForward.Subject = Item.Subject & ("S1 Jobs")

      If InStr(Item.Subject, "JobsDB") Then
      myForward.Subject = Item.Subject & ("JobsDB")

      If InStr(Item.Subject, "TradeWindsJobs") Then
      myForward.Subject = Item.Subject & ("Tradewinds")

      If InStr(Item.From, "auto@oilandgasjobsearch.com") Or InStr(Item.Body, "oilandgasjobsearch.com") Then
      myForward.Subject = Item.Subject & ("Oil&Gas JobSearch")

      If InStr(Item.Subject, "LinkedIn") Or InStr(Item.Subject, "LinkedIn") Then
      myForward.Subject = Item.Subject & ("Linkedin Advert")

      End If

      Item.Categories = "Added to Safesforce"

      Item.Save

      myForward.Recipients.Add "derekpatrickdaya@yahoo.com"

      myForward.Send

      End Sub

      When I try to click on debug it says block if without end if and it highlights the End Sub part of the script.

      1. Derek Patrick Daya

        Hi Diane,

        Thank you so much! you are truly a big help. I decided to use the case one which is kinda similar to the codes that I am familiar with. IT DID WORK!!!! NICE!!!!

        Thank you Thank you Thank you!!!

      2. Derek Patrick Daya

        Hi Diane,

        I have a follow up question if you don't mind. For LinkedIn we receive the application without a resume. On the application the email of the applicant is included their and we manually send them an email requesting for their email address. Should I create a new module for that? and do you have sample codes which I can look at so I can try writing it?

        Thank you so much for the big help!

  96. Derek Patrick Daya

    For some reasons my replies are not getting posted.

    Thank you for helping me on this Diane! :) To be honest, i really do not have any idea on how should I include the regex functionality on the current script. :( Can you provide me the code instead?

    LinkedIn email that we receive contains the email address of the applicant, is they anyway we can add the regex code on the below script? It will be like if subject contains linkedin and if has no attachment it will send out an email to the email address on the email requesting for a cv.

    If the message with subject linkedin but has attachment it should be forwarded to derekpatrickdaya@yahoo.com

    Here is the current code that I have.

    Sub ForwardEmail(Item As Outlook.MailItem)

    Dim str, strSubject As String
    Set myForward = Item.Forward

    Select Case True

    Case InStr(1, Item.Subject, "Indeed") > 0
    strSubject = " Indeed"

    Case InStr(1, Item.Body, "s1JOBS") > 0
    strSubject = " S1 Jobs"

    Case InStr(1, Item.Subject, "jobsDB") > 0
    strSubject = " JobsDB"

    Case InStr(1, Item.Subject, "TradeWindsJobs") > 0
    strSubject = " Tradewinds"

    Case InStr(1, Item.Subject, "LinkedIn") > 0
    strSubject = " LinkedIn Advert"

    End Select

    If True Then
    myForward.Subject = Item.Subject & strSubject
    End If

    If InStr(Item.SenderEmailAddress, "auto@oilandgasjobsearch.com") Or InStr(Item.Body, "oilandgasjobsearch.com") Then
    myForward.Subject = Item.Subject & ("Oil&Gas JobSearch")
    End If

    Item.Categories = "Added to Safesforce"
    Item.Save

    myForward.Recipients.Add "derekpatrickdaya@yahoo.com"
    myForward.Send

    End Sub

    Thank you!

Leave a Reply

If the Post Coment button disappears, press your Tab key.