Reputation: 198
I'm using code similar to Steve Townsend's answer from this question: Send Outlook Email Via Python? to send an email by running a python script. How can I edit the default reply-to address, so that when someone replies to the automated email it will get sent to a specific address? Alternatively, can I modify the address that the email is sent from? I tried to modify the Msg.SentOnBehalfOfName property but had no success with that. Note that the address is an alias so I can't log into the account in Outlook.
import win32com.client
def send_mail_via_com(text, subject, recipient, profilename="Outlook2003"):
s = win32com.client.Dispatch("Mapi.Session")
o = win32com.client.Dispatch("Outlook.Application")
s.Logon(profilename)
Msg = o.CreateItem(0)
Msg.To = recipient
Msg.CC = "moreaddresses here"
Msg.BCC = "address"
Msg.Subject = subject
Msg.Body = text
attachment1 = "Path to attachment no. 1"
attachment2 = "Path to attachment no. 2"
Msg.Attachments.Add(attachment1)
Msg.Attachments.Add(attachment2)
Msg.Send()
Upvotes: 2
Views: 6762
Reputation: 6289
You can try the following code to choose sender address and recipient address freely.
import win32com.client as win32
def send_mail():
outlook_app = win32.Dispatch('Outlook.Application')
# choose sender account
send_account = None
for account in outlook_app.Session.Accounts:
if account.DisplayName == '[email protected]':
send_account = account
break
mail_item = outlook_app.CreateItem(0) # 0: olMailItem
# mail_item.SendUsingAccount = send_account not working
# the following statement performs the function instead
mail_item._oleobj_.Invoke(*(64209, 0, 8, 0, send_account))
mail_item.Recipients.Add('[email protected]')
mail_item.Subject = 'Test sending using particular account'
mail_item.BodyFormat = 2 # 2: Html format
mail_item.HTMLBody = '''
<H2>Hello, This is a test mail.</H2>
Hello Guys.
'''
mail_item.Send()
if __name__ == '__main__':
send_mail()
If you are interesting, you can refer this case.
Upvotes: 3