def send_email(subject, body, send_to): try: msg = EmailMessage(subject, body, Config.MAIL_USERNAME, [send_to]) msg.content_subtype = "html" msg.send() return True except: current_app.logger.info( 'ERR - Cannot send email, please check MAIL settings') current_app.logger.info(' -> MAIL Subject: ' + subject) current_app.logger.info(' -> MAIL Body: ' + body) return False
def background_task( channel_url, text, subscribers, subject, mfrom, send_uid, attachments=[] ): logger.info( 'Start send "{subject}" to {subscribers} recipients through channel "{channel}".'.format( # noqa subject=subject, subscribers=len(subscribers), channel=channel_url ) ) try: with app.mail.get_connection() as conn: for i, mto in enumerate(subscribers): msg = EmailMessage( from_email=mfrom, to=[mto], body=text, subject=subject, connection=conn, ) msg.content_subtype = "html" for attachment in attachments: msg.attach( filename=attachment.get("filename", ""), content=attachment.get("data", ""), mimetype=attachment.get("content_type", ""), ) try: msg.send() except SMTPRecipientsRefused: logger.info("[SKIP] - {}: invalid address.".format(mto)) if (i + 1) % 1000 == 0: logger.info( "- Sending status: {}/{}".format(i + 1, len(subscribers)) ) except Exception as e: logger.error("Message not sent:") logger.exception(e) send_complete(channel_url=channel_url, send_uid=send_uid, error=True) return send_complete(channel_url=channel_url, send_uid=send_uid) logger.info("Task complete.")