-
Notifications
You must be signed in to change notification settings - Fork 1
/
python_email_send.py
95 lines (75 loc) · 2.9 KB
/
python_email_send.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import smtplib,ssl
import sys
import os
import socket
import ntpath
import datetime
from email.mime.base import MIMEBase
from email import Encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
class send_emails:
def __init__(self):
self.sender_email=''
self.receiver_email=''
self.password=''
#self.context_=''
def user_input(self):
self.sender_email="[email protected]"
self.receiver_email=["[email protected]"]
self.cc=["[email protected]"]
#self.bcc=["[email protected]"]
self.password="*******"
def user_message(self):
text="""Hi,
Please find the attachments below.
This is system generated mail, so don't reply.
Thanks & regards,
Saayan. """
return text
def read_attachment(self,attachment_):
#import pdb;pdb.set_trace()
with open(attachment_, "rb") as attachment:
# Add file as application/octet-stream
# Email client can usually download this automatically as attachment
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
# Encode file in ASCII characters to send by email
Encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
"Content-Disposition",
"attachment", filename=ntpath.basename(attachment_))
return part
def main(self):
self.user_input()
#import pdb;pdb.set_trace()
message=MIMEMultipart("alternative")
message["Subject"]="Message from python!!"
message["From"]=self.sender_email
message["To"]=",".join([email_id for email_id in self.receiver_email])
message['Cc']=",".join(self.cc)
#message['Bcc']=",".join([email for email in self.bcc])
port =25
text=self.user_message()
part1=MIMEText(text,"plain")
message.attach(part1)
filenames=['holiday_list_caavo.csv','amazon_netflix.xlsx']
for file in filenames:
attachment=os.getcwd()+'/attachments/'+file
file_=self.read_attachment(attachment)
message.attach(file_)
try:
#self.context_=ssl.create_default_context()
server = smtplib.SMTP("smtp.gmail.com",25)
server.ehlo()
server.starttls()
server.login(self.sender_email,self.password)
server.sendmail(self.sender_email,self.receiver_email+self.cc,message.as_string())
server.quit()
print("mail sent to %s %s"%(",".join(self.receiver_email+self.cc),datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
except socket.error as e:
print("retrying........",type(e))
self.main()
object_=send_emails()
object_.main()