从草稿文件夹发送电子邮件

时间:2016-12-08 18:00:32

标签: excel vba excel-vba outlook outlook-vba

使用以下VBA编码,我能够从outlook草稿文件夹发送所有电子邮件,但唯一的问题是我必须提供父文件夹名称。我们可以通过编码获得这些细节,因为这个宏将被不熟悉VBA的其他用户使用。

Dim lDraftItem As Long
Dim myOutlook As Outlook.Application
Dim myNameSpace As Outlook.NameSpace
Dim myFolders As Outlook.Folders
Dim myDraftsFolder As Outlook.MAPIFolder

Set myOutlook = Outlook.Application
Set myNameSpace = myOutlook.GetNamespace("MAPI")
Set myFolders = myNameSpace.Folders
Set myDraftsFolder = myFolders("Gaus_Shaikh2@syntelinc.com").Folders("Drafts")

For lDraftItem = myDraftsFolder.Items.Count To 1 Step -1

    If Len(Trim(myDraftsFolder.Items.Item(lDraftItem).To)) > 0 Then
        myDraftsFolder.Items.Item(lDraftItem).Send

    End If

Next lDraftItem

2 个答案:

答案 0 :(得分:1)

这应该有用......

Set myDraftsFolder = myNamespace.GetDefaultFolder(olFolderDrafts)

*编辑*

下面的代码可能是一个更好的功能;它有错误检查,所以任何电子邮件都包含在' To'部分不应该中止该功能

Sub TestSendDrafts()
    Call SendDraftMail
End Sub

Function SendDraftMail() As Boolean
On Error GoTo ExitFunction
    Dim ThisNameSpace As Outlook.NameSpace: Set ThisNameSpace = Application.GetNamespace("MAPI")
    Dim DraftFolder As Outlook.MAPIFolder: Set DraftFolder = ThisNameSpace.GetDefaultFolder(olFolderDrafts)

    Dim Var As Variant, i As Long, Difference As Long, SentItems As Long
    For i = DraftFolder.Items.Count To 1 Step -1
        Set Var = DraftFolder.Items.Item(i)
        DoEvents
        If Var.Class = olMail Then
            If Len(Trim(Var.To)) > 0 Then
                On Error Resume Next
                Var.Send
                If Err.Number = 0 Then SentItems = SentItems + 1
                On Error GoTo ExitFunction
            End If
        End If
    Next i

    Debug.Print "Sent " & SentItems & " message(s) from 'Draft E-mail'."
    SendDraftMail = True

ExitFunction:
End Function

答案 1 :(得分:0)

替换此行:

Set myDraftsFolder = myFolders("Gaus_Shaikh2@syntelinc.com").Folders("Drafts")

这三行:

Dim sUser As String
sUser = myFolders.Item(2).Name

Set myDraftsFolder = myFolders(sUser).Folders("Drafts")

第二个文件夹名称将是用户帐户名称(电子邮件地址),您可以将其存储为字符串并传递到myFolders()以限定其特定帐户。