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