コード例 #1
0
    def test_send_with_template(self):
        """
        Ensure mail.send correctly creates templated emails to recipients
        """
        OutgoingEmail.objects.all().delete()
        headers = {'Reply-to': '*****@*****.**'}
        email_template = EmailTemplate.objects.create(
            name='foo', subject='{{bar}}', email_html_text='{{baz}} {{booz}}')
        scheduled_time = timezone.now() + timedelta(days=1)
        email = send(recipients=['*****@*****.**', '*****@*****.**'],
                     sender='*****@*****.**',
                     headers=headers,
                     template=email_template,
                     scheduled_time=scheduled_time)
        self.assertEqual(email.to, ['*****@*****.**', '*****@*****.**'])
        self.assertEqual(email.headers, headers)
        self.assertEqual(email.scheduled_time, scheduled_time)

        # Test without header
        OutgoingEmail.objects.all().delete()
        email = send(recipients=['*****@*****.**', '*****@*****.**'],
                     sender='*****@*****.**',
                     template=email_template)
        self.assertEqual(email.to, ['*****@*****.**', '*****@*****.**'])
        self.assertEqual(email.headers, None)

        # Now with variables
        context = {'bar': 'foo', 'baz': 5, 'booz': (6, 7)}
        OutgoingEmail.objects.all().delete()
        email = send(recipients=['*****@*****.**', '*****@*****.**'],
                     sender='*****@*****.**',
                     template=email_template,
                     variable_dict=context)
        self.assertEqual(email.to, ['*****@*****.**', '*****@*****.**'])
        self.assertEqual(email.headers, None)
        email_message = email.email_message()
        self.assertEqual(email_message.subject, context['bar'])
        self.assertEqual(email_message.alternatives[0][0],
                         str(context['baz']) + " " + str(context['booz']))

        # Now with tags
        OutgoingEmail.objects.all().delete()
        email_template_tags = \
            EmailTemplate.objects.create(name='foo',
                                         subject='{{bar|capfirst}}',
                                         email_html_text='{{ baz }} {{ booz|first }}')
        email = send(recipients=['*****@*****.**', '*****@*****.**'],
                     sender='*****@*****.**',
                     template=email_template_tags,
                     variable_dict=context)
        self.assertEqual(email.to, ['*****@*****.**', '*****@*****.**'])
        self.assertEqual(email.headers, None)
        email_message = email.email_message()
        self.assertEqual(email_message.subject,
                         context['bar'][0].upper() + context['bar'][1:])
        self.assertEqual(email_message.alternatives[0][0],
                         str(context['baz']) + " " + "(")
コード例 #2
0
 def handle(self, *args, **options):
     mail.send(
         sender=config.EMAIL_NOTIFICATION_SENDER,
         recipients=config.EMAIL_TEST_RECIPIENT,
         subject='Dashboard test e-mail',
         message='This is a test email from the dashboard.',
         priority=models.PRIORITY.now,
         html_message='This is a test email from the dashboard <strong>hi</strong>!',
     )
コード例 #3
0
ファイル: feedback.py プロジェクト: forkhammer/example-code
def send_form_data_on_email(template_name: str, form_data: dict) -> None:
    """
    Оправляет данные формы почтой
    :param template_name: Имя шаблона письма
    :param form_data: Данные формы
    :return:
    """
    mail_template = models.EmailTemplate.objects.get(name=template_name)
    mail.send(
        sender=settings.DEFAULT_FROM_EMAIL,
        recipients=settings.NOTICE_FEEDBACK_EMAIL,
        template=mail_template,
        variable_dict=form_data,
        priority=models.PRIORITY.now,
    )
コード例 #4
0
 def test_string_priority(self):
     """
     Regression test for:
     https://github.com/ui/django-post_office/issues/23
     """
     email = send('*****@*****.**', ['*****@*****.**'], priority='low')
     self.assertEqual(email.priority, PRIORITY.low)
コード例 #5
0
 def test_send_recipient_display_name(self):
     """
     Regression test for:
     https://github.com/ui/django-post_office/issues/73
     """
     email = send(recipients=['Alice Bob <*****@*****.**>'],
                  sender='*****@*****.**')
     self.assertTrue(email.to)
コード例 #6
0
    def test_string_priority_exception(self):
        invalid_priority_send = lambda: send(
            ['*****@*****.**'], '*****@*****.**', priority='hgh')

        with self.assertRaises(ValueError) as context:
            invalid_priority_send()

        self.assertEqual(
            str(context.exception),
            'Invalid priority, must be one of: low, medium, high, now')
コード例 #7
0
    def test_send_template(self):
        # First try it manually
        template = EmailTemplate.objects.create(name='first', description='desc', subject='{{id}}',
                                                email_html_text='{{id}}')
        email = create(self.test_from_email, self.test_from_email, template=template, priority=PRIORITY.now,
                       backend='custom')
        v = TemplateVariable.objects.create(name='id', value=1, email=email)
        email = OutgoingEmail.objects.get(id=1)
        email.dispatch()

        # Then try it with send()
        email = send(self.test_from_email, self.test_from_email, template=template, priority=PRIORITY.now,
                     backend='custom', variable_dict={'id': 1})
