Zach Reneau
Zach Reneau

Reputation: 1951

How to send HTML email through Outlook with a different mail-from (win32com.client)

Brief background:

I'm writing a script to send a template for work, but I normally send messages as our team mailer for visibility within my team. Most of it is working as expected, but I am missing the mail-from action or I'm doing something wrong. Normally I just select the alternate sender in Outlook when I craft the message from the "FROM" drop-down menu.

Which attribute will let me specify a different sending address?

Something like:

newMail.From = "[email protected]"

Simplified version of what I'm working with to send an HTML body:

import win32com.client
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "the subject"
#newMail.Body = "body text"
newMail.HTMLBody  = """<a href="https://google.com">Google Link</a>"""
newMail.To = "[email protected]"
#newMail.CC = 'Bob'
#attachment1 = "c:\\mypic.jpg"
#newMail.Attachments.Add(attachment1)
newMail.Send()

Upvotes: 1

Views: 4194

Answers (2)

Zach Reneau
Zach Reneau

Reputation: 1951

I found it:

newMail.SentOnBehalfOfName = "[email protected]"

That allowed me to send the message as our mailing list using my user profile.

Upvotes: 5

abarnert
abarnert

Reputation: 365925

According to the MailItem docs in the Outlook Object Model, what you want is the Sender property:

Returns or sets an AddressEntry object that corresponds to the user of the account from which the MailItem is sent. Read/write.

In the remarks:

In a session where multiple accounts are defined in the profile, you can set this property to specify the account from which to send a mail item. Set this property to the AddressEntry object of the user that is represented by the CurrentUser property of a specific account.

If you set the Sender property to an AddressEntry that does not have permissions to send messages on that account, Outlook will raise an error.

So, if "[email protected]" has permissions to send through your Outlook account, this is how you do it; if it doesn't, there is no way to do it.

The "See Also" section has a link to a complete example (in C#, but you should be able to translate).

Upvotes: 0

Related Questions