【问题标题】:How to refer to non-default account?如何引用非默认账户?
【发布时间】:2026-02-05 08:45:02
【问题描述】:

我正在尝试使用另一个帐户发送,但是 VBA 默认为主电子邮件。

我想使用 no_reply 邮箱,但它使用 firstname.lastname@company.com。

我什至通过进入 Outlook 中的帐户设置将 no_reply 更改为我的默认电子邮件。

我在运行代码时检查了它是否在创建新邮件窗口时引用了 no_reply,它在行 Set OutAccount = myMail.Session.Accounts.Item(1) 处显示为 no_reply。但是电子邮件显示 first.last@company.com。

Sub Send_EmailV21()

Dim outlookApp As Outlook.Application
Dim myMail As Outlook.MailItem
Dim lastrow As Long
Dim i As Integer
Dim Sheet As Worksheet
Dim OutAccount As Outlook.Account

Application.ScreenUpdating = False

On Error Resume Next

lastrow = ThisWorkbook.Worksheets("Sheet1").Range("A1").End(xlDown).Row

For i = 2 To lastrow
    'If ThisWorkbook.Worksheets("Sheet2").Range("T" & i) = "No" Then
    
    Set outlookApp = New Outlook.Application
    Set myMail = outlookApp.CreateItem(olMailItem)
    'Set OutAccount = myMail.Session.Accounts.Item(1)
    source_file = ThisWorkbook.Worksheets("Sheet1").Range("E" & i).Value
    source_file2 = ThisWorkbook.Worksheets("Sheet1").Range("F" & i).Value
    
    Set Sheet = ThisWorkbook.Worksheets("Sheet1")
    
    myMail.Attachments.Add source_file
    myMail.Attachments.Add source_file2
    'Set myMail.SendUsingAccount = myMail.Session.Accounts.Item(1)
    myMail.To = ThisWorkbook.Worksheets("Sheet1").Range("D" & i).Value
    myMail.Subject = "Subject Line"
    myMail.HTMLBody = "whatever i want to write in the email"
    
    myMail.Display
    myMail.Send
    
    ThisWorkbook.Worksheets("Sheet1").Range("G" & i) = "Yes"
    'Else
    'End If
    
    Application.ScreenUpdating = True
 
Next i

End Sub

添加以下行有效。

myMail.SentOnBehalfOfName = "blah@company.com"

【问题讨论】:

标签: excel vba outlook


【解决方案1】:

我建议遍历配置文件中配置的所有帐户并选择所需的帐户。使用索引可能会错误地选择错误的帐户。

' Loop over the Accounts collection of the current Outlook session.
Dim accounts As Outlook.Accounts = application.Session.Accounts
Dim account As Outlook.Account
For Each account In accounts
   ' When the email address matches, return the account.
   If account.SmtpAddress = smtpAddress Then
      Return account
   End If
Next

更多信息请参见Send an email given the SMTP address of an account

【讨论】:

    最近更新 更多