コード例 #8
0
ファイル: incoming.py プロジェクト: balaraju1278/django-hrms
    def reply(self, **kwargs):
        """Sends a message as a reply to this message instance.

        Although Django's e-mail processing will set both IncomingEmail-ID
        and Date upon generating the e-mail message, we will not be able
        to retrieve that information through normal channels, so we must
        pre-set it.

        """
        from django_mail_admin.mail import send
        if 'sender' not in kwargs:
            if len(self.from_address) == 0 and not self.mailbox.from_email:
                raise ValidationError('No sender address to reply from, %s' %
                                      str(self))
            else:
                kwargs[
                    'sender'] = self.from_address[0] or self.mailbox.from_email
        headers = self.get_reply_headers(kwargs.get('headers'))
        kwargs['headers'] = headers
        return send(**kwargs)
コード例 #9
0
    def test_send_without_template(self):
        headers = {'Reply-to': '*****@*****.**'}
        scheduled_time = timezone.now() + timedelta(days=1)
        email = send(sender='*****@*****.**',
                     recipients=['*****@*****.**', '*****@*****.**'],
                     cc=['*****@*****.**', '*****@*****.**'],
                     bcc=['*****@*****.**', '*****@*****.**'],
                     subject='foo',
                     message='bar',
                     html_message='baz',
                     headers=headers,
                     scheduled_time=scheduled_time,
                     priority=PRIORITY.low)

        self.assertEqual(email.to, ['*****@*****.**', '*****@*****.**'])
        self.assertEqual(email.cc, ['*****@*****.**', '*****@*****.**'])
        self.assertEqual(email.bcc, ['*****@*****.**', '*****@*****.**'])
        self.assertEqual(email.subject, 'foo')
        self.assertEqual(email.message, 'bar')
        self.assertEqual(email.html_message, 'baz')
        self.assertEqual(email.headers, headers)
        self.assertEqual(email.priority, PRIORITY.low)
        self.assertEqual(email.scheduled_time, scheduled_time)
コード例 #10
0
 def test_default_priority(self):
     email = send(recipients=['*****@*****.**'], sender='*****@*****.**')
     self.assertEqual(email.priority, PRIORITY.medium)
コード例 #11
0
 def test_send_no_template(self):
     email = send(self.test_from_email, self.test_from_email, subject='Test', message='Testing',
                  priority=PRIORITY.now, backend='custom')
コード例 #12
0
def send_scan_finished_mails(scan: AccountInternetNLScan) -> int:
    """
    Sends mails, depending on user configuration, to all users associated with a scan.

    Will adhere user settings such as language and mail preferences.

    :param scan:
    :return:
    """
    if not scan.report:
        log.error(f'Tried to send a finished mail for a report that was not finished. Scan: {scan}')
        return 0

    users = get_users_to_send_mail_to(scan)

    # remove calculation because textfields are slow while filtering. Have to retrieve the textfield later
    report = UrlListReport.objects.all().filter(id=scan.report.id).order_by("-id").defer('calculation').first()

    for user in users:

        # set unsubscribe code if it's not set yet. This allows the user to instantly unsubscribe from this feed.
        if user.dashboarduser.mail_after_mail_unsubscribe_code == "":
            user.dashboarduser.mail_after_mail_unsubscribe_code = generate_unsubscribe_code()
            user.dashboarduser.save()

        placeholders = {
            "unsubscribe_code": user.dashboarduser.mail_after_mail_unsubscribe_code,

            "recipient": user.first_name if user.first_name else user.last_name if user.last_name else user.username,
            "user_id": user.id,

            "list_name": scan.urllist.name,

            "report_id": report.id,
            "report_average_internet_nl_score": report.average_internet_nl_score,
            "report_number_of_urls": report.total_urls,

            "scan_id": scan.id,
            "scan_started_on": None,
            # the scan is not yet completely finished, because this step (mailing) is still performed
            # so perform a guess, which might be a few minutes off...
            "scan_finished_on": timezone.now().isoformat(),
            "scan_duration": 0,
            # Don't use 'mail_dashboard', only mail.
            "scan_type": "",

            "dashboard_address": config.EMAIL_DASHBOARD_ADDRESS,
        }

        # could be None, strictly speaking
        if scan.scan:
            placeholders['scan_type'] = scan.scan.type \
                if scan.scan.type == "web" else "all" if scan.scan.type == "all" else "mail"

        if scan.started_on:
            placeholders['scan_started_on'] = scan.started_on.isoformat()
            placeholders['scan_duration'] = (timezone.now() - scan.started_on).seconds

        previous = values_from_previous_report(
            report.id,
            report.get_previous_report_from_this_list(),
            user.dashboarduser.mail_preferred_language.code.lower()
        )
        placeholders = {**placeholders, **previous}

        mail.send(
            sender=config.EMAIL_NOTIFICATION_SENDER,
            recipients=user.dashboarduser.mail_preferred_mail_address,  # List of email addresses also accepted
            template=xget_template(
                template_name="scan_finished",
                preferred_language=user.dashboarduser.mail_preferred_language.code.lower()
            ),
            variable_dict=placeholders
        )

    # number of mails sent is equal to users configured their account to receive mails.
    return len(users)
コード例 #13
0
 def test_get_invalid_backend(self):
     with self.assertRaises(ValueError):
         send('*****@*****.**', backend='some_non_existing')