-
Notifications
You must be signed in to change notification settings - Fork 0
/
email_gmail_smtp_with_attachment.py
65 lines (50 loc) · 1.86 KB
/
email_gmail_smtp_with_attachment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Python code to send email with multiple attachments from your Gmail account
import smtplib, os, sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from datetime import date
today = date.today()
#Add your Gmail sender Email address
fromaddr = "[email protected]"
# Add comma separated To addresses to send email
# instance of MIMEMultipart
msg = MIMEMultipart()
# storing the senders email address
msg['From'] = "[email protected]"
# storing the receivers email address
msg['To'] = ",".join(toaddr)
# storing the subject
msg['Subject'] = "My Reports"
# string to store the body of the mail
body = "Hi, \nAttached the reports \nThanks, \nSivaprakash R"
# attach the body with the msg instance
msg.attach(MIMEText(body, 'plain'))
# Add your file location which needs to be attached
attachments = ["/opt/report1-%s.csv"% (today), "/opt/report2-%s.csv"%(today)]
if 'attachments' in globals() and len('attachments') > 0: # are there attachments?
for filename in attachments:
f = filename
# instance of MIMEBase and named as p
p = MIMEBase('application', "octet-stream")
# To change the payload into encoded form
p.set_payload( open(f,"rb").read() )
# encode into base64
encoders.encode_base64(p)
p.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
# attach the instance 'p' to instance 'msg'
msg.attach(p)
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login(fromaddr, "Ku4Ood8ir8pa3ich")
# Converts the Multipart msg into a string
text = msg.as_string()
# sending the mail
s.sendmail(fromaddr, toaddr, text)
# terminating the session
s.quit()