Send mail with attachments in Python Program
What will I Learn?
This tutorial teaches you how to send email with attachments in Python Programming.
Difficulty and Requirements
Same as previous tutorials
Tutorial Content
SMTP:
SMTP stands for SImple Mail Transfer Protocol is a electronic mail transmitter which uses Transmission Control Protocol port no. 25 to exchange data between mail servers.
Python has a great module called smtplib which defines an SMTP client session object which is used to send mail to any device that is connected to internet using SMPT
or ESMPT listener daemon, which defines the way of communications between sender and receiver .
Starting the coding part, at first we will import the smtplib module
import smtplib
Now we will define sender and receiver email in string format.
sender = "[email protected]"
receiver = "[email protected]"
To format email properly we will define a message with proper headers From, To and Subject which will be separated from the body of the email using blank line.
msg = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: Sending Email using Python
I learned to send email using Python programming on programminghub tutorial.
"""
Now we define SMTP object named server which will be used to send emails. smtplib.SMTP method is called to connect to the SMTP server which
furthers calls SMTP connect()
method when host and port parameters are passed. We are using gmail to send email so we will pass gmail host and it's port number.
server = smtplib.SMTP('smtp.gmail.com',587)
Now, starttls() method is called to encrypt the following SMTP commands. As we will be passing valuable information like password , message in coming lines of code we need to call
this method. TLS stands for Transport Layer Security.
server.starttls()
We need to login to gmail server to send email. So we will call login() method for this. This method will take two arguements : sender address and it's password which will be
used to authenticate and login
into sender's SMTP server.
server.login(sender, "Sender_gmail_password")
Now we are logged in , we will send email by calling sendmail() method. This method takes three arguments : sender's email, receiver's email and message that needs to be sent.
It will construct required envelope form sender's email and receiver's email and transfers message without modifying headers.
After email is sent we need to quit the SMTP connection and end it's session so we will call quit()
server.quit()
Our final code:
import smtplib
sender = "[email protected]"
receiver = "[email protected]"
msg = """From: From Programminghub <[email protected]>
To: To Learner <[email protected]>
Subject: Sending Email using Python
I learned to send email using Python programming on programminghub tutorial.
"""
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(sender, "Sender_gmail_password")
server.sendmail(sender, receiver, msg)
server.quit()
Send attachment in email
For this we will add one more import of base64 module
import base64
base64 is a python module which provides functions to encode binary data to printable ASCII characters and decode it back. Now will open the file to read and we will encode that file into
base64 format.
file= "/path/filename.extension"
read_file = open(file, "rb")
file_content = readfile.read()
encodedcontent = base64.b64encode(file_content)
open() opens the file which take two arguments: path to file and mode. We opened /path/filename.extension in binary file read mode here. read() allows reading binary
data from opened files. To know more about working with files in python please visit here.
b64encode() method of base64 module is used to encode data which was assigned to file.
As we will be sending our email in different parts we need to set content-type to multipart/mixed. Then within boundries which is specified by two hyphens(- -) we will define text and attachment
part.We will define marker as AUNIQUEMARKER.
one defines the header, two defines the action to be taken and three defines the attachment section.
Thus three parts are defined as:
one = """From: From Programminghub <[email protected]>
To: To Learner <[email protected]>
Subject: Sending Email using Python
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
We can see that in one, header is well defined and MIMEVERSION is set to 1.0.
MIME stands for Multi-Purpose Internet Mail Extensions that
allows us to exchange different kinds of data filessuch as audio, video, images,etc.
two = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
three = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; file=%s
%s
--%s--
""" %(file, file, encoded_content, marker)
(file, file, encoded_content, marker) replaces the values in three also same things happens in other parts where values can be replaced.
We will define msg which holds the message to be send by combining all above three parts and send it.
msg=one + two + three
Combining with our previous final code and these new code lines our new final code looks like:
import smtplib
import base64
sender = '[email protected]'
receiver = '[email protected]'
file = "/path/filename.extension"
file_read = open(file, "rb")
file_content = file_read.read()
encoded_content = base64.b64encode(file_content)
marker = "AUNIQUEMARKER"
body = """
I learned to send email using Python programming on programminghub tutorial.
"""
one = """From: From Programminghub <[email protected]>
To: To Learner <[email protected]>
Subject: Sending Email using Python
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
two = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body, marker)
three = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; file=%s
%s
--%s--
""" % (file, file, encoded_content, marker)
msg = one + two + three
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, "Sender_Password_Here")
server.sendmail(sender, receiver, msg)
server.quit()
Note: Don't forget to replace email id and password with your own to send email.
all above codes including previous tutorials codes are available in my Github repo. Click here to download
For more details please visit Python Docs.
Curriculum
Python tutorials for beginners : Part - I
Python tutorials for beginners : Part - II
Python tutorials for beginners : Part - III
Reading and writing to files in python
Matching and Searching Strings with regex in Python
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
One remark: tutorial should be self sufficient, so please fill in Difficulty and Requirements section, even if it's the same as in previous tutorials.
You can contact us on Discord.
[utopian-moderator]
Hey @laxam, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!
@laxam thanks.. will take care about your suggestion from next time.
Hey @programminghub I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x