outlook一个配置文件可以添加多个邮箱账号。
当用vba调用outlook发送邮件时,一般会以默认的邮箱账号发送邮件。
当有多个邮箱账号时,需要使用MailItem对象的 SendUsingAccount 属性设置发送的邮箱账号。
以下vba代码将遍历所有的邮箱账号,选择工作邮箱账号给1722187970@qq.com发送一个测试邮件:
Sub QQ1722187970()
Dim sPath As String
sPath = Excel.ThisWorkbook.Path & "\"
Dim objOutlookApp As Outlook.Application
Set objOutlookApp = New Outlook.Application
Dim objAccount As Account
'邮件附件对象
Dim objAttachment As Outlook.Attachment
With objOutlookApp
For Each objAccount In .Session.Accounts
If objAccount.AccountType = olPop3 And objAccount.DisplayName Like "工作*" Then
'一封邮件对象
Dim objMailItem As Outlook.MailItem
Set objMailItem = .CreateItem(olMailItem)
With objMailItem
'收件人,多个收件人用分号间隔
.To = "1722187970@qq.com"
'抄送人
.CC = "1722187970@qq.com"
'密件抄送人
.BCC = "1722187970@qq.com"
'邮件主题
.Subject = "Test123"
'邮件内容格式
.BodyFormat = olFormatRichText
'邮件的内容
.Body = "sdf"
'要添加的附件
' .Attachments.Add sPath & "Test.xlsx"
objMailItem.SendUsingAccount = objAccount
' 显示对话框
' .Display
'开始发送邮件
.Send
End With
End If
Next
End With
End Sub
其中最关键的是 objMailItem.SendUsingAccount = objAccount这句。
微软的官方帮助介绍用以下语句
Set objMailItem.SendUsingAccount = objAccount
是错的,要直接用
objMailItem.SendUsingAccount = objAccount
这句,不需要添加Set,如果添加了Set会报错。


既然是在With objMailItem中,为啥还要写“ objMailItem.sendusingaccount=objaccount”?