我正在尝试使用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 = "[email protected]" 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中选择它并且工作正常。
谢谢。
请使用此例程查找发件人的帐号。
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.
的参考
在olMail
中添加此行
.SentOnBehalfOfName = "youraddress" 'here change this