首页 > 解决方案 > 如何在电子邮件正文中插入 HTML 元素

问题描述

当用户使用默认模板准备电子邮件时,我想应用 HTML。

我在网上得到了一些基本代码:

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
On Error Resume Next
If InStr(LCase(Item.To), "xxx@gmail.com") 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

当我发送时,会打开一个新的消息窗口。

我希望该 HTML 出现在同一个窗口中,而不是新窗口中。

标签: vbaoutlook

解决方案


Item.To 属性返回显示名称的字符串列表,您需要它Recipient.Address 属性,它将返回表示收件人电子邮件地址的字符串。

还要检查If Item.Class <> olMail if not then Exit Sub

完整示例

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, "TEST@gmail.com", 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

根据评论更新

只需删除if MsgBox end if代码块

例子

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, "TEST@gmail.com", vbTextCompare) Then

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

推荐阅读