Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf54aac5

Browse files
committed
edit reading emails tutorial
1 parent89a51e8 commitf54aac5

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‎

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

11+
12+
defclean(text):
13+
# clean text for creating a folder
14+
return"".join(cifc.isalnum()else"_"forcintext)
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
ifisinstance(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
ifisinstance(From,bytes):
@@ -60,10 +65,11 @@
6065
# download attachment
6166
filename=part.get_filename()
6267
iffilename:
63-
ifnotos.path.isdir(subject):
68+
folder_name=clean(subject)
69+
ifnotos.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
ifcontent_type=="text/html":
7884
# if it's HTML, create a new HTML file and open it in browser
79-
ifnotos.path.isdir(subject):
85+
folder_name=clean(subject)
86+
ifnotos.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)

[8]ページ先頭

©2009-2025 Movatter.jp