Spaces:
Configuration error
Configuration error
Upload mailer_quant.py
Browse files- mailer_quant.py +63 -0
mailer_quant.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import email, smtplib, ssl
|
2 |
+
from datetime import datetime
|
3 |
+
from email import encoders
|
4 |
+
from email.mime.base import MIMEBase
|
5 |
+
from email.mime.multipart import MIMEMultipart
|
6 |
+
from email.mime.text import MIMEText
|
7 |
+
import os
|
8 |
+
|
9 |
+
class Mailer():
|
10 |
+
|
11 |
+
def __init__(self, subject, body, html, receiver):
|
12 |
+
self.subject = subject
|
13 |
+
self.body = body
|
14 |
+
self.html = html
|
15 |
+
self.sender_email = os.environ.get('EMAIL_SENDER')
|
16 |
+
self.receiver_email = receiver
|
17 |
+
self.password = os.environ.get('EMAIL_PASSWORD')
|
18 |
+
self.message = None
|
19 |
+
self.create_message()
|
20 |
+
|
21 |
+
|
22 |
+
def create_message(self, filepath=None, filename=None):
|
23 |
+
# Create a multipart message and set headers
|
24 |
+
message = MIMEMultipart()
|
25 |
+
message["From"] = self.sender_email
|
26 |
+
message["To"] = self.receiver_email
|
27 |
+
message["Subject"] = self.subject
|
28 |
+
message["Bcc"] = self.receiver_email # Recommended for mass emails
|
29 |
+
# Add body to email
|
30 |
+
if self.html:
|
31 |
+
message.attach(MIMEText(self.html, "html"))
|
32 |
+
elif self.body:
|
33 |
+
message.attach(MIMEText(self.body, "plain"))
|
34 |
+
#filename = "test.pdf" # In same directory as script
|
35 |
+
# Open PDF file in binary mode
|
36 |
+
if filepath and filename:
|
37 |
+
with open(filepath, "rb") as attachment:
|
38 |
+
# Add file as application/octet-stream
|
39 |
+
# Email client can usually download this automatically as attachment
|
40 |
+
part = MIMEBase("application", "octet-stream")
|
41 |
+
part.set_payload(attachment.read())
|
42 |
+
|
43 |
+
# Encode file in ASCII characters to send by email
|
44 |
+
encoders.encode_base64(part)
|
45 |
+
|
46 |
+
# Add header as key/value pair to attachment part
|
47 |
+
part.add_header(
|
48 |
+
"Content-Disposition",
|
49 |
+
f"attachment; filename= {filename}",
|
50 |
+
)
|
51 |
+
|
52 |
+
# Add attachment to message and convert message to string
|
53 |
+
message.attach(part)
|
54 |
+
self.text = message.as_string()
|
55 |
+
return
|
56 |
+
|
57 |
+
def send_message(self, receiver):
|
58 |
+
# Log in to server using secure context and send email
|
59 |
+
context = ssl.create_default_context()
|
60 |
+
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
|
61 |
+
server.login(self.sender_email, self.password)
|
62 |
+
server.sendmail(self.sender_email, receiver, self.text)
|
63 |
+
|