-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsend_email.py
85 lines (74 loc) · 2.84 KB
/
send_email.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
import json
import smtplib
import socket
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.header import Header
import mimetypes
class Email:
def __init__(self, conf_file):
self.client = None
self.user = None
password = None
try:
with open(conf_file) as config:
data = json.load(config)
self.user = data['email']
password = data['password']
except KeyError as e:
print("Failed to load email configuaration", e)
except FileNotFoundError as e:
print("Email configuaration file not found ({})".format(e))
if self.user and password:
try:
self.client = smtplib.SMTP('smtp.gmail.com:587', timeout=3)
print('server ok!')
self.client.ehlo() # Can be omitted
self.client.starttls() # Secure the connection
self.client.ehlo() # Can be omitted
self.client.login(self.user, password)
print("successfully logged in")
except smtplib.SMTPException as e:
print("Error connecting:", e)
except socket.timeout as e:
print("Connection timed out:", e)
def __del__(self):
if self.client:
try:
self.client.quit()
except smtplib.SMTPServerDisconnected:
pass
def send_email(self, attachments, receiver):
if not self.client:
no_client = "Email client not initialized correctly"
print(no_client)
return no_client
try:
mail = Email._make_mime("IEEE CS - UFRN", receiver, "CS face-filters",
"Requested image attached!", attachments)
self.client.sendmail(self.user, receiver, mail.as_string())
print("sent successfully!")
except smtplib.SMTPException as e:
print("error connecting: ", e)
return str(e)
else:
return "Email sent successfully!"
def _get_attach_msg(path):
fp = open(path, 'rb')
msg = MIMEImage(fp.read())
fp.close()
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=path.split('/')[-1])
return msg
def _make_mime(mail_from, mail_to, subject, body, attach_path):
'''create MIME'''
msg = MIMEMultipart()
msg.set_charset
msg['From'] = Header(mail_from, 'ascii')
msg['To'] = Header(mail_to, 'ascii')
msg['Subject'] = Header(subject, 'ascii')
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
msg.attach(MIMEText(body,'plain'))
msg.attach(Email._get_attach_msg(attach_path))
return msg