· 6 years ago · Aug 24, 2019, 02:12 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 file_location = r'C:\Users\myname\Desktop\pictures'
30 folder = r'C:\Users\myname\Desktop\pictures'
31
32 msg = MIMEMultipart()
33 msg['From'] = email
34 msg['To'] = send_to_email
35 msg['Subject'] = subject
36
37 msg.attach(MIMEText(message, 'plain'))
38
39 for count in itertools.count():
40 if count >= 3:
41 break
42
43 if os.path.exists(file_location) and os.path.getsize(file_location) > 0:
44 for file in os.listdir(r'C:\Users\Borna\Desktop\pictures'):
45 add_attachment(msg, os.path.join(r'C:\Users\Borna\Desktop\pictures', file))
46 print(file)
47
48 server = smtplib.SMTP('smtp.gmail.com', 587)
49 server.starttls()
50 server.login(email, password)
51 text = msg.as_string()
52 server.sendmail(email, send_to_email, text)
53 server.quit()
54 print('pictures sent')
55
56 for the_file in os.listdir(folder):
57 file_path = os.path.join(folder, the_file)
58 try:
59 if os.path.isfile(file_path):
60 os.unlink(file_path)
61 elif os.path.isdir(file_path):
62 shutil.rmtree(file_path)
63 except Exception as e:
64 print(e)
65 print('content of file deleted')
66 time.sleep(10)
67 print('scanning again')
68 else:
69 print('scanning again empty')
70 time.sleep(10)
71
72
73main()