def dispatch(email: post_office_models.Email,
             log_level: Optional[int] = None,
             disconnect_after_delivery: bool = True, commit: bool = True) -> Optional[InboxMessage]:
    assert hasattr(email, '_cached_email_message')
    email_message = email.email_message()
    assert isinstance(email_message, ProviderEmailMessage)

    status = email.dispatch(log_level, disconnect_after_delivery, commit)

    if status == post_office_models.STATUS.sent:
        inbox_message = email_message.incoming_message
        assert inbox_message is not None
        return inbox_message

    return None
Exemplo n.º 2
0
def test_send_notification_recipients_str(mock_mail, file_html):
    mock_mail.send.return_value = Email()
    recipients = "*****@*****.**"
    with patch.object(Notification, 'save'):
        utils.send_notification(recipients, content_filename=file_html)
    # we called send with all the proper args
    mock_mail.send.assert_called()
    call_kwargs = mock_mail.send.call_args[1]
    assert [recipients] == call_kwargs["recipients"]
Exemplo n.º 3
0
def test_send_notification(mock_mail, file_html):
    mock_mail.send.return_value = Email()
    recipients = ["*****@*****.**"]
    with patch.object(Notification, 'save'):
        utils.send_notification(recipients, content_filename=file_html)
    # we called send with all the proper args
    mock_mail.send.assert_called()
    call_kwargs = mock_mail.send.call_args[1]
    assert settings.DEFAULT_FROM_EMAIL == call_kwargs['sender']
    assert recipients == call_kwargs["recipients"]
Exemplo n.º 4
0
def test_sender_is_not_a_user(mock_mail):
    "If sender is not a User, send DEFAULT_FROM_EMAIL"
    mock_mail.send.return_value = Email()
    notification = NotificationFactory()
    with patch.object(Notification, 'save'):
        notification.send_mail()
    # we called send ...
    mock_mail.send.assert_called()
    call_kwargs = mock_mail.send.call_args[1]
    # ... with the proper email
    assert settings.DEFAULT_FROM_EMAIL == call_kwargs['sender']
Exemplo n.º 5
0
def test_ignore_mail_sending_error(mock_mail):
    "If sending throws an error, we log and continue."
    mock_mail.send.side_effect = Exception()
    notification = NotificationFactory()
    mock_mail.send.return_value = Email()
    with patch.object(Notification, 'save'):
        with patch('unicef_notification.models.logger') as mock_logger:
            notification.send_mail()
    mock_logger.exception.assert_called_with('Failed to send mail.')
    # recipients weren't marked as successful
    assert notification.sent_recipients == []
Exemplo n.º 6
0
def test_send_notification_with_template(mock_mail, email_template):
    mock_mail.send.return_value = Email()
    recipients = ["*****@*****.**"]
    with patch.object(Notification, 'save'):
        utils.send_notification_with_template(recipients, email_template.name,
                                              {})
    # we called send with all the proper args
    mock_mail.send.assert_called()
    call_kwargs = mock_mail.send.call_args[1]
    assert settings.DEFAULT_FROM_EMAIL == call_kwargs['sender']
    assert recipients == call_kwargs["recipients"]
Exemplo n.º 7
0
def test_sender_is_from_address(mock_mail):
    "If sender is not a User, use from address if set"
    mock_mail.send.return_value = Email()
    from_address = "*****@*****.**"
    notification = NotificationFactory(from_address=from_address)
    with patch.object(Notification, 'save'):
        notification.send_mail()
    # we called send ...
    mock_mail.send.assert_called()
    call_kwargs = mock_mail.send.call_args[1]
    # ... with the proper email
    assert from_address == call_kwargs['sender']
Exemplo n.º 8
0
def test_sender_is_user(mock_mail):
    "If sender is a User, send from their email address"
    sender = UserFactory()
    notification = NotificationFactory(sender=sender)
    mock_mail.send.return_value = Email()
    with patch.object(Notification, 'save'):
        notification.send_mail()
    # we called send ...
    mock_mail.send.assert_called()
    call_kwargs = mock_mail.send.call_args[1]
    # ... with the proper email
    assert sender.email == call_kwargs['sender']
