- Send Email with Attachments by Outlook Email – Python SMTP Tutorial
- Step 1. Set sender email and password
- Step 2. Set receivers
- Step 3. Set attachment file
- Step 4. Set outlook smtp server host and port
- Step 5. Create email text content
- Step 6. Create MIMEBase object to add attachment
- Step 7. Set email format
- Step 8. Send email
- Notice:
- How to Send email using Python?
- Send Email with SMTP Server using Python
- Sending Email Without SMTP Server
- Sending Email Without Password
- Sending Outlook Email Using Python
- Conclusion
- Quick Start¶
- Examples¶
- Retrieving Emails¶
- Sending Emails¶
- Message¶
- new_email()¶
- send_email()¶
- Contacts¶
- Send Email via Outlook and SMTP
- Related Posts
Send Email with Attachments by Outlook Email – Python SMTP Tutorial
In this tutorial, we will discuss about how to send email to others with attachments by using our outlook email in python. To send plain text message email by outlook email, you can view this tutorial.
If you want to send email with attachment, you should do by these steps.
Step 1. Set sender email and password
sender = "xxx@outlook.com" password = 'xxxxxxxx'
Step 2. Set receivers
receivers = ['tt@163.com','yy@126.com']
Step 3. Set attachment file
Step 4. Set outlook smtp server host and port
server_host = 'smtp.office365.com' server_port = 587
Step 5. Create email text content
#create MIMEMultipart object main_msg = email.mime.multipart.MIMEMultipart() #create a MIMEText object, it is the text content of email text_msg = email.mime.text.MIMEText("this is a email text content") #add MIMEText object to MIMEMultipart object main_msg.attach(text_msg)
Step 6. Create MIMEBase object to add attachment
contype = 'application/octet-stream' maintype, subtype = contype.split('/', 1) #read attachment content data = open(file_name, 'rb') file_msg = email.mime.base.MIMEBase(maintype, subtype) file_msg.set_payload(data.read( )) data.close( ) #file_msg is content of attachment email.encoders.encode_base64(file_msg) #attachment header basename = os.path.basename(file_name) file_msg.add_header('Content-Disposition', 'attachment', filename = basename) #add attachment to MIMEMultipart object main_msg.attach(file_msg)
Step 7. Set email format
main_msg['From'] = sender main_msg['To'] = ", ".join(receivers) main_msg['Subject'] = "This attachment sent from outlook" main_msg['Date'] = email.utils.formatdate( ) #full content of email fullText = main_msg.as_string()
Step 8. Send email
The full example code is here.
#!/usr/bin/python import smtplib import email.mime.multipart import email.mime.text import email.mime.base import os #set sender email and password sender = "xxx@outlook.com" password = 'xxxxxx' #set receivers receivers = ['ttt@163.com','ggg@126.com'] #set attachment file file_name = "F:\\D17-1052.pdf" #set outlook smtp server host and port server_host = 'smtp.office365.com' server_port = 587 #create email text content #create MIMEMultipart object main_msg = email.mime.multipart.MIMEMultipart() #create a MIMEText object, it is the text content of email text_msg = email.mime.text.MIMEText("this is a email text content") #add MIMEText object to MIMEMultipart object main_msg.attach(text_msg) #create MIMEBase object contype = 'application/octet-stream' maintype, subtype = contype.split('/', 1) #read attachment content data = open(file_name, 'rb') file_msg = email.mime.base.MIMEBase(maintype, subtype) file_msg.set_payload(data.read( )) data.close( ) #file_msg is content of attachment email.encoders.encode_base64(file_msg) #attachment header basename = os.path.basename(file_name) file_msg.add_header('Content-Disposition', 'attachment', filename = basename) #add attachment to MIMEMultipart object main_msg.attach(file_msg) #set email format main_msg['From'] = sender main_msg['To'] = ", ".join(receivers) main_msg['Subject'] = "This attachment sent from outlook" main_msg['Date'] = email.utils.formatdate( ) #full content of email fullText = main_msg.as_string() #send email by outlook smtp server = smtplib.SMTP(server_host, server_port) try: server.ehlo() server.starttls() server.ehlo() server.login(sender,password) server.sendmail(sender, receivers, fullText) print ("Successfully sent email") except SMTPException: print ("Error: unable to send email") finally: server.quit()
Notice:
1.If you wan to send more files, you should use more main_msg.attach(file_msg) .
main_msg.attach(file_msg) main_msg.attach(file_msg)
You will send two same files.
How to Send email using Python?
In this Python tutorial, we will explore different ways you can send emails using Python, including sending without an SMTP server, without a password, and using Outlook.
Send Email with SMTP Server using Python
SMTP, or Simple Mail Transfer Protocol, is the standard protocol for sending emails. Here’s how you can use Python to send an email through an SMTP server:
Import the smtplib library:
Set up the SMTP server:
server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls()
server = smtplib.SMTP('smtp.mail.yahoo.com', 587) server.starttls()
Log in to your email account:
server.login('your_email@example.com', 'your_password')
Send an email:
server.sendmail('your_email@example.com', 'recipient_email@example.com', 'Hello, this is a test email.')
Close the server:
Sending Email Without SMTP Server
Sending an email without an SMTP server in Python involves creating a direct SMTP session with the recipient’s email server. Be cautious; this method can cause your email to be flagged as spam.
Import the libraries:
import smtplib, dns.resolver
Find the MX record of the recipient’s domain:
domain = 'example.com' records = dns.resolver.resolve(domain, 'MX') mx_record = records[0].exchange
Establish a direct SMTP session:
server = smtplib.SMTP(mx_record, 25)
Send an email:
server.sendmail('your_email@example.com', 'recipient_email@example.com', 'Hello, this is a test email.')
Close the server:
Sending Email Without Password
This method is not recommended as it is less secure. However, if you have an application-specific password or an email server that doesn’t require authentication, you can use this method:
Set up the SMTP server:
server = smtplib.SMTP('smtp.example.com', 587) server.starttls()
Send an email:
server.sendmail('your_email@example.com', 'recipient_email@example.com', 'Hello, this is a test email.')
Close the server:
Sending Outlook Email Using Python
You can also send emails via Outlook by using its SMTP server in Python.
Set up the Outlook SMTP server:
server = smtplib.SMTP('smtp.office365.com', 587) server.starttls()
Log in to your Outlook account:
server.login('your_outlook_email@example.com', 'your_password')
Send an email:
server.sendmail('your_outlook_email@example.com', 'recipient_email@example.com', 'Hello, this is a test email.')
Close the server:
Conclusion
Sending emails through Python is a handy tool for automating communication. Whether you are using an SMTP server, sending without an SMTP server or password, or utilizing Outlook, Python has you covered.
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
Quick Start¶
pyOutlook interacts with Outlook messages and folders through the class OutlookAccount(). The OutlookAccount acts as a gatekeeper to the other methods available, and stores the access token associated with an account.
from pyOutlook import OutlookAccount account_one = OutlookAccount('token 1') account_two = OutlookAccount('token 2')
From here you can access any of the methods as documented in the pyOutlook section. Here are two examples of accessing an inbox and sending a new email.
Examples¶
Retrieving Emails¶
Through the OutlookAccount class you can call one of many methods — get_messages() , inbox() , etc. These methods return a list of Message objects, allowing you to access the attributes therein.
inbox = account.inbox() inbox[0].body >>> 'A very fine body'
Sending Emails¶
As above, you can send emails through the OutlookAccount class. There are two methods for sending emails — one allows chaining of methods and the other takes all arguments upfront and immediately sends.
Message¶
You can create an instance of a Message and then send from there.
from pyOutlook import * # or from pyOutlook.core.message import Message account = OutlookAccount('token') message = Message(account, 'A body', 'A subject', [Contact('to@email.com')]) message.attach(bytes('some bytes', 'utf-8'), 'bytes.txt') message.send()
new_email()¶
body = 'I\'m sending an email through Python.
Best,
Me' email = account.new_email(body=body, subject='Hey there', to=Contact('myemail@domain.com')) email.sender = Contact('some_other_account@email.com') email.send()
Note that HTML formatting is accepted in the message body.
send_email()¶
This method takes all of its arguments at once and then sends.
account_one.send_email( to=[Contact('myemail@domain.com')], # or to=['myemail@domain.com')] subject='Hey there', body="I'm sending an email through Python.
Best,
Me", )
Contacts¶
All recipients, and the sender attribute, in Messages are represented by Contacts . Right now, this allows you to retrieve the name of a recipient, if provided by Outlook.
message = account.inbox()[0] message.sender.name >>> 'Dude'
When providing recipients to Message you can provide them either as a list of strings, or a list of Contacts . I prefer the latter, as there are further options in the Outlook API for interacting with Contacts — functionality for those may be added in the future.
© Copyright 2016, Jens Astrup. Revision 93a74d5d .
Versions latest stable v4.2.1 v4.2.0 v4.1.1 v4.1.0 v4.0.0 Downloads pdf htmlzip epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.
Send Email via Outlook and SMTP
Microsoft’s email service, Outlook (formerly Hotmail), allows application developers to send emails through the SMTP protocol. This is what you need to know about Outlook’s SMTP server:
With this information and the help of the standard email and smtplib modules, we can use the following code to send an email from an Outlook account (it also accepts the old @hotmail.com, @live.com, etc.):
from email.message import EmailMessage |
import smtplib |
sender = «sender@outlook.com» |
recipient = «recipient@example.com» |
message = «Hello world!» |
email = EmailMessage () |
email [ «From» ] = sender |
email [ «To» ] = recipient |
email [ «Subject» ] = «Test Email» |
email . set_content ( message ) |
smtp = smtplib . SMTP ( «smtp-mail.outlook.com» , port = 587 ) |
smtp . starttls () |
smtp . login ( sender , «my_outlook_password_123» ) |
smtp . sendmail ( sender , recipient , email . as_string ()) |
smtp . quit () |
You’ll need to replace «sender@outlook.com» and «my_outlook_password_123» with the credentials of the Outlook account which you want to send the email from.
For a general explanation of the structure of this code and how to include HTML code and/or file attachments, see our post on the email and smtplib modules: Send HTML Email With Attachments via SMTP.