Send email python outlook 365
Here is an example of how to send an email using Python with Outlook 365:
Prerequisites:
- You need to have the
win32com
library installed, which is a Python wrapper for the Microsoft Outlook COM API. You can install it using pip:pip install pywin32
- You need to have Outlook 365 installed and configured on your machine
- You need to have the Outlook 365 account credentials (username and password) to use for sending the email
Code:
import win32com.client
# Set up the Outlook application
outlook = win32com.client.Dispatch('Outlook.Application')
# Set up the email message
email = outlook.CreateItem(0) # 0 = MailItem
# Set the sender and recipient
email.From = '[email protected]'
email.To = '[email protected]'
# Set the subject and body
email.Subject = 'Test email from Python'
email.Body = 'This is a test email sent from Python using Outlook 365'
# Add attachments (optional)
# email.Attachments.Add('path/to/attachment1.pdf')
# email.Attachments.Add('path/to/attachment2.docx')
# Send the email
email.Send()
# Clean up
outlook.Quit()
Note:
- Make sure to replace
[email protected]
and[email protected]
with the actual email addresses you want to use. - You need to have the Outlook 365 account credentials (username and password) to use for sending the email. You can store these credentials securely using a library like
keyring
orpython-dotenv
. - This code uses the
win32com
library, which is a Python wrapper for the Microsoft Outlook COM API. This means that you need to have Outlook 365 installed and configured on your machine for this code to work. - This code sends the email using the default Outlook 365 account. If you have multiple accounts configured, you may need to specify the account to use using the
email.Account
property.
Security considerations:
- When storing email credentials, make sure to use a secure method such as environment variables or a secrets manager.
- Be aware that this code uses the
win32com
library, which is a Python wrapper for the Microsoft Outlook COM API. This means that you need to have Outlook 365 installed and configured on your machine for this code to work. This may pose a security risk if you are running this code on a machine that is not under your control.