MS Access/Outlook 2010 - 如何选择从哪个帐户发送电子邮件?

Joh*_*ith 3 ms-access outlook vba outlook-vba

我正在尝试从特定帐户发送电子邮件,但无论我尝试多少代码或我做什么,它总是从我的主要邮件发送.有没有办法告诉它从特定帐户发送它?我在MS Access中编写代码,但使用的是Outlook对象.

Sub testEmail()
    On Error Resume Next
    Set outapp = GetObject(, "Outlook.Application")

    If outapp Is Nothing Then
        Set outapp = CreateObject("Outlook.Application")
    End If


    Set oMail = outapp.CreateItem(olMailItem)

    With oMail
        .To = "randomaddress@randomdomain.com"
        .Subject = "test2"

        .Send
    End With

    Set outapp = Nothing
    Set oMail = Nothing

End Sub
Run Code Online (Sandbox Code Playgroud)

更新的代码:

Option Compare Database

Sub testEmail()
    On Error Resume Next
    Set oApp = CreateObject("Outlook.Application")
    Set oMail = oApp.CreateItem(olMailItem)
    Set olAccount = oApp.Account
    Set olAccountTemp = oApp.Account
    Dim foundAccount As Boolean
    Dim strFrom As String
    strFrom = "FROMADDY@randomaddress.com"    

    foundAccount = False
    Set olAccounts = oApp.Application.Session.Accounts
    For Each olAccountTemp In olAccounts
        Debug.Print olAccountTemp.smtpAddress
        If (olAccountTemp.smtpAddress = strFrom) Then
            Set olAccount = olAccountTemp
            foundAccount = True
            Exit For
        End If
    Next

    If foundAccount Then
        Debug.Print "ACCT FOUND!"
        With oMail
            .To = "randomaddress@random.com"
            .Body = "Message!"
            .Subject = "test3"
            .sendusingaccount = olAccount
        End With
    Else
        Debug.Print "No acct found"
    End If

    Set oApp = Nothing
    Set oMail = Nothing
    Set olAccounts = Nothing
    Set olAccount = Nothing
    Set olAccountTemp = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)

小智 6

尝试使用

Set oMail.sendusingaccount=olAccount
Run Code Online (Sandbox Code Playgroud)

代替

oMail.sendusingaccount=olAccount
Run Code Online (Sandbox Code Playgroud)

它适用于我,你的代码是完美的,只是Set缺少.