How to read email using python and smtplib

Question:

Found a lot of examples how to send mail, but how can I read inbox? For example yandex.

import smtplib as smtp

email = "[email protected]"
password = "password"

server = smtp.SMTP_SSL('smtp.yandex.com')
server.set_debuglevel(1)
server.ehlo(email)
server.login(email, password)
server.auth_plain()
# server.get_and_print_your_inbox_magic_method()
server.quit()
Asked By: Rasul

||

Answers:

The SMTP protocol is for sending mails. If you want to look at your inbox – aka receive mails – you need to use POP3 or IMAP.

But just like smtplib, Python also has imaplib for IMAP and poplib for POP3.

Answered By: finefoot

As already stated, you need:

  • SMTP server for sending emails
  • IMAP for reading emails
  • POP3 for reading emails

IMAP is more powerful than POP3; in general, you probably want to use IMAP. POP3 deletes the emails after they have been read, unlike IMAP.


For SMTP you can use Python’s smtplib, for IMAP you can use imaplib and for POP3 you can use poplib (all from standard library). However, they are all pretty low-level.

I have created more abstract alternatives to make things easy for everyone:

Here is an example of Red Mail:

from redmail import EmailSender

# Configure sender
email = EmailSender(host="smtp.example.com", port=587)

# Send an email
email.send(
    subject="An example email",
    sender="[email protected]",
    receivers=['[email protected]'],
    text="Hello!",
    html="<h1>Hello!</h1>"
)

And an example of Red Box:

from redbox import EmailBox
from redbox.query import UNSEEN, SUBJECT

# Configure email box    
box = EmailBox(host="imap.example.com", port=993)

# Select email folder
inbox = box['INBOX']

for msg in inbox.search(UNSEEN & SUBJECT("An example email")):
    # Process the message
    print(msg.subject)
    print(msg.from_)

    # Mark the message as read
    msg.read()

You can pip install the libraries:

pip install redmail redbox

Relevant links

Red Box:

Red Mail:

Answered By: miksus
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.