Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

vba - How can I supress the Outlook warning while sending mail using macro in excel

I am trying to send an email using macro in excel.

But when I run this code my mail client i.e. MS Outlook shows a pop up warning similar to
Someone is tying to send mail on behalf of you. select yes or no

Is there any way using to suppress that warning so the email should be sent without any problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best way I know is to create an outlook application item, create the message, display the message and use sendkeys to send the message (equivelent of typing alt s).

The drawback is that the sendkeys method can be a bit buggy. To make it more robust I get the inspector for the mail item i.e. the window it is in and activate it immediately prior to the call to sendkeys. The code is shown below:

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

I normally then have code to check that the number of items in the sent folder has increased and if not I get the application wait again and repeat the last 2 lines of code and recheck that the number of messages in the sent folder has increased. The code does this upto 5 times. After the 5th time a message box comes up warning that the message may not have been sent.

I have never found this method to fail in sending a message from excel though I once saw the warning message when our system was particularly slow, on investigation it turned out that the message had been sent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...