1 from django.conf import settings
2 from django.core.mail import send_mail
3 from django.db import models
4 from django.template import Template, Context
5 from django.utils.translation import ugettext_lazy as _
6 from sentry_sdk import capture_exception
7 from .states import states
10 class EmailTemplate(models.Model):
11 state = models.CharField(_('state'), max_length=128, choices=[(s.slug, s.name) for s in states], help_text='?')
12 subject = models.CharField(_('subject'), max_length=1024)
13 body = models.TextField(_('body'))
14 days = models.SmallIntegerField(_('days'), null=True, blank=True)
15 hour = models.IntegerField(_('hour'), null=True, blank=True)
16 is_active = models.BooleanField(_('active'), default=False)
19 verbose_name = _('email template')
20 verbose_name_plural = _('email templates')
23 return '%s (%+d)' % (self.get_state_display(), self.days)
26 def run(self, time=None, verbose=False, dry_run=False):
27 state = self.get_state()
28 recipients = state(time=time, offset=self.days).get_recipients()
29 hash_values = set(recipient.hash_value for recipient in recipients)
30 sent = set(EmailSent.objects.filter(
31 template=self, hash_value__in=hash_values
32 ).values_list('hash_value', flat=True))
33 for recipient in recipients:
34 if recipient.hash_value in sent:
36 self.send(recipient, verbose=verbose, dry_run=dry_run)
40 if s.slug == self.state:
42 raise ValueError('Unknown state', s.state)
44 def send(self, recipient, verbose=False, dry_run=False):
45 subject = Template(self.subject).render(Context(recipient.context))
46 body = Template(self.body).render(Context(recipient.context))
48 print(recipient.email, subject)
51 send_mail(subject, body, settings.CONTACT_EMAIL, [recipient.email], fail_silently=False)
55 self.emailsent_set.create(
56 hash_value=recipient.hash_value,
57 email=recipient.email,
64 class EmailSent(models.Model):
65 template = models.ForeignKey(EmailTemplate, models.CASCADE)
66 hash_value = models.CharField(max_length=1024)
67 timestamp = models.DateTimeField(auto_now_add=True)
68 email = models.CharField(_('e-mail'), max_length=1024)
69 subject = models.CharField(_('subject'), max_length=1024)
70 body = models.TextField(_('body'))
73 verbose_name = _('email sent')
74 verbose_name_plural = _('emails sent')
75 ordering = ('-timestamp',)
78 return '%s %s' % (self.email, self.timestamp)