batMan007
batMan007

Reputation: 589

How to insert HTML elements in email body

I want to apply HTML when a user prepares email with a default template.

I got some basic code online:

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
On Error Resume Next
If InStr(LCase(Item.To), "[email protected]") Then
    prompt$ = "Are You Sure want to send this email to " & Item.To& " ?"
    If MsgBox(prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check Address") = vbNo Then
        Cancel = True
        Dim objOutlookMsg As Outlook.MailItem
        Set objOutlookMsg = Outlook.Application.CreateItem(olMailItem)
        objOutlookMsg.HTMLBody = "<html><body><strong>HELLO OUTLOOK</strong></body></html>"
        objOutlookMsg.Display
    End If
End If
End Sub

When I send, a new message window opens.

I want that HTML to present in the same window, not a new window.

Upvotes: 1

Views: 4011

Answers (2)

0m3r
0m3r

Reputation: 12497

The Item.To Property Returns String list of display names, what you need it Recipient.Address Property which will Return a String representing the email address of the Recipient.

Also check If Item.Class <> olMail if not then Exit Sub

Full Example

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    If Item.Class <> olMail Then Exit Sub

    Dim Rcpt As Recipient
    Dim Prompt As String
        Prompt = "Are You Sure want to send this email to " & Item.To & " ?"

    For Each Rcpt In Item.Recipients
        If InStr(1, Rcpt.AddressEntry, "[email protected]", vbTextCompare) Then
            If MsgBox(Prompt, vbYesNo + vbQuestion + vbMsgBoxSetForeground, _
                                              "Check Address ") = vbNo Then
                Cancel = True
                Exit Sub
            End If

         Item.HTMLBody = "<html><body><strong>HELLO OUTLOOK</strong></body></html>" _
                                                                      & Item.HTMLBody
        End If
    Next
End Sub

Updated per comments

Simply remove if MsgBox end if block of code

Example

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    If Item.Class <> olMail Then Exit Sub

    Dim Rcpt As Recipient

    For Each Rcpt In Item.Recipients
        If InStr(1, Rcpt.AddressEntry, "[email protected]", vbTextCompare) Then

         Item.HTMLBody = "<html><body><strong>HELLO OUTLOOK</strong></body></html>" _
                                                                      & Item.HTMLBody
        End If
    Next
End Sub

Upvotes: 1

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66286

If you want to modify the HTML body of the message begin sent (it is passed as the Item parameter to your event handler), why are you creating a new message instead of modifying the existing message? Set HTMLBody property on the Item object.

Upvotes: 0

Related Questions