如何使用Excel(VBA)从特定的Outlook帐户发送电子邮件?

时间:2019-03-26 15:29:14

标签: excel vba outlook-vba

我正在尝试使用Excel发送电子邮件(它将自动生成并发送电子邮件)。我有一个可以发送电子邮件的有效代码,但是它使用默认的Outlook帐户发送电子邮件。

我尝试更改代码以从特定电子邮件发送它,但是现在当我尝试运行宏时,什么也没有发生。该代码有问题吗,还是由于另一个问题(与Outlook相关的帐户和权限)而无法正常工作?

Sub CommandButton1_Click()

Dim wb As Workbook
Dim olApp As Outlook.Application
Dim olMail As Outlook.MailItem
Dim q As Long


Dim oAccount As Outlook.Account


Set wb = ThisWorkbook



For Each oAccount In Outlook.Application.Session.Accounts

If oAccount = "theEmailiWantToUse@domain.com" Then

    For q = 2 To 3 'LastRow

eName = wb.Sheets(1).Cells(q, 2).Value

Set olApp = New Outlook.Application
Set olMail = olApp.CreateItem(olMailItem)

mailBody = "Hello, "

With olMail
    .To = Worksheets("Emails").Cells(q, 4).Value
    .Subject = eName
    .HTMLBody = "<!DOCTYPE html><html><head><style>"
    .HTMLBody = .HTMLBody & "body{font-family: Calibri, ""Times New Roman"", sans-serif; font-size: 14px}"
    .HTMLBody = .HTMLBody & "</style></head><body>"
    .HTMLBody = .HTMLBody & mailBody & "</body></html>"

    Set .SendUsingAccount = oAccount
    .Display
     ' .Send

     End With

    Next

Else
End If

 Next

     Set olMail = Nothing
     Set olApp = Nothing

 End Sub

我知道我可以访问我想从中发送电子邮件的电子邮件,因为我可以从Outlook中选择它并且可以正常工作。

谢谢。

2 个答案:

答案 0 :(得分:3)

olMail

中添加此行
    .SentOnBehalfOfName = "youraddress" 'here change this

答案 1 :(得分:1)

请使用此例程查找发件人的帐号。

Sub Which_Account_Number()
'Don't forget to set a reference to Outlook in the VBA editor
    Dim OutApp As Outlook.Application
    Dim I As Long

    Set OutApp = CreateObject("Outlook.Application")

    For I = 1 To OutApp.Session.Accounts.Count
        MsgBox OutApp.Session.Accounts.Item(I) & " : This is account number " & I
    Next I
End Sub

然后

   .SendUsingAccount = olApp.Session.Accounts.Item(5)' whatever account index number you want to send. i have chosen 5

代替

Set .SendUsingAccount = oAccount

这种方法对我有用。您可以将此概念进一步整合到您的程序中。请确保在Outlook Object Library中设置了对Tools/References.的引用