emails.py 2.24 KB
Newer Older
1
"""The emails defined by the newsletters package"""
2

3
from django.conf import settings
4
5
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
6
7
from django.utils import translation, timezone
from django.utils.timezone import make_aware
8
9

from members.models import Member
10
from newsletters import services
11
from partners.models import Partner
12

13

14
def send_newsletter(newsletter):
15
16
    """
    Sends the newsletter as HTML and plaintext email
17

18
19
    :param newsletter: the newsletter to be send
    """
20
21
22
23
24
25
26
27
    events = None
    if newsletter.date:
        datetime = make_aware(timezone.datetime(
            year=newsletter.date.year,
            month=newsletter.date.month,
            day=newsletter.date.day,
        )) if newsletter.date else None
        events = services.get_agenda(datetime)
28
29
30
31
32

    from_email = settings.NEWSLETTER_FROM_ADDRESS
    html_template = get_template('newsletters/email.html')
    text_template = get_template('newsletters/email.txt')

33
34
35
    main_partner = Partner.objects.filter(is_main_partner=True).first()
    local_partner = Partner.objects.filter(is_local_partner=True).first()

36
37
38
39
40
41
42
43
44
45
46
47
48
    for language in settings.LANGUAGES:
        translation.activate(language[0])

        recipients = [member.email for member in
                      Member.current_members.all().filter(
                          profile__receive_newsletter=True,
                          profile__language=language[0])
                      if member.email]

        subject = '[THALIA] ' + newsletter.title

        context = {
            'newsletter': newsletter,
49
            'agenda_events': events,
50
            'main_partner': main_partner,
51
            'local_partner': local_partner,
52
            'lang_code': language[0]
53
54
55
56
57
58
59
60
61
62
63
64
        }

        html_message = html_template.render(context)
        text_message = text_template.render(context)

        msg = EmailMultiAlternatives(subject, text_message,
                                     to=[from_email],
                                     bcc=recipients,
                                     from_email=from_email)
        msg.attach_alternative(html_message, "text/html")
        msg.send()

65
66
        services.write_to_file(newsletter.pk, language[0], html_message)

67
        translation.deactivate()