Python - Sending Outlook email from different address using pywin32 - python

I have a working script that creates and sends Outlook emails successfully through pywin32, but I would like to send the email from a different, generic account. I have access to this generic account (and password) and even have the mailbox opened concurrently in Outlook, if that helps.
Trying something like msg.From = "generic#email.com" returns AttributeError: Property 'CreateItem.From' can not be set..
Is there any way to accomplish this without using SMTP? Even just changing the headers to reflect the generic account as the From and Reply-To address would work.
Edit: Using Win7 32bit, Outlook 2010, python 2.7, and the pywin32 module to create the following bit of code:
from win32com.client import Dispatch
mailer = Dispatch("Outlook.Application")
msg = mailer.CreateItem(0)
msg.To = emailTo
msg.CC = emailCC
msg.Subject = emailSubject
msg.Body = emailBody
msg.Send()
This part works perfectly fine, but it sends the emails through the user that's logged in, myself. I'd rather send it from a generic account so that it looks more official and replies are received there instead of in my mailbox.

I know this comes late, but this is another way I've managed to make this work. With this I was able to send e-mails with my non-default e-mail address in outlook:
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.Subject = "Test subject"
mail.To = "yourrecipient#gmail.com"
# If you want to set which address the e-mail is sent from.
# The e-mail needs to be part of your outlook account.
From = None
for myEmailAddress in outlook.Session.Accounts:
if "#gmail.com" in str(myEmailAddress):
From = myEmailAddress
break
if From != None:
# This line basically calls the "mail.SendUsingAccount = xyz#email.com" outlook VBA command
mail._oleobj_.Invoke(*(64209, 0, 8, 0, From))
mail.Send()

You can send mails via exchange using the extended mapi. It takes a little more effort than what you tried so far but it is very powerful, e.g. it allows to select an outlook profile to be used.
Have a look at site-packages\win32comext\mapi\demos\mapisend.py of your pywin32 installation.
EDIT:
As said in the comment, try the following to be sure Outlook is using the profile you want. Look for this line:
session = mapi.MAPILogonEx(0, MAPIProfile, None, mapi.MAPI_EXTENDED |
mapi.MAPI_USE_DEFAULT)
and change it to
session = mapi.MAPILogonEx(0, MAPIProfile, None, mapi.MAPI_EXTENDED |
mapi.MAPI_LOGON_UI)
Call SendEMAPIMail like this:
SendEMAPIMail(SendSubject, SendMessage, SendTo, MAPIProfile=None)
A dialog should appear offering to select the Outlook profile.
EDIT:
As #caseodilla found out, if Outlook is running with another profile, MAPILogonEx seems to reuse the running session and its profile. In order to force mapi to use another profile add the MAPI_NEW_SESSION flag:
session = mapi.MAPILogonEx(0, MAPIProfile, None, mapi.MAPI_EXTENDED |
mapi.MAPI_LOGON_UI | mapi.MAPI_NEW_SESSION)

Related

Opening outlook with filled fields using Python

I am trying to create a function to open a new Outlook message, but I would like the message to appear already with the recipient, subject fields.
So far what I have found is how to open a new Outlook window with the recipient, but I still can't get the subject to be displayed.
import webbrowser
webbrowser.open('mailto:email#domain.com', new=1)
Hope u can help me, ty.
mailto would work fine as long as you don't want HTML body or attachments. You can specify to/cc/bbc, subject, and body.
Something along the lines:
mailto:user1#domain.demo?subject=Test%20Subject&body=Test%20body&cc=user2#domain.demo&bcc=user3#domain.demo
And it will work under any OS and any email client.
Here is a potential solution using win32.com.client:
import win32.com.client as win32
outlook = win32.Dispatch("Outlook.Application") # Starts Outlook application
new_email = outlook.CreateItem(0) # Creates new email item
new_email.To = "email#domain.com" # Add recipients separated by comma or semicolon
new_email.Subject = "How to create new Outlook email in Python" # Your email subject
new_email.Body = "This text will be the body of your new email" # Your email body
new_email.Display(True) # Displays the new email item

Using Python and gmail API, how can I send messages with multiple attachements?

