Skip to content

Commit c4eedc7

Browse files
committed
added reading emails tutorial
1 parent 0c99e25 commit c4eedc7

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# [How to Read Emails in Python](https://www.thepythoncode.com/article/reading-emails-in-python)
2+
Edit `reading_emails.py` on your needs and then run it.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import imaplib
2+
import email
3+
from email.header import decode_header
4+
import webbrowser
5+
import os
6+
7+
# account credentials
8+
username = "youremailaddress@provider.com"
9+
password = "yourpassword"
10+
11+
# number of top emails to fetch
12+
N = 3
13+
14+
# create an IMAP4 class with SSL, use your email provider's IMAP server
15+
imap = imaplib.IMAP4_SSL("imap.gmail.com")
16+
# authenticate
17+
imap.login(username, password)
18+
19+
# select a mailbox (in this case, the inbox mailbox)
20+
# use imap.list() to get the list of mailboxes
21+
status, messages = imap.select("INBOX")
22+
23+
# total number of emails
24+
messages = int(messages[0])
25+
26+
for i in range(messages-4, messages-N-4, -1):
27+
# fetch the email message by ID
28+
res, msg = imap.fetch(str(i), "(RFC822)")
29+
for response in msg:
30+
if isinstance(response, tuple):
31+
# parse a bytes email into a message object
32+
msg = email.message_from_bytes(response[1])
33+
# decode the email subject
34+
subject = decode_header(msg["Subject"])[0][0]
35+
if isinstance(subject, bytes):
36+
# if it's a bytes, decode to str
37+
subject = subject.decode()
38+
# email sender
39+
from_ = msg.get("From")
40+
print("Subject:", subject)
41+
print("From:", from_)
42+
# if the email message is multipart
43+
if msg.is_multipart():
44+
# iterate over email parts
45+
for part in msg.walk():
46+
# extract content type of email
47+
content_type = part.get_content_type()
48+
content_disposition = str(part.get("Content-Disposition"))
49+
try:
50+
# get the email body
51+
body = part.get_payload(decode=True).decode()
52+
except:
53+
pass
54+
if content_type == "text/plain" and "attachment" not in content_disposition:
55+
# print text/plain emails and skip attachments
56+
print(body)
57+
elif "attachment" in content_disposition:
58+
# download attachment
59+
filename = part.get_filename()
60+
if filename:
61+
if not os.path.isdir(subject):
62+
# make a folder for this email (named after the subject)
63+
os.mkdir(subject)
64+
filepath = os.path.join(subject, filename)
65+
# download attachment and save it
66+
open(filepath, "wb").write(part.get_payload(decode=True))
67+
else:
68+
# extract content type of email
69+
content_type = msg.get_content_type()
70+
# get the email body
71+
body = msg.get_payload(decode=True).decode()
72+
if content_type == "text/plain":
73+
# print only text email parts
74+
print(body)
75+
if content_type == "text/html":
76+
# if it's HTML, create a new HTML file and open it in browser
77+
if not os.path.isdir(subject):
78+
# make a folder for this email (named after the subject)
79+
os.mkdir(subject)
80+
filename = f"{subject[:50]}.html"
81+
filepath = os.path.join(subject, filename)
82+
# write the file
83+
open(filepath, "w").write(body)
84+
# open in the default browser
85+
webbrowser.open(filepath)
86+
87+
print("="*100)
88+
89+
# close the connection and logout
90+
imap.close()
91+
imap.logout()

0 commit comments

Comments
 (0)