|
0
|
1 |
""" |
|
|
2 |
Simple extension of django's EmailMessage to store emails in db |
|
|
3 |
""" |
|
|
4 |
from cm.cm_settings import CM_EMAIL_SUBJECT_PREFIX |
|
|
5 |
from cm.models import Email |
|
|
6 |
from cm.utils.i18n import translate_to |
|
|
7 |
from django.conf import settings |
|
|
8 |
from django.contrib.auth.models import User |
|
|
9 |
from django.core.mail import EmailMessage as BaseEmailMessage |
|
|
10 |
from django.template.loader import render_to_string |
|
|
11 |
LIST_SEP = ' ' |
|
|
12 |
|
|
|
13 |
class EmailMessage(BaseEmailMessage): |
|
|
14 |
|
|
|
15 |
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, |
|
|
16 |
connection=None, attachments=None, headers=None): |
|
|
17 |
if CM_EMAIL_SUBJECT_PREFIX: |
|
|
18 |
subject = CM_EMAIL_SUBJECT_PREFIX + subject |
|
|
19 |
BaseEmailMessage.__init__(self, subject, body, from_email, to, bcc, connection, attachments, headers) |
|
|
20 |
|
|
|
21 |
def send(self, fail_silently=False): |
|
|
22 |
# store in db |
|
|
23 |
Email.objects.create( |
|
|
24 |
from_email = self.from_email, |
|
|
25 |
to = LIST_SEP.join(self.to), |
|
|
26 |
bcc = LIST_SEP.join(self.bcc), |
|
|
27 |
body = self.body, |
|
|
28 |
subject = self.subject, |
|
|
29 |
message = self.message().as_string() |
|
|
30 |
) |
|
|
31 |
# then send for real |
|
|
32 |
BaseEmailMessage.send(self,fail_silently) |
|
|
33 |
|
|
|
34 |
def send_mail(subject, message, from_email, recipient_list, |
|
|
35 |
fail_silently=False, auth_user=None, auth_password=None): |
|
|
36 |
""" |
|
|
37 |
Easy wrapper for django replacing of send_mail in django.core.mail |
|
|
38 |
""" |
|
|
39 |
# Email subject *must not* contain newlines |
|
|
40 |
subject = ''.join(subject.splitlines()) |
|
|
41 |
|
|
|
42 |
msg = EmailMessage(subject=subject, body=message, from_email=from_email, to = recipient_list) |
|
|
43 |
msg.send(fail_silently) |
|
|
44 |
|
|
|
45 |
def send_mail_in_language(subject, subject_vars, message_template, message_vars, from_email, recipient_list): |
|
|
46 |
""" |
|
|
47 |
If obj in recipient_list is user: used preferred_language in profile to send the email |
|
|
48 |
""" |
|
|
49 |
for user_recipient in recipient_list: |
|
|
50 |
if type(user_recipient) == User: |
|
|
51 |
lang_code = User.get_profile().preferred_language |
|
|
52 |
recipient = User.email |
|
|
53 |
else: |
|
|
54 |
lang_code = settings.LANGUAGE_CODE |
|
|
55 |
recipient = user_recipient |
|
|
56 |
|
|
|
57 |
processed_subject = translate_to(subject, lang_code) %subject_vars |
|
76
|
58 |
processed_message = translate_to(message_template, lang_code) %message_vars |
|
0
|
59 |
|
|
|
60 |
send_mail(processed_subject, processed_message, from_email, recipient) |
|
|
61 |
|
|
|
62 |
|