Exemplo n.º 9
0
 def test_sender_is_not_a_user(self, mock_mail):
     "If sender is not a User, send DEFAULT_FROM_EMAIL"
     mock_mail.send.return_value = Email()
     notification = NotificationFactory()
     with mock.patch.object(Notification,
                            'save'):  # Don't actually try to save it
         notification.send_mail()
     # we called send ...
     mock_mail.send.assert_called()
     call_kwargs = mock_mail.send.call_args[1]
     # ... with the proper email
     self.assertEqual(settings.DEFAULT_FROM_EMAIL, call_kwargs['sender'])
Exemplo n.º 10
0
def test_template_data_is_str(mock_mail):
    "We accept string data for the template context."
    template_data = '{"foo": "bar"}'
    notification = NotificationFactory(template_data=template_data)
    mock_mail.send.return_value = Email()
    with patch.object(Notification, 'save'):
        notification.send_mail()
    # we called send ...
    mock_mail.send.assert_called()
    call_kwargs = mock_mail.send.call_args[1]
    # ... with the proper context
    assert {'foo': 'bar'} == call_kwargs['context']
Exemplo n.º 11
0
 def test_ignore_mail_sending_error(self, mock_mail):
     "If sending throws an error, we log and continue."
     mock_mail.send.side_effect = Exception()
     notification = NotificationFactory()
     mock_mail.send.return_value = Email()
     with mock.patch.object(Notification,
                            'save'):  # Don't actually try to save it
         with patch('etools.applications.notification.models.logger'
                    ) as mock_logger:
             notification.send_mail()
     mock_logger.exception.assert_called_with('Failed to send mail.')
     # recipients weren't marked as successful
     self.assertEqual(notification.sent_recipients, [])
Exemplo n.º 12
0
def test_send_notification_from_address(mock_mail, file_html):
    mock_mail.send.return_value = Email()
    recipients = ["*****@*****.**"]
    from_address = "*****@*****.**"
    with patch.object(Notification, 'save'):
        utils.send_notification(recipients,
                                from_address=from_address,
                                content_filename=file_html)
    # we called send with all the proper args
    mock_mail.send.assert_called()
    call_kwargs = mock_mail.send.call_args[1]
    assert from_address == call_kwargs['sender']
    assert recipients == call_kwargs["recipients"]
Exemplo n.º 13
0
 def test_sender_is_user(self, mock_mail):
     "If sender is a User, send from their email address"
     sender = UserFactory()
     notification = NotificationFactory(sender=sender)
     mock_mail.send.return_value = Email()
     with mock.patch.object(Notification,
                            'save'):  # Don't actually try to save it
         notification.send_mail()
     # we called send ...
     mock_mail.send.assert_called()
     call_kwargs = mock_mail.send.call_args[1]
     # ... with the proper email
     self.assertEqual(sender.email, call_kwargs['sender'])
Exemplo n.º 14
0
 def test_template_data_is_str(self, mock_mail):
     "We accept string data for the template context."
     template_data = '{"foo": "bar"}'
     notification = NotificationFactory(template_data=template_data)
     mock_mail.send.return_value = Email()
     with mock.patch.object(Notification,
                            'save'):  # Don't actually try to save it
         notification.send_mail()
     # we called send ...
     mock_mail.send.assert_called()
     call_kwargs = mock_mail.send.call_args[1]
     # ... with the proper context
     self.assertEqual({'foo': 'bar'}, call_kwargs['context'])
Exemplo n.º 15
0
def test_send_notification_with_template_recipients_str(
        mock_mail, email_template):
    mock_mail.send.return_value = Email()
    recipients = "*****@*****.**"
    with patch.object(Notification, 'save'):
        utils.send_notification_with_template(
            recipients,
            email_template.name,
            {},
        )
    # we called send with all the proper args
    mock_mail.send.assert_called()
    call_kwargs = mock_mail.send.call_args[1]
    assert [recipients] == call_kwargs["recipients"]
def add_tracking_info(email: post_office_models.Email,
                      click_tracking: bool = False,
                      open_tracking: bool = False) -> post_office_models.Email:
    msg_id = email.headers.get('Message-ID', None)

    # TODO: add expectation

    html_message = adapt_html(
        '<html><body>%s</body></html>' % email.html_message,
        extra_metadata={
            'tenant': db_connection.tenant.id,
            'id': msg_id,
        },
        click_tracking=click_tracking,
        open_tracking=open_tracking,
        configuration=get_configuration_from_settings(),
    )

    email.html_message = html_message

    if email.id:
        email.save()

    return email
