Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 31 additions & 12 deletions notifications/notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,14 @@ def run(self):
CronJob.sync_cron(cron_rec)


def construct_msg(subject, html, message_id=None, in_reply_to=None):
def construct_msg(cc_addresses, subject, html, message_id=None, in_reply_to=None):
msg = MIMEMultipart("alternative")

msg["Subject"] = subject
msg["From"] = settings.EMAIL_USER.upper()
msg["To"] = "no-reply@ifrc.org"
if cc_addresses:
msg["Cc"] = ",".join(cc_addresses)

if message_id:
msg["Message-ID"] = message_id
Expand All @@ -78,15 +80,29 @@ def construct_msg(subject, html, message_id=None, in_reply_to=None):
return msg


def send_notification(subject, recipients, html, message_id=None, in_reply_to=None, mailtype="", files=None):
def clean_emails(emails):
return [e for e in emails if isinstance(e, str) and e.strip()]


def send_notification(subject, recipients, html, mailtype="", message_id=None, in_reply_to=None, cc_recipients=None, files=None):
"""Generic email sending method, handly only HTML emails currently"""
cc_recipients = cc_recipients or []
if not settings.EMAIL_USER or not settings.EMAIL_API_ENDPOINT:
logger.warning("Cannot send notifications.\n" "No username and/or API endpoint set as environment variables.")
if settings.DEBUG:
print("-" * 22, "EMAIL START", "-" * 22)
print(f"subject={subject}\nrecipients={recipients}\nhtml={html}\nmailtype={mailtype}")
print("-" * 22, "EMAIL END -", "-" * 22)
return

to_addresses = clean_emails(recipients)
cc_addresses = clean_emails(cc_recipients)
addresses = to_addresses + cc_addresses

if not addresses:
logger.info("No valid email addresses provided for sending the notification.")
return

if settings.DEBUG_EMAIL:
print("-" * 22, "EMAIL START", "-" * 22)
print(f"\n{html}\n")
Expand All @@ -95,19 +111,18 @@ def send_notification(subject, recipients, html, message_id=None, in_reply_to=No
if settings.FORCE_USE_SMTP:
logger.info("Forcing SMPT usage for sending emails.")
msg = construct_msg(
subject=subject,
html=html,
cc_addresses,
subject,
html,
message_id=message_id,
in_reply_to=in_reply_to,
)
SendMail(recipients, msg).start()
SendMail(addresses, msg).start()
return

if "?" not in settings.EMAIL_API_ENDPOINT: # a.k.a dirty disabling email sending
return

to_addresses = recipients if isinstance(recipients, list) else [recipients]

# if not IS_PROD:
# logger.info('Using test email addresses...')
# to_addresses = []
Expand All @@ -127,6 +142,7 @@ def send_notification(subject, recipients, html, message_id=None, in_reply_to=No
# to_addresses.append(eml)

recipients_as_string = ",".join(to_addresses)
cc_recipients_as_string = ",".join(cc_addresses)
if not recipients_as_string:
if len(to_addresses) > 0:
warn_msg = "Recipients failed to be converted to string, 1st rec.: {}".format(to_addresses[0])
Expand All @@ -142,7 +158,7 @@ def send_notification(subject, recipients, html, message_id=None, in_reply_to=No
payload = {
"FromAsBase64": str(base64.b64encode(settings.EMAIL_USER.encode("utf-8")), "utf-8"),
"ToAsBase64": str(base64.b64encode(EMAIL_TO.encode("utf-8")), "utf-8"),
"CcAsBase64": "",
"CcAsBase64": str(base64.b64encode(cc_recipients_as_string.encode("utf-8")), "utf-8"),
"BccAsBase64": str(base64.b64encode(recipients_as_string.encode("utf-8")), "utf-8"),
"SubjectAsBase64": str(base64.b64encode(subject.encode("utf-8")), "utf-8"),
"BodyAsBase64": str(base64.b64encode(html.encode("utf-8")), "utf-8"),
Expand Down Expand Up @@ -171,7 +187,9 @@ def send_notification(subject, recipients, html, message_id=None, in_reply_to=No
# Saving GUID into a table so that the API can be queried with it to get info about
# if the actual sending has failed or not.
NotificationGUID.objects.create(
api_guid=res_text, email_type=mailtype, to_list=f"To: {EMAIL_TO}; Bcc: {recipients_as_string}"
api_guid=res_text,
email_type=mailtype,
to_list=f"To: {EMAIL_TO}; Cc: {cc_recipients_as_string}; Bcc: {recipients_as_string}",
)

logger.info("E-mails were sent successfully.")
Expand All @@ -185,10 +203,11 @@ def send_notification(subject, recipients, html, message_id=None, in_reply_to=No
# Try sending with Python smtplib, if reaching the API fails
logger.warning(f"Authorization/authentication failed ({res.status_code}) to the e-mail sender API.")
msg = construct_msg(
subject=subject,
html=html,
cc_addresses,
subject,
html,
message_id=message_id,
in_reply_to=in_reply_to,
)
SendMail(to_addresses, msg).start()
SendMail(addresses, msg).start()
return res.text
Loading