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
608 views
in Technique[技术] by (71.8m points)

vba - MS Access / Outlook 2010 - how to choose which account to send email from?

I am trying to send emails from a specific account but it always sends from my main no matter how much code I try or what I do. Is there any way to tell it to send it from a particular account? I am writing my code in MS Access, but using Outlook objects.

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 = "[email protected]"
        .Subject = "test2"

        .Send
    End With

    Set outapp = Nothing
    Set oMail = Nothing

End Sub

Updated code:

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 = "[email protected]"    

    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 = "[email protected]"
            .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
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try using

Set oMail.sendusingaccount=olAccount

instead of

oMail.sendusingaccount=olAccount

It worked for me, your code is perfect, just the Set is missing.


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

...