编辑自动生成的电子邮件,并仅在/如果发送时继续编程

时间:2014-07-09 06:42:50

标签: vb.net email outlook

我有一个使用数据库(访问)数据生成电子邮件(outlook)的程序。我希望在发送电子邮件时更新数据库,但如果没有发送则不会。我正在寻找一种“暂停”程序的方法,直到用户通过发送或取消它来处理电子邮件。这就是我所拥有的(这不符合我想要的方式):

    Dim OutApp As New Outlook.Application
    Dim OutMail As Outlook.MailItem

    OutApp = CreateObject("Outlook.Application")
    OutApp.Session.Logon()

    OutMail = OutApp.CreateItem(Outlook.OlItemType.olMailItem)
    With OutMail
        .To = recipient
        .Subject = subject
        .BodyFormat = Outlook.OlBodyFormat.olFormatHTML
        .Body = htmlBody                
        .Display()
    End With

    If OutMail.Sent Then
        'Code that is to be run if the email is sent
    Else
        'Code that is to be run if the email is not sent
    End If

问题在于If的答案总是“假”,因为程序在用户检查电子邮件时仍在运行,并且在电子邮件最终发送时,“其他”代码已经存在运行

所以我的问题是:有没有办法让程序等待,看看电子邮件是否被发送?

2 个答案:

答案 0 :(得分:0)

Dim OutApp As New Outlook.Application
Dim OutMail As Outlook.MailItem

OutApp = CreateObject("Outlook.Application")
OutApp.Session.Logon()

OutMail = OutApp.CreateItem(Outlook.OlItemType.olMailItem)
With OutMail
    .To = recipient
    .Subject = subject
    .BodyFormat = Outlook.OlBodyFormat.olFormatHTML
    .Body = htmlBody                
    .Display()
End With

' *** NEW CODE:
Dim numberOfAttempts As Integer = 10
While Not OutMail.Sent And numberOfAttempts > 0
    numberOfAttempts -= 1
    Threading.Thread.Sleep(10000) ' Wait 10 seconds and retry
End While

If numberOfAttempts > 0 Then
    'Code that is to be run if the email is sent
Else
    'Code that is to be run if the email is not sent
End If

灾难性的补丁,但它可能会起作用:

' WARNING : WORST. CODE. EVER.
Dim numberOfAttempts As Integer = 10
While numberOfAttempts > 0
    Try
        If OutMail.Sent Then Exit While
    Catch ex As Exception
        'apparently "exception" = "success" ..... so there we go:
        Exit While
    End Try
    numberOfAttempts -= 1
    Threading.Thread.Sleep(10000) ' Wait 10 seconds and retry
End While

If numberOfAttempts > 0 Then
    'Code that is to be run if the email is sent
Else
    'Code that is to be run if the email is not sent
End If

答案 1 :(得分:0)

确认已发送电子邮件有点棘手。监控发件箱(例如通过发件箱的Folder.Items.ItemAdd / ItemMove事件)是一个不好的想法,因为触摸该文件夹中的任何项目通常会中断该项目的发送。

您可以监控撰写电子邮件的MailItem.Send事件,这可能已足够,但您必须假设将根据用户的发送/接收组和设置发送电子邮件。但您可以通过每个S / R组的SyncObject.SyncStart / SyncEnd事件监视那些发送事件的事件。如果事件与用于发送电子邮件的帐户匹配,您可以检查发件箱的Items.Count值以验证它是否已发送。