Created
April 1, 2020 06:00
-
-
Save mrsaicharan1/7830fefe1fca461886ef9feab9508f0a to your computer and use it in GitHub Desktop.
scheduled_task_email.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
@celery.task(name='send.email.post.sendgrid') | |
def send_email_task_sendgrid(payload, headers, smtp_config): | |
try: | |
message = Mail(from_email=From(payload['from'], payload['fromname']), | |
to_emails=payload['to'], | |
subject=payload['subject'], | |
html_content=payload["html"]) | |
if payload['attachments'] is not None: | |
for attachment in payload['attachments']: | |
with open(attachment, 'rb') as f: | |
file_data = f.read() | |
f.close() | |
encoded = base64.b64encode(file_data).decode() | |
attachment = Attachment() | |
attachment.file_content = FileContent(encoded) | |
attachment.file_type = FileType('application/pdf') | |
attachment.file_name = FileName(payload['to']) | |
attachment.disposition = Disposition('attachment') | |
message.add_attachment(attachment) | |
sendgrid_client = SendGridAPIClient(get_settings()['sendgrid_key']) | |
logging.info('Sending an email regarding {} on behalf of {}'.format(payload["subject"], payload["from"])) | |
sendgrid_client.send(message) | |
logging.info('Email sent successfully') | |
except urllib.error.HTTPError as e: | |
if e.code == 429: | |
logging.warning("Sendgrid quota has exceeded") | |
send_email_task_smtp.delay(payload=payload, headers=None, smtp_config=smtp_config) | |
elif e.code == 554: | |
empty_attachments_send(sendgrid_client, message) | |
else: | |
logging.exception("The following error has occurred with sendgrid-{}".format(str(e))) | |
@celery.task(name='send.email.post.smtp') | |
def send_email_task_smtp(payload, smtp_config, headers=None): | |
mailer_config = { | |
'transport': { | |
'use': 'smtp', | |
'host': smtp_config['host'], | |
'username': smtp_config['username'], | |
'password': smtp_config['password'], | |
'tls': smtp_config['encryption'], | |
'port': smtp_config['port'] | |
} | |
} | |
try: | |
mailer = Mailer(mailer_config) | |
mailer.start() | |
message = Message(author=payload['from'], to=payload['to']) | |
message.subject = payload['subject'] | |
message.plain = strip_tags(payload['html']) | |
message.rich = payload['html'] | |
if payload['attachments'] is not None: | |
for attachment in payload['attachments']: | |
message.attach(name=attachment) | |
mailer.send(message) | |
logging.info('Message sent via SMTP') | |
except urllib.error.HTTPError as e: | |
if e.code == 554: | |
empty_attachments_send(mailer, message) | |
mailer.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment