我所知道的最好方法是创建一个Outlook应用程序项,创建消息,显示消息并使用sendkeys发送消息(等同于键入alt)。
缺点是sendkeys方法可能有点麻烦。为了使它更健壮,我让邮件项目的检查器(即它所在的窗口)在调用sendkeys之前立即将其激活。代码如下所示:
Dim olApp As outlook.Application
Dim objNS As Outlook.Namespace
Dim objMail As Outlook.MailItem
Dim objSentItems As Outlook.MAPIFolder
Dim myInspector As Outlook.Inspector
'Check whether outlook is open, if it is use get object, if not use create object
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
On Error GoTo 0
If olApp Is Nothing Then
Set olApp = CreateObject("Outlook.Application")
End If
Set objNS = olApp.GetNamespace("MAPI")
objNS.Logon
'Prepare the mail object
Set objMail = olApp.CreateItem(olMailItem)
With objMail
.To = <insert recipients name as string>
.Subject = <insert subject as string>
.Body = <insert message as string>
.Display
End With
'Give outlook some time to display the message
Application.Wait (Now + TimeValue("0:00:05"))
'Get a reference the inspector obj (the window the mail item is displayed in)
Set myInspector = objMail.GetInspector
'Activate the window that the mail item is in and use sendkeys to send the message
myInspector.Activate
SendKeys "%s", True
Run Code Online (Sandbox Code Playgroud)
然后,我通常会使用代码来检查已发送文件夹中的项目数是否已增加,如果没有,我会再次让应用程序等待并重复最后两行代码,然后重新检查已发送文件夹中的消息数是否已增加。该代码最多执行5次。第5次之后,会出现一个消息框,警告可能未发送该消息。
我从未发现此方法无法从excel发送消息,尽管我曾经在系统速度特别慢时看到警告消息,但在调查中发现该消息已发送。