Skip to content

Commit 79033e2

Browse files
authored
Merge pull request #834 from Somanyu/main
Attachment Downloader
2 parents 1176624 + 844e006 commit 79033e2

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

attachment-downloader/README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Package/Script Name
2+
3+
A python script that automates download of attachments based on various constraints such as file extensions or file name or sender. There is no need of any external library everything is present already.
4+
5+
## Setup instructions
6+
7+
No neeed of any setup just add your email and password in the beginning and mention the path where you want to download the attachments.
8+
9+
## Author(s)
10+
11+
Somanyu
12+
13+
## Disclaimers, if any
14+
15+
Use this section to mention if any particular disclaimer is required

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)