· 6 years ago · Aug 24, 2019, 02:16 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
11
12def add_attachment(msg, file_location):
13 filename = os.path.basename(file_location)
14 attachment = open(file_location, 'rb')
15 part = MIMEBase('application', 'octet-stream')
16 part.set_payload(attachment.read())
17 encoders.encode_base64(part)
18 part.add_header('Content-Disposition', 'attachment; filename= %s' % filename)
19 attachment.close()
20 msg.attach(part)
21
22
23def main():
24 email = '@gmail.com'
25 password = 'p'
26 send_to_email = '@gmail.com'
27 subject = 'Test sa slanjem i brisanjem 4' # The subject line
28 message = 'sa attachmentom'
29 folder = r'C:\Users\myname\Desktop\pictures'
30
31 msg = MIMEMultipart()
32 msg['From'] = email
33 msg['To'] = send_to_email
34 msg['Subject'] = subject
35
36 msg.attach(MIMEText(message, 'plain'))
37
38 for count in itertools.count():
39 if count >= 3:
40 break
41
42 if os.path.exists(folder) and os.path.getsize(folder) > 0:
43 for file in os.listdir(r'C:\Users\Borna\Desktop\pictures'):
44 add_attachment(msg, os.path.join(r'C:\Users\Borna\Desktop\pictures', file))
45 print(file)
46
47 server = smtplib.SMTP('smtp.gmail.com', 587)
48 server.starttls()
49 server.login(email, password)
50 text = msg.as_string()
51 server.sendmail(email, send_to_email, text)
52 server.quit()
53 print('pictures sent')
54
55 for the_file in os.listdir(folder):
56 file_path = os.path.join(folder, the_file)
57 try:
58 if os.path.isfile(file_path):
59 os.unlink(file_path)
60 elif os.path.isdir(file_path):
61 shutil.rmtree(file_path)
62 except Exception as e:
63 print(e)
64 print('content of file deleted')
65 time.sleep(10)
66 print('scanning again')
67 else:
68 print('scanning again empty')
69 time.sleep(10)
70
71
72main()