Outlook - insert text based on recipient - vba

I need to automatically insert text into an outgoing email depending on the recipient. I found some code in an answer to another question (credit to 76Mel) that looks promising. It seems that I could attach the code to ItemSend in ThisOutlookSession
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
If Item.MessageClass = "IPM.Note" Then
For Each myRecipient In Item.Recipients
If myRecipient.Address = "<EMAIL ADDRESS TO FIND>" Then
<code to add text>
End If
Next
End If
End Sub
What would the code be that adds the text to the body of the email - and would this even work? Would this code fire before the email is sent, or is it already too late?
I do need it to be automated (creating a button or running the macro manually isn't really an option; it's a memory thing: if I could remember to run the macro, I could just add the text manually)

Is this what you are trying? I have added the comments so you shouldn't have any problem understanding it :) If you still have a question, simply ask...
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
'~~> Check if it is an email
If TypeName(Item) <> "MailItem" Then Exit Sub
Dim srchString As String, NewText As String
'~~> Email Address which you want to search for
srchString = "abc#gmail.com"
'~~> New text that you want to add
NewText = "Blah Blah"
'~~> Search To, CC, BCC Fields
If InStr(1, Item.To, srchString, vbTextCompare) Or _
InStr(1, Item.CC, srchString, vbTextCompare) Or _
InStr(1, Item.BCC, srchString, vbTextCompare) Then
'~~> Add the relevant text to the body
Item.Body = Item.Body & vbNewLine & NewText
End If
End Sub
I would recommend this MSDN Link.
Topic: MailItem Object Members
Link: http://msdn.microsoft.com/en-us/library/bb176688%28v=office.12%29.aspx
Quote From the Above Link
Represents a mail message in an Inbox folder.
Lists all Methods / Properties for a MailItem Object

Related

Create a rule that deletes attachments before forwarding

I have been tasked to create an automated report system where an report from Google Data Studios are uploaded to specific projects (On a site called Basecamp). The reports always include both a report within the body of the e-mail and an attached PDF file. The are sent to a Gmail account (data studios refuse to schedule towards a non-Google account). The filters within Gmail doesnt really work well with the Basecamp system so I use filters to re-route them towards a Outlook account. There I use rules to send each e-mail towards the correct client within Basecamp.
Here comes the problem, Basecamp shows both the body of the e-mail AND the attached PDF version which makes us show duplicates.
Is there a way to create a macro that first deletes all attachments (or body of an e-mail) and THEN forward the e-mail.
It cant be done manually it have to be a rule that does it automaticaly. Keep in mind that I am not a coder and have never done anything like this so please keep it simple for my dumb brain!
Thank you in advance!
Marcus
PS: I found a code that seems to be what I am after.
Public WithEvents ReceivedItems As Outlook.Items
Private Sub Application_Startup()
Set ReceivedItems = Outlook.Application.Session.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub ReceivedItems_ItemAdd(ByVal Item As Object)
Dim xForwardMail As Outlook.MailItem
Dim xEmail As MailItem
On Error Resume Next
If Item.Class <> olMail Then Exit Sub
Set xEmail = Item
If InStrRev(UCase(xEmail.Subject), UCase("kto feature")) = 0 Then Exit Sub 'change subject text to your need
If xEmail.Attachments.Count = 0 Then Exit Sub
Set xForwardMail = xEmail.Forward
With xForwardMail
.HTMLBody = ""
With .Recipients
.Add "skyyang#addin88.com" 'change address to your own
.ResolveAll
End With
.Send
End With
End Sub
I am trying to get that code to work, and changes the subject to a specific word and then route it to a final e-mail account that then filters out to correct clients. However the code doesnt seem to work, it DOES forward the e-mail but the attachment is still there. The code was found at https://www.extendoffice.com/documents/outlook/5359-outlook-forward-attachment-only.html#a1
It seems you need to modify the code slightly:
Public WithEvents ReceivedItems As Outlook.Items
Private Sub Application_Startup()
Set ReceivedItems = Outlook.Application.Session.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub ReceivedItems_ItemAdd(ByVal Item As Object)
Dim xForwardMail As Outlook.MailItem
Dim xEmail As MailItem
Dim myattachments as Outlook.Attachments
On Error Resume Next
If Item.Class <> olMail Then Exit Sub
Set xEmail = Item
If InStrRev(UCase(xEmail.Subject), UCase("kto feature")) = 0 Then Exit Sub 'change subject text to your need
If xEmail.Attachments.Count = 0 Then Exit Sub
Set xForwardMail = xEmail.Forward
Set myattachments = xForwardMail.Attachments
While myattachments.Count > 0
myattachments.Remove 1
Wend
With xForwardMail
.HTMLBody = ""
With .Recipients
.Add "skyyang#addin88.com" 'change address to your own
.ResolveAll
End With
.Send
End With
End Sub
The Remove method of the Attachments class removes an object from the collection.

VBA for Outlook - Change Subject Line using Right

I am trying to change incoming emails subject line to only the last 11 characters of the subject line. When I use Item.Subject = Right(Item.Subject,11) it does not work.
Can someone assist?
Full code.
Sub ChangeSubjectForward(Item As Outlook.MailItem)
Item.Subject = Right(Item.Subject, 11)
Item.Save
End Sub
You could create a macro rule then run the below code:
Sub save_to_dir_test1(mymail As MailItem)
Dim strID As String
Dim objMail As Outlook.MailItem
strID = mymail.EntryID
Set objMail = Application.Session.GetItemFromID(strID)
objMail.Subject = Right(m.Subject, 11)
objMail.Save
Set objMail = Nothing
End Sub
For more information, please refer to this link:
Run a Script Rule: Change Subject then Forward Message
Getting the incoming email in outlook via VBA
I found another SO thread that says you can't modify the subject of a message without opening it first. We can use ActiveInspector to get a handle on the Item after we display it. Then we can change it, save it, and close it. I added a check to see if the subject is actually longer than 11 characters before we attempt to truncate it.
Try this:
Public Sub ChangeSubjectForward(ByRef Item As Outlook.MailItem)
Debug.Print Now ' This shows you when the code runs
If Len(Item.Subject) > 11 Then
Debug.Print "Subject is too long. Trimming..." ' This shows that we tried to truncate.
Item.Display 'Force the pop-up
Dim thisInspector As Inspector
Set thisInspector = Application.ActiveInspector
Set Item = thisInspector.CurrentItem ' Get the handle from the Inspector
Item.Subject = Right$(Item.Subject, 11)
Item.Save
Item.Close
End If
End Sub

