【问题标题】:How to send email from a specific Outlook account using Excel?如何使用 Excel 从特定 Outlook 帐户发送电子邮件?
【发布时间】:2019-03-26 15:29:13
【问题描述】:

我有使用默认 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 中选择它并且它可以工作。

【问题讨论】:

  • 当 Display 显示管理时,您是否看到选择了正确的帐户? oAccount 是 Exchange 还是 POP3?IMAP4/SMTP 帐户?
  • 现在什么都没有发生(什么都没有显示)——假设“If oAccount..”行有问题——它是一个 Exchange 帐户——我不知道是什么不同之处在于代码。
  • 您不应将 Account 对象与 ha 字符串进行比较。使用 SmtpAddress 或 DisplayName 属性

标签: excel vba outlook


【解决方案1】:

olMail 中添加这一行

    .SentOnBehalfOfName = "youraddress" 'here change this

【讨论】:

  • 无需通过整个 'oAccount' 方法即可工作,但是由于工作权限,我无权“代表”所需域发送。
  • 嗯,this 有帮助吗?
  • 不幸的是,我在 .SendUsingAccount 之前确实有“设置”。问题是宏现在什么都不做,所以我最好的猜测是没有触发 If 函数来处理其余代码,但我不知道为什么。
【解决方案2】:

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

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

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

【讨论】:

  • 太棒了,谢谢!工作得很好(我真的明白为什么现在太大声了)。
猜你喜欢
  • 2015-07-26
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2018-07-24
  • 2012-12-28
  • 1970-01-01
  • 2012-09-10
相关资源
最近更新 更多