-
Notifications
You must be signed in to change notification settings - Fork 11
/
emailing.py
39 lines (30 loc) · 1.4 KB
/
emailing.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
"""Module for sending emails using the account specified by the environment variables"""
import os
import sys
import logging
import smtplib, ssl
from dotenv import load_dotenv
load_dotenv()
local_dev = os.getenv("LOCAL_DEV") == "true"
logger = logging.getLogger()
logging.basicConfig(stream=sys.stdout)
logger.setLevel(logging.INFO)
def send_email(message: str, subject: str):
"""Sends email with specified message and subject"""
if local_dev:
return
if os.getenv("ERROR_EMAIL_ADDRESS") and os.getenv("ERROR_EMAIL_ADDRESS_PASSWORD"):
email, password = os.getenv("ERROR_EMAIL_ADDRESS"), os.getenv("ERROR_EMAIL_ADDRESS_PASSWORD")
port, smtp_server, context = 465, "smtp.gmail.com", ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(email, password)
server.sendmail(email, email, f"Subject: Eviction-scraper: {subject}\n\n{message}\n")
else:
logger.error("Cannot send email because the necessary environment variables (ERROR_EMAIL_ADDRESS and ERROR_EMAIL_ADDRESS_PASSWORD) do not exist.")
def log_and_email(message: str, subject: str, error=False):
"""Sends email with specified message and subject and prints the message to logs"""
if error:
logger.error(f"{subject}:\n{message}")
else:
logger.info(f"{subject}:\n{message}")
send_email(message, subject)