How to add multiple safe addresses in outlook

i have created a outlook macro where if i want to send email other then the listed email id,it will give me a popup. However, i am not being able to add multiple email ids to the list. please find the below code that i have written. Can someone please help me how to add multiple email ids in my below code?
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Const ADDR_TO_WATCH_FOR = "James.t#outlook.com"
Dim olkRec As Outlook.Recipient
If Item.Class = olMail Then
For Each olkRec In Item.Recipients
If LCase(olkRec.Address) <> ADDR_TO_WATCH_FOR Then
If MsgBox("This message is addressed to " & ADDR_TO_WATCH_FOR & ". Are you sure you want to send it?", vbQuestion + vbYesNo, "Confirm Send") = vbNo Then
Cancel = True
End If
Exit For
End If
Next
End If
Set olkRec = Nothing
End Sub
Don't show the message box inside the loop over all recipients. Run the loop first and check all recipients. Build a list of multiple recipients if necessary. After you exit the loop, check if that list (a string) if not empty, show the message box.

Excel 'Forgot to Attach Attachment' alert VBA no longer working

I inserted the below VBA I found somewhere on the web into my outlook to catch e-mails which I have forgotten to attach the attachment to before they get sent.
It worked fine on initial application of the VBA however today I managed to forget to attach the attachment to an e-mail and sure enough it has stopped working for whatever reason. Can anybody help me rectify this please?
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim m As Variant
Dim strBody As String
Dim intIn As Long
Dim intAttachCount As Integer, intStandardAttachCount As Integer
On Error GoTo handleError
'Edit the following line if you have a signature on your email that includes images or other files. Make intStandardAttachCount equal the number of files in your signature.
intStandardAttachCount = 1
strBody = LCase(Item.Body)
intIn = InStr(1, strBody, "original message")
If intIn = 0 Then intIn = Len(strBody)
intIn = InStr(1, Left(strBody, intIn), "attach")
intAttachCount = Item.Attachments.Count
If intIn > 0 And intAttachCount <= intStandardAttachCount Then
m = MsgBox("You forgot to attach your file didn't you?" & vbCrLf & " ...idiot" & vbCrLf & vbCrLf & " Send it without?", vbQuestion + vbYesNo + vbMsgBoxSetForeground)
If m = vbNo Then Cancel = True
End If
handleError:
If Err.Number <> 0 Then
MsgBox "Outlook Attachment Reminder Error: " & Err.Description, vbExclamation, "Outlook Attachment Reminder Error"
End If
End Sub
I inserted the below VBA I found somewhere on the web into my excel to catch e-mails which I have forgotten to attach the attachment to before they get sent.
Your code isn't going to work in Excel as is.
The event Application_ItemSend is an Outlook specific event handler. It is not present in Excel. It is tied to the Outlook action "Send." See here for a description.
Setup event handler for Excel to handle Outlook events
If you want to have this work for emails generated in Excel you are going to have to do something different.
In your situation, create a separate class module and name it OutlookEventHandler and paste the following:
Private WithEvents ol As Outlook.Application
Private Sub ol_ItemSend(ByVal Item As Object, Cancel As Boolean)
'your code here
End Sub
Public Sub init()
Set ol = GetObject(, "Outlook.Application")
End Sub
Then, in your ThisWorkbook module add the following:
Private olEH As OutlookEventHandler
Private Sub Workbook_Activate()
Set olEH = New OutlookEventHandler
olEH.init
End Sub
This will result in your event handler being called for emails sent by both Excel and Outlook.

outlook macro to send email conditionally

Could anyone guide me in creating an Outlook Macro that does the following:
Whenever I send a mail to a particular mail-id an automated mail will be send to a specified group pa mail-ids or some outlook contacts group.
Thanks in advance!!
Here is a quick piece of VBA for you to get going with, add it in your ThisOutlookSession module.
you should be able to do the CC via a rule as well from the tools menu, or write the code to create a rule !
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
If Item.MessageClass = "IPM.Note" Then
For Each myRecipient In Item.Recipients
If myRecipient.Address = "<EMAIL ADDRESS TO FIND>" Then
''SendNotification
SendNotificationWithCopy Item
End If
Next
End If
End Sub
Sub SendNotification()
Set objMail = Application.CreateItem(olMailItem)
objMail.Recipients.Add "<EMAIL ADDRESS/GROUP TO SEND NOTIFICATION>"
objMail.Recipients.ResolveAll
objMail.Subject = "NOTIFICATION"
objMail.Body = "Body Text"
objMail.Send
End Sub
Sub SendNotificationWithCopy(obj As Object)
Set objMail = Application.CreateItem(olMailItem)
objMail.Recipients.Add "<EMAIL ADDRESS TO SEND NOTIFICATION>"
objMail.Recipients.ResolveAll
objMail.Attachments.Add obj, OlAttachmentType.olEmbeddeditem
objMail.Subject = "NOTIFICATION with attachment"
objMail.Body = "Body Text"
objMail.Send
End Sub