I'm currently trying to change the sender's email address in VBA to my secondary email in Outlook. The sender should change if an attachment's name includes a specific "attachment_name". I've already tried using the Application_ItemSend event, but it didn't work as expected.
端子
即使我包括“停止”并逐步移动,它也从默认电子邮件地址发送电子邮件。它达到“帐户”定义为new_sender_email的地步,但仍从错误的地址发送 这是我的尝试:
私有sub Application_itemsend(byval item作为对象,取消为布尔值) Dim MailItem作为Outlook.mailitem 昏暗的依恋作为outlook.attachment dim smtpaddress作为字符串
If TypeName(Item) <> "MailItem" Then Exit Sub
Stop
Set mailItem = Item
smtpAddress = "new_sender_email"
For Each attachment In mailItem.Attachments
If InStr(LCase(attachment.FileName), "rechnung") > 0 Then
mailItem.SentOnBehalfOfName = smtpAddress
If mailItem.SentOnBehalfOfName <> smtpAddress Then
MsgBox "Error2", vbExclamation
Cancel = True
End If
Exit For
End If
Next attachment
您面临的问题是由于使用SentonBehalfofName属性,该属性是为您代表他人发送电子邮件(例如代表)的方案而设计的。相反,您需要使用SendusingAccount属性来指定应使用哪个电子邮件帐户发送电子邮件。
这里是校正的代码:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim mailItem As Outlook.MailItem
Dim attachment As Outlook.Attachment
Dim newSenderAccount As Outlook.Account
Dim smtpAddress As String
Dim account As Outlook.Account
Dim accounts As Outlook.Accounts
Dim found As Boolean
' Ensure it's a MailItem
If TypeName(Item) <> "MailItem" Then Exit Sub
Set mailItem = Item
smtpAddress = "new_sender_email" ' Define the new sender's email address
found = False
' Get all accounts in Outlook
Set accounts = Application.Session.Accounts
' Loop through accounts and find the one that matches the smtpAddress
For Each account In accounts
If account.SmtpAddress = smtpAddress Then
Set newSenderAccount = account
found = True
Exit For
End If
Next account
' If the account is found, set the email to send using that account
If found Then
mailItem.SendUsingAccount = newSenderAccount
Else
MsgBox "Account not found.", vbExclamation
Cancel = True
End If
' Check for attachments and apply condition based on the file name
For Each attachment In mailItem.Attachments
If InStr(LCase(attachment.FileName), "rechnung") > 0 Then
' Ensure the new sender is correctly applied
If mailItem.SendUsingAccount Is newSenderAccount Then
MsgBox "Email will be sent from " & newSenderAccount.DisplayName, vbInformation
Else
MsgBox "Error: Unable to change sender.", vbExclamation
Cancel = True
End If
Exit For
End If
Next attachment
End Sub