从excel vba发送outlook邮件

问题描述 投票:1回答:3

我有以下代码发送Outlook邮件。但是,当前景关闭时,这将不起作用。 Sub DraftMail(emailAddr, strBody, strSub)
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = GetObject(, "Outlook.Application")
If OutApp Is Nothing Then
Set OutApp = CreateObject("Outlook.Application")
End If Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .To = ""
    .CC = ""
    .BCC = emailAddr
    .Subject = strSub
    .HTMLBody = strBody
    .Send   'or use .Display
    .ReadReceiptRequested = True
End With
On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing

End Sub

任何人都可以帮助我,即使在前景关闭时如何使其工作?

vba outlook
3个回答
0
投票

试试这段代码:(未经测试)

Sub SendMail()

    Dim iMsg As Object
    Dim iConf As Object
    Dim Flds As Variant


    Set iMsg = CreateObject("CDO.Message")
    Set iConf = CreateObject("CDO.Configuration")

    iConf.Load -1
    Set Flds = iConf.Fields

    With Flds
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "<server>"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
        .Update
    End With

    With iMsg

        Set .Configuration = iConf
        .To = "[email protected]"
        .From = "[email protected]"
        .Subject = "MIS Reports" & " " & Date & " " & Time
        .TextBody = "Link to Currency Data :" & vbNewLine & "<" & myDest & ">"
        .Send
    End With

    Set iMsg = Nothing
    Set iConf = Nothing

End Sub

0
投票

首先,你有没有任何错误处理?例如,如果您调用getObject并且它已关闭,您应该收到错误?

所以大多数人使用的方式是调用get对象,如果出现错误,那么他们知道outlook已关闭并且他们创建了一个新实例。

如果你想非常精确,错误代码是429,例如这里的代码Link to previous question.

为了帮助您入门,这也应该有效

On Error Resume Next

Set OutApp = GetObject(, "Outlook.Application")
If OutApp Is Nothing Then
   Set OutApp = CreateObject("Outlook.Application")
End If

一旦你有这个工作,然后你可以删除“On Error Resume Next”并捕获特定的错误429,如果你想,然后你知道错误是因为Outlook没有运行。


0
投票

最简单的方法是构建一个mailto:// url并通过shell command运行它。

你必须URL encode主题和身体,以使其正确显示。

示例(在Windows中粘贴到“运行”命令中):

mailto://[email protected]?subject=New%20Email&body=This%20is%20the%20message%20body.

© www.soinside.com 2019 - 2024. All rights reserved.