· 6 years ago · Aug 24, 2019, 02:58 PM
1#!/usr/bin/env python3
2from email import encoders
3from email.mime.base import MIMEBase
4from email.mime.multipart import MIMEMultipart
5from email.mime.text import MIMEText
6import itertools
7import os
8import shutil
9import smtplib
10import time
11
12INTERVAL = 10
13FOLDER = r'C:\Users\myname\Desktop\pictures'
14SOURCE_EMAIL = '@gmail.com'
15PASSWORD = 'p'
16DEST_EMAIL = '@gmail.com'
17SUBJECT = 'Test sa slanjem i brisanjem 4' # The subject line
18MESSAGE = 'sa attachmentom'
19
20
21def add_attachment(msg, file_location):
22 part = MIMEBase('application', 'octet-stream')
23 with open(file_location, 'rb') as attachment:
24 part.set_payload(attachment.read())
25 encoders.encode_base64(part)
26 part.add_header('Content-Disposition', f'attachment; filename= {os.path.basename(file_location)}')
27 msg.attach(part)
28
29
30def wait():
31 print(f'scanning again in {INTERVAL} seconds')
32 time.sleep(INTERVAL)
33
34
35def main():
36 for count in itertools.count():
37 if count >= 3:
38 break
39
40 try:
41 contents = os.listdir(FOLDER)
42 except OSError as e:
43 print(f'error reading directory contents: {e}')
44 wait()
45 continue
46
47 if not contents:
48 print('folder was empty')
49 wait()
50 continue
51
52 msg = MIMEMultipart()
53 msg['From'] = SOURCE_EMAIL
54 msg['To'] = DEST_EMAIL
55 msg['Subject'] = SUBJECT
56
57 msg.attach(MIMEText(MESSAGE, 'plain'))
58
59 # attach files
60 for file in contents:
61 filepath = os.path.join(FOLDER, file)
62 try:
63 add_attachment(msg, filepath)
64 except OSError as e:
65 print(f"error with file '{file}': {e}")
66 print(f'skipping file: {file}')
67 continue
68 print(f"attaching file '{file}'")
69 os.remove(filepath)
70 print(f"deleted file '{file}'")
71
72 # send email
73 server = smtplib.SMTP('smtp.gmail.com', 587)
74 server.starttls()
75 server.login(SOURCE_EMAIL, PASSWORD)
76 text = msg.as_string()
77 server.sendmail(SOURCE_EMAIL, DEST_EMAIL, text)
78 server.quit()
79 print('pictures sent')
80
81 wait()
82
83
84if __name__ == '__main__':
85 main()