从excel vba发送outlook邮件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从excel vba发送outlook邮件相关的知识,希望对你有一定的参考价值。
我有以下代码发送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
任何人都可以帮助我,即使在前景关闭时如何使其工作?
试试这段代码:(未经测试)
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 = "test@gmail.com"
.From = "test@gmail.com"
.Subject = "MIS Reports" & " " & Date & " " & Time
.TextBody = "Link to Currency Data :" & vbNewLine & "<" & myDest & ">"
.Send
End With
Set iMsg = Nothing
Set iConf = Nothing
End Sub
首先,你有没有任何错误处理?例如,如果您调用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没有运行。
最简单的方法是构建一个mailto://
url并通过shell command运行它。
你必须URL encode主题和身体,以使其正确显示。
示例(在Windows中粘贴到“运行”命令中):
mailto://user@domain.com?subject=New%20Email&body=This%20is%20the%20message%20body.
以上是关于从excel vba发送outlook邮件的主要内容,如果未能解决你的问题,请参考以下文章
如何更改通过 Excel VBA 代码通过 Outlook 发送的电子邮件的字体格式?