In this chapter, I will teach you how to use Python to send emails. So we would write a simple Python program to send emails to Yahoo, Gmail etc.
- How SMTP Works
- Sending an Email
- How Email is Sent
- Sending HTML Email in Python
- Including Attachment to Email
1. How SMTP Works
SMTP stands for Simple Mail Transfer Protocol. You use SMTP to send relay emails between mail servers.
The smtplib module is used for this purpose. So you need to import it. This module defines something called ‘SMTP client session object’. This is an object used for sending email to any mail server on the Internet.
To create an SMTP session object, you use the following syntax:
import smtplib smtpObject = smtplib.SMTP(host, portnumber, localhostname)
The SMTP function takes three parameters: host, portnumber and local_hostname
host – This is the host running SMTP server. You can either specify the computer name, domain name or IP address
portnumber: This is the port on the server where the SMTP is listening. You can typically use port 25 as the portnumber.
localhostname: This is a situation where the SMTP server is your local machine. In this case, the localhostname is just localhost (or your computer name)
2. Sending an Email
After creating an SMTP session object, you need to use sendmail method. The sendmail method is an instance method used to send and email.
This method takes three parameters:
sender – This is a string of the sender email address
recipients – List of recipient email addresses
message – A string that specified To, subject and body of the email
The code below sends an email to the specified email address
import smtplib sender = 'email@example.com' recipients = ['firstname.lastname@example.org'] message = """From: Sender Name <email@example.com> To: Recipient Name <firstname.lastname@example.org> Subject: Test Email This is a sample email sent from Python """ try: smtpObject = smtplib.SMTP('smtp.gmail.com', 587) smtpObject.sendmail(sender, recipients, message) print("Email has been sent") except: print("Error Occured: Email Sending failed")
3. How Email is Sent
First, we import the smtplib. Then we define a sender and a list of recipients. Then we define a multiline message. Note that the message specifies the Sender, the Recipient and the Subject. Now, these three items make up the header and they are each place in separate line.
You can get the hostname from the particular host.
4. Sending HTML Email in Python
A HTML email is different from plain-text email described above. So this means, you can format using html tags. Even if you use html, everything would be displayed as plain text. Therefore to use formatted text which is called HTML email, you need to add two more headers to the email message.
These headers are: MIME-Version and Content-type. The mime version is set to 1.0 while the Content-type is set to text/html.
See example below, where we have modified the original code to support HTML email.
import smtplib sender = 'email@example.com' recipients = ['firstname.lastname@example.org'] message = """From: Sender Name <email@example.com> To: Recipient Name <firstname.lastname@example.org> Subject: Test Email MIME-Version: 1.0 Content-type: text/html This is a sample email sent from Python """ try: smtpObject = smtplib.SMTP('localhost') smtpObject.sendmail(sender, recipients, message) print("Email has been sent") except: print("Error Occured: Email Sending failed")
5. Including Attachments to Email
Just like you can attach files when sending email, you can do same in Python. So to do this, you simple change the Content-type to multipart/mixed.
After you do this, you also need to specify the text and attachment sections within boundaries.
The attached file must be encoded in base64. You can encode using the pack(“m”) function.
The complete code for sending an attachment is given below:
import smtplib import base64 filename = "D/test.txt" # Read a file from the file system fo = open(filename, "rb") filecontent = fo.read() encodedcontent = base64.b64encode(filecontent) sender = 'email@example.com' reciever = 'firstname.lastname@example.org' marker = "MARKER" body = """ This an email sent with an attachment from kindsonthegenius.com/python. """ # Main headers is defined here. section1 = """From: From Person <email@example.com> To: To Person <firstname.lastname@example.org> Subject: Sending Attachment MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=%s --%s """ % (marker, marker) # The message action is defined here section2 = """Content-Type: text/plain Content-Transfer-Encoding:8bit %s --%s """ % (body,marker) # The attachment is defined here section3 = """Content-Type: multipart/mixed; name=\"%s\" Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename=%s %s --%s-- """ %(filename, filename, encodedcontent, marker) message = section1 + section2 + section3 try: smtpObject = smtplib.SMTP('localhost') smtpObject.sendmail(sender, reciever, message) print("Email has been sent successfully") except Exception: print("Error occured: Email sending failed")