|
8 | 8 | username = "youremailaddress@provider.com"
|
9 | 9 | password = "yourpassword"
|
10 | 10 |
|
| 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 | + |
11 | 16 | # number of top emails to fetch
|
12 | 17 | N = 3
|
13 | 18 |
|
|
31 | 36 | # parse a bytes email into a message object
|
32 | 37 | msg = email.message_from_bytes(response[1])
|
33 | 38 | # decode the email subject
|
34 |
| - subject = decode_header(msg["Subject"])[0][0] |
| 39 | + subject, encoding = decode_header(msg["Subject"])[0] |
35 | 40 | if isinstance(subject, bytes):
|
36 | 41 | # if it's a bytes, decode to str
|
37 |
| - subject = subject.decode() |
| 42 | + subject = subject.decode(encoding) |
38 | 43 | # decode email sender
|
39 | 44 | From, encoding = decode_header(msg.get("From"))[0]
|
40 | 45 | if isinstance(From, bytes):
|
|
60 | 65 | # download attachment
|
61 | 66 | filename = part.get_filename()
|
62 | 67 | if filename:
|
63 |
| - if not os.path.isdir(subject): |
| 68 | + folder_name = clean(subject) |
| 69 | + if not os.path.isdir(folder_name): |
64 | 70 | # 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) |
67 | 73 | # download attachment and save it
|
68 | 74 | open(filepath, "wb").write(part.get_payload(decode=True))
|
69 | 75 | else:
|
|
76 | 82 | print(body)
|
77 | 83 | if content_type == "text/html":
|
78 | 84 | # 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): |
80 | 87 | # 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) |
84 | 91 | # write the file
|
85 | 92 | open(filepath, "w").write(body)
|
86 | 93 | # open in the default browser
|
|
0 commit comments