~linuxgoose/bocpress

ref: 16ffd8e75ae0637489ad15138c74641b0317f4a7 bocpress/main/management/commands/testbulkmail.py -rw-r--r-- 2.2 KiB
16ffd8e7Jordan Robinson add atom feed 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import time

from django.conf import settings
from django.core import mail
from django.core.management.base import BaseCommand


def get_mail_connection():
    return mail.get_connection(
        "django.core.mail.backends.smtp.EmailBackend",
        host=settings.EMAIL_HOST_BROADCASTS,
    )


def get_email_body():
    body = """The need for webrings stemmed during the 90s when there was no
Google and search engines were inefficient in helping people
discover web content.

The need re-arises in 2020, when search engines are influenced by SEO
techniques and content platforms have become silos. These days, an indie
web revival would be incredible.

A webring has a specific theme, and the links that comprise it are
curated. Manually curating a webring's content means that it has been
agreed that the website's content is relevant to the webring's theme.
The modern web approach would be to add a neural network to figure out
the website's theme, but that would be totally not fly!
"""

    return body


def get_email(address):
    email = mail.EmailMessage(
        subject="Hey, this is a test",
        body=get_email_body(),
        from_email=f"Mataroa Test Agency <testing@{settings.EMAIL_FROM_HOST}>",
        to=[address],
    )
    return email


class Command(BaseCommand):
    help = "Sends a few bulk emails to test email provider."

    def handle(self, *args, **options):
        self.stdout.write(self.style.NOTICE("Processing test bulk mails."))

        if not settings.EMAIL_TEST_RECEIVE_LIST:
            self.stdout.write(
                self.style.NOTICE("Setting EMAIL_TEST_RECEIVE_LIST not set.")
            )
            return

        message_list = set()
        for address in settings.EMAIL_TEST_RECEIVE_LIST.split(","):
            email = get_email(address)
            message_list.add(email)

            msg = f"Logging record for '{address}'."
            self.stdout.write(self.style.SUCCESS(msg))

        # sent out messages
        connection = get_mail_connection()
        for message in message_list:
            connection.send_messages([message])
            time.sleep(0.1)

        self.stdout.write(
            self.style.SUCCESS(
                f"Test broadcast sent. Total {len(message_list)} emails."
            )
        )