Demo entry 6783365

"""Mailgun email backend class."""importrequestsfromdjango.confimportsettingsfromdjango.core.mail.backends.baseimportBaseEmailBackendfromdjango.core.mail.messageimportsanitize_addressclassMailgunBackend(BaseEmailBackend):""" A wrapper that manages mailgun API """def__init__(self,url=None,fail_silently=False):super().__init__(fail_silently=fail_silently)self.url=urlorsettings.MAILGUN_API_URLself.api_key=settings.MAILGUN_API_KEYdefsend_messages(self,email_messages):""" Send one or more EmailMessage objects and return the number of email messages sent. """ifnotemail_messages:returnnum_sent=0formessageinemail_messages:sent=self._send(message)ifsent:num_sent+=1returnnum_sentdef_send(self,email_message):"""A helper method that does the actual sending."""ifnotemail_message.recipients():returnFalseencoding=email_message.encodingorsettings.DEFAULT_CHARSETfrom_email=sanitize_address(email_message.from_email,encoding)recipients=[sanitize_address(addr,encoding)foraddrinemail_message.recipients()]body=email_message.bodyreply_to=email_message.reply_toorNonetry:requests.post(self.url,auth=("api",self.api_key),data={"from":from_email,"to":recipients,"subject":email_message.subject,"text":body,"h:Reply-To":reply_to})exceptException:ifnotself.fail_silently:raisereturnFalsereturnTrue