Sending & Receiving Emails using Python

Bhavesh Goyal
3 min readAug 18, 2020

--

INTRODUCTION

Email systems are robust because they rely upon well-established protocols used by all email platforms across the internet. These protocols are defined and published by documents called RFC that stands for Request for Comments and resemble the PEPs from Python, but for protocols and patterns that define the operation of communication systems through the internet.

To send emails, we use the SMTP protocol, and to receive them, we use IMAP or POP protocols.

Sending Emails

import os
import smtplib
from email.message import EmailMessage
to=["xxx@yy.com","zzz@yy.com"]#To whomever you want to send the maila="""Enter your body of the email.
"""
email_id='Your email id'
email_pass='Your Password'
for i in to:

msg=EmailMessage()
msg['Subject']='Subject of mail'
msg['From']=email_id
msg['To']= i
msg.set_content(a)
# if you want to add an attachment
files=['xxx.pdf']
for file in files:
with open(file,'rb') as f:
data=f.read()
name=f.name
msg.add_attachment(data,maintype='application',subtype='octet-stream',filename=name)with smtplib.SMTP_SSL('smtp.gmail.com',465)as smtp:
smtp.login(email_id,email_pass)
smtp.send_message(msg)
smtp.quit()

Note: Don’t save your file as email.py, it won’t work as it clashes with the file in which the library is written.

In case you have problems to connect at Google, you need to enable the “Less secure app access”.

Google blocks access from apps that it judges as not following its security standards, the problem is they don’t have a clear explanation of what these standards are, besides that it’s not a trivial task for whom is starting and doing the first test to struggle with that.

That said if you are facing this issue, you can enable access to make your tests by accessing https://myaccount.google.com/u/0/security?hl=en:

If you have 2-step verification on for your Gmail account (which I recommend) then follow these steps:

  1. Goto this link
  2. Create an app password.
  3. Use that password instead of your original password.

Receiving emails

The IMAP Internet Message Access Protocol is used to receive emails, and as on SMTP, it operates at the application layer over TCP/IP. The port used for its connections is 143 for unencrypted and 993 for encrypted.

Another protocol that works for this task is the POP3, Post Office Protocol, but IMAP is better due to its synchronization between the client and the server and also the ability to access more than the email inbox.

The process of receiving emails is more complicated than sending because you also have to search for the message and decode it:

import email
import imaplib

EMAIL = 'mymail@mail.com'
PASSWORD = 'password'
SERVER = 'imap.gmail.com'

mail = imaplib.IMAP4_SSL(SERVER)
mail.login(EMAIL, PASSWORD)
mail.select('inbox')
status, data = mail.search(None, 'ALL')
mail_ids = []
for block in data:
mail_ids += block.split()

for i in mail_ids:
status, data = mail.fetch(i, '(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
message = email.message_from_bytes(response_part[1])
mail_from = message['from']
mail_subject = message['subject']
if message.is_multipart():
mail_content = ''

for part in message.get_payload():
if part.get_content_type() == 'text/plain':
mail_content += part.get_payload()
else:
mail_content = message.get_payload()
print(f'From: {mail_from}')
print(f'Subject: {mail_subject}')
print(f'Content: {mail_content}')

To stay connected follow me here.

--

--