Created
April 1, 2020 06:01
-
-
Save mrsaicharan1/e06e065ccb5278990d6e279fd9d810be to your computer and use it in GitHub Desktop.
email_send.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def send_email(to, action, subject, html, attachments=None): | |
""" | |
Sends email and records it in DB | |
""" | |
from .tasks import send_email_task_sendgrid, send_email_task_smtp | |
if not string_empty(to): | |
email_service = get_settings()['email_service'] | |
email_from_name = get_settings()['email_from_name'] | |
if email_service == 'smtp': | |
email_from = email_from_name + '<' + get_settings()['email_from'] + '>' | |
else: | |
email_from = get_settings()['email_from'] | |
payload = { | |
'to': to, | |
'from': email_from, | |
'subject': subject, | |
'html': html, | |
'attachments': attachments | |
} | |
if not current_app.config['TESTING']: | |
smtp_encryption = get_settings()['smtp_encryption'] | |
if smtp_encryption == 'tls': | |
smtp_encryption = 'required' | |
elif smtp_encryption == 'ssl': | |
smtp_encryption = 'ssl' | |
elif smtp_encryption == 'tls_optional': | |
smtp_encryption = 'optional' | |
else: | |
smtp_encryption = 'none' | |
smtp_config = { | |
'host': get_settings()['smtp_host'], | |
'username': get_settings()['smtp_username'], | |
'password': get_settings()['smtp_password'], | |
'encryption': smtp_encryption, | |
'port': get_settings()['smtp_port'], | |
} | |
smtp_status = check_smtp_config(smtp_encryption) | |
if smtp_status: | |
if email_service == 'smtp': | |
send_email_task_smtp.delay(payload=payload, headers=None, smtp_config=smtp_config) | |
else: | |
key = get_settings().get('sendgrid_key') | |
if key: | |
headers = { | |
"Authorization": ("Bearer " + key), | |
"Content-Type": "application/json" | |
} | |
payload['fromname'] = email_from_name | |
send_email_task_sendgrid.delay(payload=payload, headers=headers, smtp_config=smtp_config) | |
else: | |
logging.exception('SMTP & sendgrid have not been configured properly') | |
else: | |
logging.exception('SMTP is not configured properly. Cannot send email.') | |
# record_mail(to, action, subject, html) | |
mail = Mail( | |
recipient=to, action=action, subject=subject, | |
message=html, time=datetime.utcnow() | |
) | |
save_to_db(mail, 'Mail Recorded') | |
record_activity('mail_event', email=to, action=action, subject=subject) | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment