11# coding=utf-8
2- import os
32import logging
4- import six
3+ import os
54from smtplib import SMTPException
65
76from django .conf import settings
@@ -109,13 +108,19 @@ def __compile_template(self):
109108 if not self .compiled_template :
110109 self .compiled_template = Template (self .template )
111110
111+ def get_context (self ):
112+ self .context .update ({
113+ "default_attachments" : self .get_default_attachments (as_links = True )
114+ })
115+ return self .context
116+
112117 def render_message (self ):
113118 self .__compile_template ()
114119 try :
115- message = self .compiled_template .render (self .context ) #
120+ message = self .compiled_template .render (self .get_context () ) #
116121 except AttributeError :
117122 # NOTE: for template from string Context() is still required!
118- message = self .compiled_template .render (Context (self .context ))
123+ message = self .compiled_template .render (Context (self .get_context () ))
119124 self .message = message
120125
121126 def get_message_object (self , send_to , attachment_paths , * args , ** kwargs ):
@@ -153,6 +158,25 @@ def send_email(self, send_to, attachment_paths=None, fail_silently=True, *args,
153158
154159 return self .sent
155160
161+ def get_default_attachments (self , as_links = False ):
162+ """
163+ Prepare default attachments data (files will be include into email as attachments)
164+ """
165+ attachments = []
166+ try :
167+ tmp = self .get_template_object ()
168+ except ObjectDoesNotExist :
169+ return attachments
170+
171+ for attachment in tmp .attachments .filter (send_as_link = as_links ):
172+ if as_links :
173+ attachments .append (attachment .attachment_file .url )
174+ else :
175+ attachments .append (
176+ (os .path .basename (attachment .attachment_file .name ), attachment .attachment_file .read ())
177+ )
178+ return attachments
179+
156180 def send (self , to , attachment_paths = None , * args , ** kwargs ):
157181 """This function does all the operations on eft object, that are necessary to send email.
158182 Usually one would use eft object like this:
@@ -162,9 +186,12 @@ def send(self, to, attachment_paths=None, *args, **kwargs):
162186 eft.send_email(['[email protected] ']) 163187 return eft.sent
164188 """
189+ attachments = self .get_default_attachments (as_links = False )
190+ attachments .extend (kwargs .get ('attachments' , []))
191+
165192 self .get_object ()
166193 self .render_message ()
167- self .send_email (to , attachment_paths , * args , ** kwargs )
194+ self .send_email (to , attachment_paths , attachments = attachments , * args , ** kwargs )
168195 if self .sent :
169196 logger .info (u"Mail has been sent to: %s " , to )
170197 return self .sent
0 commit comments