Looking to create and send messages with multiple files attached. Per the online gmail api documentation, there is a function for building messages with an attachment but no documentation for howto use it to create a message with multiple attachments.
Can I use the gmail API to send messages with multiple attachments programmatically? How might one do this?
With this function, you can send to one or multiple recipient emails, and also you can attach zero, one or more files. Coding improvement recommendations are welcome, however the way it is now, it works.
Python v3.7
smtplib from https://github.com/python/cpython/blob/3.7/Lib/smtplib.py (download the code and create the smtplib.py on your project folder)
def send_email(se_from, se_pwd, se_to, se_subject, se_plain_text='', se_html_text='', se_attachments=[]):
""" Send an email with the specifications in parameters
The following youtube channel helped me a lot to build this function:
https://www.youtube.com/watch?v=JRCJ6RtE3xU
How to Send Emails Using Python - Plain Text, Adding Attachments, HTML Emails, and More
Corey Schafer youtube channel
Input:
se_from : email address that will send the email
se_pwd : password for authentication (uses SMTP.SSL for authentication)
se_to : destination email. For various emails, use ['email1#example.com', 'email2#example.com']
se_subject : email subject line
se_plain_text : body text in plain format, in case html is not supported
se_html_text : body text in html format
se_attachments : list of attachments. For various attachments, use ['path1\file1.ext1', 'path2\file2.ext2', 'path3\file3.ext3']. Follow your OS guidelines for directory paths. Empty list ([]) if no attachments
Returns
-------
se_error_code : returns True if email was successful (still need to incorporate exception handling routines)
"""
import smtplib
from email.message import EmailMessage
# Join email parts following smtp structure
msg = EmailMessage()
msg['From'] = se_from
msg['To'] = se_to
msg['Subject'] = se_subject
msg.set_content(se_plain_text)
# Adds the html text only if there is one
if se_html_text != '':
msg.add_alternative("""{}""".format(se_html_text), subtype='html')
# Checks if there are files to be sent in the email
if len(se_attachments) > 0:
# Goes through every file in files list
for file in se_attachments:
with open(file, 'rb') as f:
file_data = f.read()
file_name = f.name
# Attaches the file to the message. Leaves google to detect the application to open it
msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)
# Sends the email that has been built
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(se_from, se_pwd)
smtp.send_message(msg)
return True
Don't forget to activate less secure apps on your google account (https://myaccount.google.com/lesssecureapps) for this code to work.
Hope this helps

Send an AppointmentIthem with python win32com library

I'm developing a Python scripts to create a simple AppointmentItem and send it to some recipients using win32com library. I found all the documentation and some VBA examples in this link: https://msdn.microsoft.com‎ and everything seems to be clear and well exained. But, in my script, though the AppointmentItem is created and the Recipients resolved, I am not able to send it. The following is just an example of how looks the code.
outlook = win32com.client.Dispatch("Outlook.Application")
ns = outlook.GetNamespace("MAPI")
ns.Logon(profilename)
App = outlook.CreateItem(1)
App.Subject = "subject"
App.Body = "Meeting"
App.Location = "München"
App.Recipients.Add(recipient)
App.Recipients.ResolveAll()
App.Send()
Should I have necessarily an Exchange Account? Is there a workaround to avoid this problem? I can send normal email using this library using:
Msg = outlook.CreateItem(0)
instead of creating an appointment (fourth line). I tried, for this reason, to send an email with the appointment in attachment, but in the email there is no attachment.
I found the solution and I'd like to post it, in order to help someone else, who may need it.
It's necessary just one code line more. The appointment should be changed into a meeting.
outlook = win32com.client.Dispatch("Outlook.Application")
ns = outlook.GetNamespace("MAPI")
ns.Logon(profilename)
App = outlook.CreateItem(1)
App.Subject = "subject"
App.Body = "Meeting"
App.Location = "München"
App.MeetingStatus = 1
App.Recipients.Add(recipient)
App.Recipients.ResolveAll()
App.Send()

programmatically send outlook email from shared mailbox

I'm trying to send an email with python from a shared mailbox.
I have been able to sucessfuly send it through my own email, but sending one with a shared mailbox (that I have tested that I have access too) is giving me issues.
Code used for email script in python
import win32com.client
import win32com
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "Python Email Test"
newMail.Body = "Test"
newMail.To = 'hi#hi.com'
newMail.Send()
I know that below is how I can read my emails from a shared Folder.
outlook = win32com.Dispatch("Outlook.Application").GetNamespace("MAPI")
dir_accounts = outlook.Folders("SharedFolder")
Any ideas on how to combine these?
In case if you have multiple accounts configured in Outlook you may use the SendUsingAccount property of the MailItem class. Or if you have sufficient privileges (rights) you may consider using the SentOnBehalfOfName property which is a string indicating the display name for the intended sender of the mail message.
Added this right before the newMail.send() step and it worked
newMail.SentOnBehalfOfName = 'SharedFolder'

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 = "mailer#my.org"
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 = """Google Link"""
newMail.To = "customer#example.org"
#newMail.CC = 'Bob'
#attachment1 = "c:\\mypic.jpg"
#newMail.Attachments.Add(attachment1)
newMail.Send()
I found it:
newMail.SentOnBehalfOfName = "mailer#company.com"
That allowed me to send the message as our mailing list using my user profile.
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 "mailer#my.org" 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).

Categories