Introduction to Send Mail in Python
We can send mail in python very easily by using the Simple Mail Transfer Protocol (SMTP). Python offers a native Library called “smptlib”. The module smptlib actually defines a client session object which can be used to send mail.
We have just to call the SMTP method from smtplib class.
Code:
Obj = Smtplib.SMTP([host[,port[,local_hostname]]])
Parameters:
- host: The host which is running the SMTP server. This is an optional argument.
- port: Usually, if the host is specified, we need to specify a port.
- local_hostname: If the SMTP server is running locally, we should pass this value as localhost.
Ways of Sending Mail in Python
There are exactly two ways to send mail:
1. We can set up a local SMTP debugging server by the following command:
Code:
Python –m Smtp –c DebuggingServer –n localhost:1025
When the email is sent through this server, that email will be discarded and shown in the terminal.
Sending a plain text in mail:
While sending mail through python, we should make sure that the connection is encrypted, which makes sure that login credentials and messages are securely transferred.
We can establish a connection using two ways:
- Starting connection using SMTP_SSL()
- Starting connection which is encrypted using .starttls()
In the above ways, Gmail will be encrypting emails using TLS, which is better than SSL.
Connection using SMTP_SSL()
2. We can log in to the Gmail account and then send the mail.
For which we need to follow some steps:
Step 1: Sign-in to your google account.
Step 2: Click on this link https://myaccount.google.com/intro/security
Step 3: Disable the 2-step verification for signing in to google.
Step 4: Turn off less secure app access.
Here is the sample code through which we can check if the above settings help to send mail from a gmail account to others.
Code:
#!/usr/bin/python
# Python code for sending mail from your Gmail account
import smtplib
# Creating SMTP Client Session
smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security which makes the connection more secure
smtpobj.starttls()
senderemail_id="[email protected]"
senderemail_id_password="######"
receiveremail_id="[email protected]"
# Authentication for signing to gmail account
smtpobj.login(senderemail_id, senderemail_id_password)
# message to be sent
message = "Hey this is the test code for sending email from gmail account to another account"
# sending the mail - passing 3 arguments i.e sender address, receiver address and the message
smtpobj.sendmail(senderemail_id,receiveremail_id, message)
# Hereby terminate the session
smtpobj.quit()
print "mail send - Using simple text message"
In the above code, we are doing the following steps:
- smtplib is imported.
- An SMTP client session is created “smtpobj”, which is used to bundle the SMTP connection. Also, for Gmail, use port 587.
- Because of security things, SMTP connection is put into TLS mode, i.e. enabling encryption of all commands. The compiler will show the authentication error if an invalid email id and password are given.
- The message is passed as the third parameter to a method called send mail. With sender’s email address and receiver’s email address
- Note that don’t disturb the sequence of the parameter as shown in the code above.
- After all the task is done, we are quitting the SMTP session
Output:
Where gmail2.py is python code name with the above content.
Otherwise, you may encounter the following error:
Output:
When we send a text message on email, the content is treated as simple text. But we can include HTML tags also inside the text.
Example:
Code:
#!/usr/bin/python
# Python code for sending mail from your Gmail account
import smtplib
# Creating SMTP Client Session
smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security which makes the connection more secure
smtpobj.starttls()
senderemail_id="[email protected]"
senderemail_id_password="######"
receiveremail_id="[email protected]"
# Authentication for signing to Gmail account
smtpobj.login(senderemail_id, senderemail_id_password)
# message to be sent
message = """From: From Someone <from@[email protected]>
To: To Person <to@[email protected]>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
I have send you an test e-mail message in HTML format
<b>Sample HTML message</b>
<h1>headline</h1>
"""
# sending the mail - passing 3 arguments i.e sender address, receiver address and the message
smtpobj.sendmail(senderemail_id,receiveremail_id, message)
# Hereby terminate the session
smtpobj.quit()
print " mail send - Using HTML tags inside the message body"
In the above code, we have defined the message with HTML tags also. You can see in the below screenshot we may receive mail like this.
Output:
Sending Email with Attachments
There are two ways to send an email:
1. We can send an email with the content-type header as multipart/mixed. Then we need to read the file to be attached in binary mode, after which the file has to be encoded. We can use base64 encoding before sending mail.
Below is the example to send mail by using just 3 libraries smtpblib, base64 and os.
First, we need to create a text file that we will be sending in the mail as an attachment. We need to read the text file then use base64 for encoding; the encoded file will be sent now.
While creating a message to be sent, we divide the message into 3 sections:
- Here we mention to and from address, subject also Multipurpose Internet Mail Extension (mime) version.
- Next, we define the action on the message.
- Define the attachment.
Then concatenate all the parts as a “message”.
Then we follow the same steps for sending mail using SMTP.
Code:
#!/usr/bin/python
import smtplib
import base64
import os
os.chdir(r'C:/Python27/Projects')
fileName= 'abc.txt'
#os.path.join(r'C:/Python27/Projects/','abc.txt')
# We are reading the file abc.txt in binary mode
fs = open('C:/Python27/Projects/abc.txt',"rb")
fsContent=fs.read()
# Encoding the file before sending
fsEncoded = base64.b64encode(fsContent)
[email protected]"
senderemail_id_password=”#########"
receiveremail_id="[email protected]"
marker = "AUNIQUEMARKER"
body= """I am sending you a test mail including attachment"""
# Defining header for the message
p1 = """From: From Someone <[email protected]>
To: To Person <[email protected]>
Subject: Sending an Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s""" % (marker, marker)
# Defining action for message
p2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s""" % (body,marker)
# Defining the attachment part
p3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; fileName=%s
%s
--%s--""" %(fileName, fileName, fsEncoded, marker)
message = p1+p2+p3
# Creating SMTP Client Session
smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security which makes connection more secure
smtpobj.starttls()
# Authentication for signing to gmail account
smtpobj.login(senderemail_id, senderemail_id_password)
# sending the mail - passing 3 arguments i.e sender address,receiver address and the message
smtpobj.sendmail(senderemail_id,receiveremail_id, message)
# Hereby terminate the session
smtpobj.quit()
print "mail send - Using simple message including encoding"
Output:
2. Another way is by using the following imports in the python code. Which are native libraries in python.
Code:
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
Below is the code for sending mail using python native libraries.
Code:
# Libraries to be imported
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "[email protected]"
toaddr = "[email protected]"
fromaddrpassword = "#######"
# Instance of MIMEMultipart
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = " SUBJECT OF THE MAIL"
body = " Main body of the mail"
msg.attach(MIMEText(body,'plain'))
Output:
Conclusion
The above mentioned all the methods used to send mail a simple text, text with HTML tags, and email attachments. These days, sending mail has used notifications or alerts for applications running and used for normal email purposes. Python has made it easy by introducing the above libraries.
Recommended Articles
This is a guide to Send Mail in Python. Here we discuss the 2 ways of sending a plain text in the mail and sending mail with attachments. You can also go through our other suggested articles to learn more–