Skip to content

Commit f54aac5

Browse files
committed
edit reading emails tutorial
1 parent 89a51e8 commit f54aac5

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

python-standard-library/reading-email-messages/reading_emails.py

+16-9
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@
88
username = "youremailaddress@provider.com"
99
password = "yourpassword"
1010

11+
12+
def clean(text):
13+
# clean text for creating a folder
14+
return "".join(c if c.isalnum() else "_" for c in text)
15+
1116
# number of top emails to fetch
1217
N = 3
1318

@@ -31,10 +36,10 @@
3136
# parse a bytes email into a message object
3237
msg = email.message_from_bytes(response[1])
3338
# decode the email subject
34-
subject = decode_header(msg["Subject"])[0][0]
39+
subject, encoding = decode_header(msg["Subject"])[0]
3540
if isinstance(subject, bytes):
3641
# if it's a bytes, decode to str
37-
subject = subject.decode()
42+
subject = subject.decode(encoding)
3843
# decode email sender
3944
From, encoding = decode_header(msg.get("From"))[0]
4045
if isinstance(From, bytes):
@@ -60,10 +65,11 @@
6065
# download attachment
6166
filename = part.get_filename()
6267
if filename:
63-
if not os.path.isdir(subject):
68+
folder_name = clean(subject)
69+
if not os.path.isdir(folder_name):
6470
# make a folder for this email (named after the subject)
65-
os.mkdir(subject)
66-
filepath = os.path.join(subject, filename)
71+
os.mkdir(folder_name)
72+
filepath = os.path.join(folder_name, filename)
6773
# download attachment and save it
6874
open(filepath, "wb").write(part.get_payload(decode=True))
6975
else:
@@ -76,11 +82,12 @@
7682
print(body)
7783
if content_type == "text/html":
7884
# if it's HTML, create a new HTML file and open it in browser
79-
if not os.path.isdir(subject):
85+
folder_name = clean(subject)
86+
if not os.path.isdir(folder_name):
8087
# make a folder for this email (named after the subject)
81-
os.mkdir(subject)
82-
filename = f"{subject[:50]}.html"
83-
filepath = os.path.join(subject, filename)
88+
os.mkdir(folder_name)
89+
filename = "index.html"
90+
filepath = os.path.join(folder_name, filename)
8491
# write the file
8592
open(filepath, "w").write(body)
8693
# open in the default browser

0 commit comments

Comments
 (0)