Exemplo n.º 17
0
def test_send_notification_with_template_from_address(mock_mail,
                                                      email_template):
    mock_mail.send.return_value = Email()
    recipients = ["*****@*****.**"]
    from_address = "*****@*****.**"
    with patch.object(Notification, 'save'):
        utils.send_notification_with_template(
            recipients,
            email_template.name,
            {},
            from_address=from_address,
        )
    # we called send with all the proper args
    mock_mail.send.assert_called()
    call_kwargs = mock_mail.send.call_args[1]
    assert from_address == call_kwargs['sender']
    assert recipients == call_kwargs["recipients"]
def prepare_email_message(email: post_office_models.Email,
                          provider: EmailAccount) -> EmailMultiAlternatives:
    assert hasattr(email, '_cached_email_message')

    msg = provider.create_email(
        subject=email.subject, body=email.message, html_body=email.html_message,
        to=email.to, cc=email.cc, bcc=email.bcc,
        from_email=email.from_email,
        headers=email.headers,
    )

    # todo: support unsaved emails
    for attachment in email.attachments.all():
        msg.attach(attachment.name, attachment.file.read(), mimetype=attachment.mimetype or None)
        attachment.file.close()

    email._cached_email_message = msg
    return msg
Exemplo n.º 19
0
def test_success(mock_mail):
    "On successful notification, sent_recipients should be populated."
    cc = ['*****@*****.**']
    notification = NotificationFactory(template_data={'foo': 'bar'}, cc=cc)
    mock_mail.send.return_value = Email()
    with patch.object(Notification, 'save'):
        notification.send_mail()
    # we called send with all the proper args
    mock_mail.send.assert_called_with(
        recipients=notification.recipients,
        cc=cc,
        sender=settings.DEFAULT_FROM_EMAIL,
        template=notification.template_name,
        context=notification.template_data,
        html_message='',
        message='',
        subject='',
    )
    # we marked the recipients as sent
    assert notification.recipients + cc == notification.sent_recipients
Exemplo n.º 20
0
                                   bcc=self.bcc,
                                   cc=self.cc,
                                   connection=connection,
                                   headers=self.headers)

        for attachment in self.attachments.all():
            mailmsg.attach(attachment.name, attachment.file.read())
        return mailmsg


class EmailManager(models.Manager):
    def get_queryset(self):
        return Email.objects.get_queryset()


OriginalEmail.add_to_class('objects', EmailManager())


class Notification(models.Model):
    """
    A task executed on receiving a signal.
    """
    name = models.CharField(max_length=50, verbose_name=_("Name"))
    transition_target = models.CharField(max_length=50,
                                         verbose_name=_("Event"))
    mail_to = models.PositiveIntegerField(verbose_name=_("Mail to"),
                                          null=True,
                                          blank=True,
                                          default=None)
    mail_template = models.ForeignKey(EmailTemplate,
                                      verbose_name=_("Template"),
Exemplo n.º 21
0
        else:
            mailmsg = EmailMessage(
                subject=subject, body=message, from_email=self.from_email,
                to=self.to, bcc=self.bcc, cc=self.cc,
                connection=connection, headers=self.headers)

        for attachment in self.attachments.all():
            mailmsg.attach(attachment.name, attachment.file.read())
        return mailmsg


class EmailManager(models.Manager):
    def get_queryset(self):
        return Email.objects.get_queryset()

OriginalEmail.add_to_class('objects', EmailManager())


class Notification(models.Model):
    """
    A task executed on receiving a signal.
    """
    name = models.CharField(max_length=50, verbose_name=_("Name"))
    transition_target = models.CharField(max_length=50, verbose_name=_("Event"))
    mail_to = models.PositiveIntegerField(verbose_name=_("Mail to"), null=True,
                                          blank=True, default=None)
    mail_template = models.ForeignKey(EmailTemplate, verbose_name=_("Template"),
                            limit_choices_to=Q(language__isnull=True) | Q(language=''))

    class Meta:
        app_label = 'shop'