Outlook VBA 发送带有 PDF 附件的自动电子邮件

Outlook VBA to send Automated email with PDF attachment

需要帮助使用 VBA 在 Outlook 中发送自动电子邮件,同时从文件夹位置附加 PDF。以下是我到目前为止所拥有的。我卡在附加 PDF 的部分

Sub ViolationProcessingTest()

Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

strbody = "<BODY style = font-size:11pt;font-family:Calibri>" & _
"Hello, <br><br> Please process the attached violations."

On Error Resume Next
    With OutMail
        .To = "email@email.com"
        .CC = "email@email.com"
        .Subject = "Violations Processing"
        .Display
        .HTMLBody = strbody & .HTMLBody
        .Attachments.Add = "Folder path location with PDF"
    
    End With
    On Error GoTo 0
    
Set OutMail = Nothing
End Sub

首先,去掉 On Error Resume Next 行是个好主意 - 出现错误是有原因的,否则您甚至不知道代码失败的原因或位置。

其次,你的代码几乎没问题,你只需要去掉 = (这是一个方法调用,而不是 属性 赋值)并指定一个完全限定的 PDF 文件名:

.Attachments.Add "c:\SomeFolder\TheFile.PDF"

Attachments.Add 方法(不是 属性)在附件集合中创建一个新附件。附件的来源可以是文件(由带文件名的完整文件系统路径表示)或构成附件的 Outlook 项目。所以,代码应该是这样的:

    With OutMail
        .To = "email@email.com"
        .CC = "email@email.com"
        .Subject = "Violations Processing"
        .HTMLBody = strbody & .HTMLBody
        .Attachments.Add filePathToYourFile
        .Display
    End With

您可能会发现 How To: Create and send an Outlook message programmatically 文章有帮助。