-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathemail_tools.py
58 lines (49 loc) · 1.64 KB
/
email_tools.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
import os
from dotenv import load_dotenv
import background
load_dotenv()
SMTP_MAILHOST_HOST = os.getenv("SMTP_MAILHOST_HOST")
SMTP_MAILHOST_PORT = int(os.getenv("SMTP_MAILHOST_PORT"))
SMTP_MAILHOST = (
SMTP_MAILHOST_HOST,
SMTP_MAILHOST_PORT,
) # noqa: E501
SMTP_FROMADDR = os.getenv("SMTP_FROMADDR")
SMTP_TOADDRS = os.getenv("SMTP_TOADDRS")
SMTP_SUBJECT = os.getenv("SMTP_SUBJECT")
SMTP_CREDENTIALS_EMAIL = os.getenv("SMTP_CREDENTIALS_EMAIL")
SMTP_CREDENTIALS_PASSWORD = os.getenv("SMTP_CREDENTIALS_PASSWORD") # noqa: E501
SMTP_CREDENTIALS = (
SMTP_CREDENTIALS_EMAIL,
SMTP_CREDENTIALS_PASSWORD,
)
SMTP_SECURE = os.getenv("SMTP_SECURE")
if SMTP_SECURE == "()":
SMTP_SECURE = ()
else:
SMTP_SECURE = None
SMTP_TIMEOUT = int(os.getenv("SMTP_TIMEOUT"))
@background.task
def send_email(subject, from_email, to_email, body):
try:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Create a text/plain message with body
msg = EmailMessage()
msg.set_content(body)
msg["Subject"] = subject
msg["From"] = from_email
msg["To"] = to_email
# Send the message via our own SMTP server.
s = smtplib.SMTP(host=SMTP_MAILHOST_HOST, port=SMTP_MAILHOST_PORT)
s.connect(SMTP_MAILHOST_HOST, SMTP_MAILHOST_PORT)
s.starttls()
s.login(
user=SMTP_CREDENTIALS_EMAIL, password=SMTP_CREDENTIALS_PASSWORD
) # noqa: E501
s.send_message(msg)
s.quit()
except Exception as e:
print(f"Could not send email: {e}")