Skip to content

Commit e9a61b3

Browse files
authored
Create app.py
1 parent 3569c88 commit e9a61b3

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

attachment-downloader/app.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import imaplib
2+
import email
3+
import os
4+
5+
USEREMAIL = "example@mail.com"
6+
USERPASS = "Example000"
7+
8+
9+
def downloadAttachment():
10+
11+
mail = imaplib.IMAP4_SSL("imap.gmail.com", port=993)
12+
mail.login(USEREMAIL, USERPASS)
13+
14+
mail.select()
15+
16+
result, data = mail.uid("search", None, "ALL")
17+
mails = len(data[0].split())
18+
19+
for i in range(mails):
20+
latestEmailUID = data[0].split()[i]
21+
result, emailData = mail.uid("fetch", latestEmailUID, "(RFC822)")
22+
23+
rawEmail = emailData[0][1]
24+
rawEmailString = rawEmail.decode("utf-8")
25+
emailMessage = email.message_from_string(rawEmailString)
26+
27+
for content in emailMessage.walk():
28+
if content.get_content_maintype() == "multipart":
29+
continue
30+
if content.get("Content-Disposition") is None:
31+
continue
32+
fileName = content.get_filename()
33+
fromEmail = emailMessage["from"]
34+
35+
if bool(fileName):
36+
if fileName.endswith(".pdf"):
37+
if fileName.startswith("SOMETHING"):
38+
cwd = os.getcwd()
39+
filePath = os.path.join("PATH", fileName)
40+
if not os.path.isfile(filePath):
41+
fileWrite = open(filePath, "wb")
42+
fileWrite.write(content.get_payload(decode=True))
43+
fileWrite.close()
44+
uid = latestEmailUID.decode("utf-8")
45+
print(
46+
f'Downloaded "{fileName}" in "{cwd}\\download" from "{fromEmail}" with UID "{uid}"'
47+
)
48+
49+
50+
downloadAttachment()

0 commit comments

Comments
 (0)