Receive and Send Gmail Using Python

Receive and Send email using python

In this tutorial, I will show a simple way to receive and send email using Python.

Receive email using imaplib

Python imaplib.IMAP4 class implements the actual IMAP4 protocol. The connection is created and protocol version (IMAP4 or IMAP4rev1) is determined when the instance is initialized. If host is not specified, “ (the localhost) is used. If port is omitted, the standard IMAP4 port (143) is used

import email
import imaplib
import sys
from email.mime.text import MIMEText
from email.parser import HeaderParser
from email.policy import default

IMAP_SERVER = 'imap.gmail.com'
IMAP_SERVER_PORT = 143

def process_mailbox(M):
    rv, data = server.search(None, "(UNSEEN)")`
    if rv != 'OK':
        print("No unread messages found!")
        return

    for num in data[0].split():
        rv, data = server.fetch(num, '(RFC822)')
        if rv != 'OK':
            print("ERROR getting message", num)
            return

        msg = email.message_from_bytes(data[0][1])
        headers = HeaderParser().parsestr(msg.as_string())
        sender = ''.join(email_parser.findall(headers['From'])).strip()
        print('The sender is {}'.forma(sender))

server = imaplib.IMAP4_SSL(IMAP_SERVER, port=IMAP_SERVER_PORT)

try:
    smtp.login(EMAIL_ACCOUNT, EMAIL_PASSWORD)
    rv, data = server.login(EMAIL_ACCOUNT, EMAIL_PASSWORD)
except imaplib.IMAP4.error:
    print("LOGIN FAILED!!! ")
    sys.exit(1)

rv, mailboxes = server.list()
if rv == 'OK':
    print("Mailboxes:")
    for mailbox in mailboxes:
        print(str(mailbox))

rv, data = server.select(EMAIL_FOLDER)
if rv == 'OK':
    print("Processing mailbox...\n")
    process_mailbox(M)
    server.close()
else:
    print("ERROR: Unable to open mailbox ", rv)

server.logout()

Send email using smtplib

The Python smtplib module defines an SMTP client session object that can be used to send mail.

In this example, I will use gmail smtp server, but you can use any other SMTP server. The default value of host is empty which means localhost and the default value of port is 0.

#!/usr/bin/python
import sys
import smtplib

import settings

import smtplib
import os.path as op
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders


def send_mail(send_to, subject, message, files=[], server="smtp.gmail.com", port=587, use_tls=True):

    username = settings.GMAIL_USERNAME
    password = settings.GMAIL_PASSWORD
    msg = MIMEMultipart()
    msg['From'] = username
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(message))

    for path in files:
        part = MIMEBase('application', "octet-stream")
        with open(path, 'rb') as file:
            part.set_payload(file.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="{}"'.format(op.basename(path)))
        msg.attach(part)

    smtp = smtplib.SMTP(server, port)
    if use_tls:
        smtp.starttls()
    smtp.login(username, password)
    smtp.sendmail(username, send_to, msg.as_string())
    smtp.quit()
    print('Email was sent successfully!')
Last modified October 4, 2020