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