如何在Outlook电子邮件正文中插入HTML元素

时间:2019-01-10 09:30:42

标签: vba outlook outlook-vba

你好,我是Outlook开发人员的新手,我有一个任务,即当用户在发送邮件时使用默认模板准备电子邮件时,我必须向其中注入一些html或javascript代码,而邮件上不会显示任何内容。

我从这里在线获得了一些基本代码

示例代码:

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

上面的代码很好用,但是当我点击send选项时,一个新的Outlook窗口随即打开了html字段。我希望html代码应该出现在同一窗口中,而不是显示在另一个新窗口中

2 个答案:

答案 0 :(得分:1)

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

还要检查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

答案 1 :(得分:0)

如果要修改开始发送消息的HTML正文(将其作为Item参数传递给事件处理程序),为什么要创建新消息而不是修改现有消息?在Item对象上设置HTMLBody属性。