Debian Codegraph @

djcelery_email/utils.py

raw
1 import copy
2 import base64
3 from email.mime.base import MIMEBase
4
5 from django.conf import settings
6 from django.core.mail import EmailMultiAlternatives, EmailMessage
7
8
9 def chunked(iterator, chunksize):
10 """
11 Yields items from 'iterator' in chunks of size 'chunksize'.
12
13 >>> list(chunked([1, 2, 3, 4, 5], chunksize=2))
14 [(1, 2), (3, 4), (5,)]
15 """
16 chunk = []
17 for idx, item in enumerate(iterator, 1):
18 chunk.append(item)
19 if idx % chunksize == 0:
20 yield chunk
21 chunk = []
22 if chunk:
23 yield chunk
24
25
26 def email_to_dict(message):
27 if isinstance(message, dict):
28 return message
29
30 message_dict = {'subject': message.subject,
31 'body': message.body,
32 'from_email': message.from_email,
33 'to': message.to,
34 'bcc': message.bcc,
35 # ignore connection
36 'attachments': [],
37 'headers': message.extra_headers,
38 'cc': message.cc,
39 'reply_to': message.reply_to}
40
41 if hasattr(message, 'alternatives'):
42 message_dict['alternatives'] = message.alternatives
43 if message.content_subtype != EmailMessage.content_subtype:
44 message_dict["content_subtype"] = message.content_subtype
45 if message.mixed_subtype != EmailMessage.mixed_subtype:
46 message_dict["mixed_subtype"] = message.mixed_subtype
47
48 attachments = message.attachments
49 for attachment in attachments:
50 if isinstance(attachment, MIMEBase):
51 filename = attachment.get_filename('')
52 binary_contents = attachment.get_payload(decode=True)
53 mimetype = attachment.get_content_type()
54 else:
55 filename, binary_contents, mimetype = attachment
56 # For a mimetype starting with text/, content is expected to be a string.
57 if isinstance(binary_contents, str):
58 binary_contents = binary_contents.encode()
59 contents = base64.b64encode(binary_contents).decode('ascii')
60 message_dict['attachments'].append((filename, contents, mimetype))
61
62 if settings.CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES:
63 for attr in settings.CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES:
64 if hasattr(message, attr):
65 message_dict[attr] = getattr(message, attr)
66
67 return message_dict
68
69
70 def dict_to_email(messagedict):
71 message_kwargs = copy.deepcopy(messagedict) # prevents missing items on retry
72
73 # remove items from message_kwargs until only valid EmailMessage/EmailMultiAlternatives kwargs are left
74 # and save the removed items to be used as EmailMessage/EmailMultiAlternatives attributes later
75 message_attributes = ['content_subtype', 'mixed_subtype']
76 if settings.CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES:
77 message_attributes.extend(settings.CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES)
78 attributes_to_copy = {}
79 for attr in message_attributes:
80 if attr in message_kwargs:
81 attributes_to_copy[attr] = message_kwargs.pop(attr)
82
83 # remove attachments from message_kwargs then reinsert after base64 decoding
84 attachments = message_kwargs.pop('attachments')
85 message_kwargs['attachments'] = []
86 for attachment in attachments:
87 filename, contents, mimetype = attachment
88 contents = base64.b64decode(contents.encode('ascii'))
89
90 # For a mimetype starting with text/, content is expected to be a string.
91 if mimetype and mimetype.startswith('text/'):
92 contents = contents.decode()
93
94 message_kwargs['attachments'].append((filename, contents, mimetype))
95
96 if 'alternatives' in message_kwargs:
97 message = EmailMultiAlternatives(**message_kwargs)
98 else:
99 message = EmailMessage(**message_kwargs)
100
101 # set attributes on message with items removed from message_kwargs earlier
102 for attr, val in attributes_to_copy.items():
103 setattr(message, attr, val)
104
105 return message