def test_EmailMessage_attributes(self): """Test that send_at and categories attributes are correctly written through to output.""" msg = EmailMessage( subject="Hello, World!", body="Hello, World!", from_email="Sam Smith <*****@*****.**>", to=["John Doe <*****@*****.**>", "*****@*****.**"], ) # Set new attributes as message property msg.send_at = 1518108670 if SENDGRID_VERSION < '6': msg.categories = ['mammal', 'dog'] else: msg.categories = ['dog', 'mammal'] msg.ip_pool_name = 'some-name' result = self.backend._build_sg_mail(msg) expected = { "personalizations": [{ "to": [{ "email": "*****@*****.**", "name": "John Doe" }, { "email": "*****@*****.**", }], "subject": "Hello, World!", "send_at": 1518108670, }], "from": { "email": "*****@*****.**", "name": "Sam Smith" }, "mail_settings": { "sandbox_mode": { "enable": False } }, "subject": "Hello, World!", "tracking_settings": { "open_tracking": { "enable": True } }, "content": [{ "type": "text/plain", "value": "Hello, World!" }], "categories": ['mammal', 'dog'], "ip_pool_name": "some-name" } self.assertDictEqual(result, expected)
def test_build_sg_email_w_categories(self): msg = EmailMessage() msg.categories = ['name'] with self.settings(SENDGRID_API_KEY='test_key'): mail = SendGridBackend()._build_sg_mail(msg) self.assertEqual( mail, {'categories': ['name'], 'content': [{'type': 'text/plain', 'value': ''}], 'from': {'email': 'webmaster@localhost'}, 'personalizations': [{'subject': ''}], 'subject': '' } )
def test_EmailMessage_attributes(self): """Test that send_at and categories attributes are correctly written through to output.""" msg = EmailMessage( subject="Hello, World!", body="Hello, World!", from_email="Sam Smith <*****@*****.**>", to=["John Doe <*****@*****.**>", "*****@*****.**"], ) # Set new attributes as message property msg.send_at = 1518108670 msg.categories = ['mammal', 'dog'] msg.ip_pool_name = 'some-name' result = self.backend._build_sg_mail(msg) expected = { "personalizations": [{ "to": [{ "email": "*****@*****.**", "name": "John Doe" }, { "email": "*****@*****.**", }], "subject": "Hello, World!", "send_at": 1518108670, }], "from": { "email": "*****@*****.**", "name": "Sam Smith" }, "mail_settings": { "sandbox_mode": { "enable": False } }, "subject": "Hello, World!", "tracking_settings": {"open_tracking": {"enable": True}}, "content": [{ "type": "text/plain", "value": "Hello, World!" }], "categories": ['mammal', 'dog'], "ip_pool_name": "some-name" } self.assertDictEqual(result, expected)
def send_email(template, to, subject, variables=None, fail_silently=False, cms=False, replace_variables=None, sender=None, attachments=None, categories=None): attachments = attachments or [] if variables is None: variables = {} if replace_variables is None: replace_variables = {} variables["site"] = Site.objects.get_current() variables["STATIC_URL"] = settings.STATIC_URL variables["is_secure"] = getattr(settings, "UNIVERSAL_NOTIFICATIONS_IS_SECURE", False) protocol = "https://" if variables["is_secure"] else "http://" variables["protocol"] = protocol replace_variables['protocol'] = protocol domain = variables["site"].domain variables["domain"] = domain replace_variables["domain"] = domain html = render_to_string('emails/email_%s.html' % template, variables) for key, value in replace_variables.items(): if not value: value = "" html = html.replace("{%s}" % key.upper(), value) # Update path to have domains base = protocol + domain if sender is None: sender = settings.DEFAULT_FROM_EMAIL if getattr(settings, "UNIVERSAL_NOTIFICATIONS_USE_PREMAILER", True): html = html.replace("{settings.STATIC_URL}CACHE/".format(settings=settings), "{settings.STATIC_ROOT}/CACHE/".format(settings=settings)) # get local file html = Premailer(html, remove_classes=False, exclude_pseudoclasses=False, keep_style_tags=True, include_star_selectors=True, strip_important=False, cssutils_logging_level=logging.CRITICAL, base_url=base).transform() email = EmailMessage(subject, html, sender, [to], attachments=attachments) if categories: email.categories = categories email.content_subtype = "html" email.send(fail_silently=fail_silently)
def send_email(self, subject, context, receiver): template = self.get_template() html = template.render(context) # update paths base = context["protocol"] + context["domain"] sender = self.sender or settings.DEFAULT_FROM_EMAIL if getattr(settings, "UNIVERSAL_NOTIFICATIONS_USE_PREMAILER", True) and self.use_premailer is not False: html = html.replace( "{settings.STATIC_URL}CACHE/".format(settings=settings), "{settings.STATIC_ROOT}/CACHE/".format( settings=settings)) # get local file html = Premailer(html, remove_classes=False, exclude_pseudoclasses=False, keep_style_tags=True, include_star_selectors=True, strip_important=False, cssutils_logging_level=logging.CRITICAL, base_url=base).transform() # if subject is not provided, try to extract it from <title> tag if not subject: self.email_subject = self.__get_title_from_html(html) subject = self.prepare_subject() email = EmailMessage(subject, html, sender, [receiver], attachments=self.attachments) if self.categories: email.categories = self.categories if self.sendgrid_asm: email.asm = self.sendgrid_asm email.content_subtype = "html" email.send(fail_silently=False)
def send_email(provider, from_email="Salalem <*****@*****.**>", to_emails=None, reply_to_email_header="*****@*****.**", attachment=None, **kwargs): if to_emails is None: to_emails = [] if not provider: raise Exception("A provider arg should be specified") if not isinstance(to_emails, list): raise Exception("to_emails arg should be a list of email addresses") if len(to_emails) == 0: raise Exception( "to_emails list should have at-least one email address") mail = EmailMessage( from_email=from_email, to=to_emails, headers={"Reply-To": reply_to_email_header}, ) mail.content_subtype = "html" if provider == AvailableEmailServiceProviders.sendgrid: if "template_id" not in kwargs: raise Exception( "A template_id arg should be specified with provider: " + provider) mail.template_id = kwargs.get("template_id") if "template_data" not in kwargs: raise Exception( "A template_data arg should be specified with provider: " + provider) dynamic_data = kwargs.get("template_data") try: if dynamic_data["c2a_link"].startswith("https://salalem.com"): dynamic_data["c2a_link"] = dynamic_data["c2a_link"].replace( "https://salalem.com", "https://demo.salalem.com") except: pass mail.dynamic_template_data = kwargs.get("template_data") if "categories" not in kwargs: raise Exception( "A categories list should be specified with provider: " + provider) mail.categories = kwargs.get("categories") # # Attach file # with open('somefilename.pdf', 'rb') as file: # mail.attachments = [ # ('somefilename.pdf', file.read(), 'application/pdf') # ] if attachment: mail.attach( 'Enrollments Report.xlsx', attachment, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) # Add categories return mail.send(fail_silently=False)
def run(self, *args, **kwargs): message_pk = kwargs.get('pk', None) to_addresses = kwargs.get('to_addresses', []) is_manually_sent = kwargs.get('is_manually_sent', False) message = Message.objects.get(pk=message_pk) msg = 'SendMailTask: Trying to send {} to {}'.format( message_pk, to_addresses) logger.info(msg) if isinstance(to_addresses, str): to_addresses = to_addresses.split(',') email = EmailMessage( subject=message.subject, body=message.email.get('body'), from_email=settings.MAIL_FROM_EMAIL, to=to_addresses, bcc=None, reply_to=[settings.MAIL_REPLY_TO], connection=get_connection(backend=settings.MAILER_EMAIL_BACKEND)) for attachment in message.email.get('attachments', []): curated_content = get_curated_content(attachment) try: email.attach(attachment[0], curated_content, attachment[2]) except IndexError: email.attach(attachment[0], curated_content, attachment[1]) try: if email is not None: try: categories = message.category.split(',') if is_manually_sent: email.categories = [ '{}_DEBUG'.format(c) for c in categories ] else: email.categories = categories email.content_subtype = 'html' email.send() msg = 'SendMailTask: Message {} sent to {}'.format( message_pk, to_addresses) logger.info(msg) MessageLog.objects.create( action=settings.MAIL_LOG_ACTIONS_SENT, email=message, message='to: {}'.format(email.to)) except Exception as err: MessageLog.objects.create( action=settings.MAIL_LOG_ACTIONS_FAILED, email=message, message=err) msg = 'SendMailTask Exception: {} - {}'.format( err, message_pk) logger.error(msg) self.retry(countdown=120, max_retries=20) else: msg = 'Message {} discarded due to failure in converting from DB. Added on {}'.format( message_pk, message.created) logger.warning(msg) MessageLog.objects.create( action=settings.MAIL_LOG_ACTIONS_FAILED, email=message, message=msg) except ObjectDoesNotExist: msg = 'SendMailTask Message.ObjectDoesNotExist: {}'.format( message_pk) logger.error(msg) except Exception as exc: msg = 'SendMailTaskException: {}: {}'.format( type(exc).__name__, exc.args) logger.error(msg) self.retry(countdown=120, max_retries=20) capture_exception(exc)