def _send(self): if not self.sent: if getattr(settings, 'USE_TZ', False): # This change breaks SQLite usage. from django.utils.timezone import utc self.last_attempt = datetime.datetime.utcnow().replace(tzinfo=utc) else: self.last_attempt = datetime.datetime.now() subject, from_email, to = self.subject, self.from_address, self.to_address text_content = self.content msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) if self.html_content: html_content = self.html_content msg.attach_alternative(html_content, "text/html") if self.bcc_address: if ',' in self.bcc_address: msg.bcc = [ email.strip() for email in self.bcc_address.split(',') ] else: msg.bcc = [self.bcc_address, ] # Add any additional attachments for attachment in self.attachment_set.all(): msg.attach_file(os.path.join(settings.MEDIA_ROOT, attachment.file_attachment.name)) try: msg.send() self.sent = True except Exception as e: self.do_not_send = True logger.error('Mail Queue Exception: {0}'.format(e)) self.save()
def send_email(to, subject, email_template, cc=None, images=None, context=None, attachments=None, use_bcc=False): to = list(to) if not to: return connection = get_connection() html_content = render_to_string(email_template, context) text_content = strip_tags(html_content) email = EmailMultiAlternatives(subject, text_content, settings.EMAIL_FROM, to, cc, connection) if use_bcc: email.to = [] email.bcc = to email.attach_alternative(html_content, "text/html") if images: email.mixed_subtype = 'related' for i in images: #email.headers() image_name = i.split("/")[-1] fp = open(settings.BASE_DIR + i, 'rb') msg_img = MIMEImage(fp.read()) msg_img.add_header('Content-Id', '<' + image_name + '>') email.attach(msg_img) fp.close() if attachments: for a in attachments: if isinstance(a, dict): email.attach(filename=a['filename'], content=a['file']) elif isinstance(a.attachment, FieldFile): email.attach_file(a.attachment.path) if settings.DEBUG: if settings.EMAIL_ADMIN: email.to = [settings.EMAIL_ADMIN] email.bcc = [settings.EMAIL_ADMIN] email.send() else: print(email.body) else: email.send()
def _send(self): if not self.sent: self.last_attempt = timezone.now() subject, from_email = self.subject, '{0} <{1}>'.format(self.from_name, self.from_address) text_content = self.content msg = EmailMultiAlternatives(subject, text_content, from_email) if self.reply_to: msg.extra_headers.update({"reply-to": self.reply_to}) if self.html_content: html_content = self.html_content msg.attach_alternative(html_content, "text/html") msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()] msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()] # Add any additional attachments for attachment in self.attachment_set.all(): msg.attach_file(os.path.join(settings.MEDIA_ROOT, attachment.file_attachment.name)) try: msg.send() self.sent = True except Exception as e: self.do_not_send = True logger.error('Mail Queue Exception: {0}'.format(e)) self.save()
def _send(self): if not self.sent: self.last_attempt = timezone.now() subject, from_email = self.subject, self.from_address text_content = self.content msg = EmailMultiAlternatives(subject, text_content, from_email) if self.reply_to: msg.extra_headers.update({"reply-to": self.reply_to}) if self.html_content: html_content = self.html_content msg.attach_alternative(html_content, "text/html") msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()] msg.cc = [email.strip() for email in self.cc_address.split(',') if email.strip()] msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()] # Add any additional attachments for attachment in self.attachment_set.all(): path = attachment.file_attachment.path if os.path.isfile(path): with open(path, 'rb') as f: content = f.read() msg.attach(attachment.original_filename, content, None) try: msg.send() self.sent = True except Exception as e: self.do_not_send = True logger.error('Mail Queue Exception: {0}'.format(e)) self.save()
def send_mail(self, sender, recipients, context=None, cc=None, bcc=None, sender_name="", attachments=None): """ This method sends the mail with the given parameters, replacing any variable fields with those in the context """ if isinstance(recipients, basestring): recipients = [recipients]#To avoid exceptions in case there is a single recipient if cc is None: cc = [] if bcc is None: bcc = [] if attachments is None: attachments = {} plainBody = Template(self.email_object.plainBody).render(Context(context)) htmlBody = Template(self.email_object.htmlBody).render(Context(context)) email = EmailMultiAlternatives() email.subject = Template(self.email_object.subject).render(Context(context)) email.body = plainBody email.attach_alternative(htmlBody, 'text/html') email.from_email="%s <%s>" %(sender_name, sender) email.to = recipients email.cc = cc email.bcc = bcc for attachment in self.email_object.attachments.all(): email.attach("%s.%s" % (attachment.name, attachment.fileAttachment.file.name.split(".")[-1]), attachment.fileAttachment.file.read()) for attachment in attachments: email.attach(attachment['filename'].encode('ascii', 'ignore'), attachment['data']) return email.send()
def _send(self): if not self.sent: self.last_attempt = timezone.now() subject, from_email = self.subject, self.from_address text_content = self.content msg = EmailMultiAlternatives(subject, text_content, from_email) if self.html_content: html_content = self.html_content msg.attach_alternative(html_content, "text/html") msg.to = [ email.strip() for email in self.to_address.split(',') if email.strip() ] msg.bcc = [ email.strip() for email in self.bcc_address.split(',') if email.strip() ] # Add any additional attachments for attachment in self.attachment_set.all(): msg.attach_file( os.path.join(settings.MEDIA_ROOT, attachment.file_attachment.name)) try: msg.send() self.sent = True except Exception as e: self.do_not_send = True logger.error('Mail Queue Exception: {0}'.format(e)) self.save()
def _send(self): if not self.sent: self.last_attempt = timezone.now() subject, from_email = self.subject, self.from_address text_content = self.content msg = EmailMultiAlternatives(subject, text_content, from_email) if self.reply_to: msg.reply_to = [email.strip() for email in self.reply_to.split(',') if email.strip()] if self.html_content: html_content = self.html_content msg.attach_alternative(html_content, "text/html") msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()] msg.cc = [email.strip() for email in self.cc_address.split(',') if email.strip()] msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()] # Add any additional attachments for attachment in self.attachment_set.all(): path = attachment.file_attachment.path if os.path.isfile(path): with open(path, 'rb') as f: content = f.read() msg.attach(attachment.original_filename, content, None) try: msg.send() self.sent = True except Exception as e: self.do_not_send = True logger.error('Mail Queue Exception: {0}'.format(e)) self.save()
def sendMail(self, mailFrom='*****@*****.**', mailTo=None, mailCC=None, mailBCC=None, replyTo=None, subject=None, bodyHTML=None, bodyText=None): surpress = (EmailSuppression.objects.filter(suppression_date=date.today()).count() > 0) if surpress: log.warn("Surpressing e-mail") return if bodyText and bodyHTML: message = EmailMultiAlternatives() message.body = bodyText message.attach_alternative(transform(bodyHTML), "text/html") elif bodyText: message = EmailMessage() message.body = bodyText elif bodyHTML: message = EmailMessage() message.body = transform(bodyHTML) message.content_subtype = "html" else: raise TypeError("bodyHTML or bodyText must be set") if not (mailTo or mailCC or mailBCC): raise TypeError("Message must have at least one recipient") if subject: message.subject = subject overrideEmail = None #Try to get override email from settings try: overrideEmail = [settings.ENRICHMENT_OVERRIDE_EMAIL] except AttributeError: pass #Take presidence on the parameter if self.overrideEmail: overrideEmail = self.overrideEmail if not overrideEmail: if mailTo: message.to = list(mailTo) if mailCC: message.cc = list(mailCC) if mailBCC: message.bcc = list(mailBCC) else: message.to = overrideEmail if replyTo: message.reply_to = list(replyTo) message.from_email = mailFrom message.send()
def send_60_day_user_conversion_email(self, user): # sent 60 days after signup email = EmailMultiAlternatives() email.subject = "Support Rhizome by Becoming a Member!" email.to = [user.email] email.bcc = [settings.MEMBERSHIP_GROUP_EMAIL] email.from_email = settings.MEMBERSHIP_GROUP_EMAIL content = { "user": user, "email_body": AutoGeneratedEmail.objects.get( email_title='60_day_conversion').email_body } plaintext_template = get_template( 'accounts/emails/conversion_email_60day.txt') plaintext_message = plaintext_template.render(Context(content)) html_template = get_template( 'accounts/emails/conversion_email_60day.html') html_message = html_template.render(Context(content)) #send plaintext and html version email.attach_alternative(html_message, "text/html") email.send(fail_silently=False)
def send_15day_till_expired_email(self, membership): email = EmailMultiAlternatives() email.subject = "Only 15 days until your Rhizome Membership expires!" email.to = [membership.user.email] email.bcc = [settings.MEMBERSHIP_GROUP_EMAIL] email.from_email = settings.MEMBERSHIP_GROUP_EMAIL content = { "user": membership.user, "email_body": AutoGeneratedEmail.objects.get( email_title='15_day_renewal').email_body } plaintext_template = get_template( 'accounts/emails/renewal_email_15day.txt') plaintext_message = plaintext_template.render(Context(content)) html_template = get_template( 'accounts/emails/renewal_email_15day.html') html_message = html_template.render(Context(content)) #send plaintext and html version email.attach_alternative(html_message, "text/html") email.send(fail_silently=False)
def send_14d_comeback_email(self, membership): email = EmailMultiAlternatives() email.subject = "We want you back!" email.to = [membership.user.email] email.bcc = [settings.MEMBERSHIP_GROUP_EMAIL] email.from_email = settings.MEMBERSHIP_GROUP_EMAIL content = { "user": membership.user, "email_body": AutoGeneratedEmail.objects.get( email_title='comeback_email').email_body } plaintext_template = get_template( 'accounts/emails/renewal_email_comeback.txt') plaintext_message = plaintext_template.render(Context(content)) html_template = get_template( 'accounts/emails/renewal_email_comeback.html') html_message = html_template.render(Context(content)) #send plaintext and html version email.attach_alternative(html_message, "text/html") email.send(fail_silently=False)
def SendEmail(template_name, content, email_to, email_from, subject, email_bcc): ''' Send Email - will always send text message - if html version exists, it will send that also ''' try: # handle template_name as template or path try: plaintext = get_template('%s.txt' % template_name) text_content = plaintext.render(content) except TemplateDoesNotExist as e: # @UnusedVariable try: with open(template_name, 'r') as fsock: plaintext = Template(fsock.read()) text_content = plaintext.render(content) except IOError, args: logger.debug( 'Unable to open template_name as path or template: %s, %s' % (Exception, args)) logger.debug('Exception: %s' % sys.exc_info()[0]) except Exception: raise # create msg object and send email msg = EmailMultiAlternatives( subject, \ text_content, \ email_from, \ [ email_to ]) if email_bcc: msg.bcc = email_bcc try: # handle template_name as template or path try: html = get_template('%s.html' % template_name) html_content = html.render(content) except TemplateDoesNotExist as e: # @UnusedVariable try: with open(template_name, 'r') as fsock: html = Template(fsock.read()) html_content = html.render(content) except IOError, args: logger.debug( 'Unable to open template_name as path or template: %s, %s' % (Exception, args)) logger.debug('Exception: %s' % sys.exc_info()[0]) except Exception: raise msg.attach_alternative(html_content, "text/html")
def _setup_email(self): msg = EmailMultiAlternatives(self.get_rendered_subject(), self.get_plain_text_body(), self.from_address, self._normalize_to_iterable(self.to)) if self.cc: msg.cc = self._normalize_to_iterable(self.cc) full_bcc = self._get_bcc_with_debugging_copy() if full_bcc: msg.bcc = self._normalize_to_iterable(full_bcc) msg.attach_alternative(self.get_rendered_html_body(), "text/html") return msg
def _convert_to_django_msg(msg): body, alternatives = _get_content(msg) if alternatives: email = EmailMultiAlternatives(body=body, alternatives=alternatives) else: email = EmailMessage(body=body) email.subject = _parse_header(msg['Subject']) email.to = _parse_header(msg['To']) email.cc = _parse_header(msg.get('Cc', None)) email.bcc = _parse_header(msg.get('Bcc', None)) email.from_email = _parse_header(msg['From']) return email
def handle_signoff_emails(instance, created, **kwargs): if not created: return message = EmailMultiAlternatives() # Collect recipients based on site settings if hasattr(settings, 'SIGNOFF_EMAIL_USER') and\ settings.SIGNOFF_EMAIL_USER: message.to = [ instance.user.email, ] if hasattr(settings, 'SIGNOFF_EMAIL_RECEIPT') and\ settings.SIGNOFF_EMAIL_RECEIPT: if message.to: message.bcc = settings.SIGNOFF_EMAIL_RECEIPT else: message.to = settings.SIGNOFF_EMAIL_RECEIPT # If neither key is true, then we have no recipients, and therefore no mail # to send if not message.to: return if hasattr(settings, 'SIGNOFF_EMAIL_FROM') and\ settings.SIGNOFF_EMAIL_FROM: message.from_email = settings.SIGNOFF_EMAIL_FROM if hasattr(settings, 'SIGNOFF_EMAIL_REPLY_TO') and\ settings.SIGNOFF_EMAIL_REPLY_TO: message.reply_to = (settings.SIGNOFF_EMAIL_REPLY_TO, ) # Build message template_context = { 'document': instance.document, 'user': instance.user, 'instance': instance, } message.subject = render_to_string( 'signoff/email_subject.txt', context=template_context, ).strip() html_body = render_to_string( 'signoff/email_body.html', context=template_context, ).strip() message.body = html_body message.attach_alternative(html_body, 'text/html') message.send()
def _convert_to_django_msg(msg): body, alternatives = _get_content(msg) if alternatives: email = EmailMultiAlternatives(body=body, alternatives=alternatives) else: email = EmailMessage(body=body) email.subject = _parse_header(msg["Subject"]) email.to = _parse_header(msg["To"]) email.cc = _parse_header(msg.get("Cc", None)) email.bcc = _parse_header(msg.get("Bcc", None)) email.from_email = _parse_header(msg["From"]) return email
def send(self): if not self.sent: if getattr(settings, 'USE_TZ', False): # This change breaks SQLite usage. from django.utils.timezone import utc self.last_attempt = datetime.datetime.utcnow().replace( tzinfo=utc) else: self.last_attempt = datetime.datetime.now() subject, from_email, to = self.subject, self.from_address, self.to_address text_content = self.content msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) if self.html_content: html_content = self.html_content msg.attach_alternative(html_content, "text/html") if self.bcc_address: if ',' in self.bcc_address: msg.bcc = [ email.strip() for email in self.bcc_address.split(',') ] else: msg.bcc = [ self.bcc_address, ] # Add any additional attachments for attachment in self.attachment_set.all(): msg.attach_file( os.path.join(settings.MEDIA_ROOT, attachment.file_attachment.name)) try: msg.send() self.sent = True except Exception, e: self.do_not_send = True logger.error('Mail Queue Exception: {0}'.format(e)) self.save()
def send_email_html(self, template, context): html_content = render_to_string(template, context) text_content = strip_tags(html_content).strip() email = EmailMultiAlternatives() if self.email_subject: email.subject = self.email_subject if self.email_to: email.to = [x.strip() for x in self.email_to.split(',')] if self.email_cc: email.cc = [x.strip() for x in self.email_cc.split(',')] if self.email_bcc: email.bcc = [x.strip() for x in self.email_bcc.split(',')] if self.email_reply_to: email.reply_to = [ x.strip() for x in self.email_reply_to.split(',') ] # if self.email_msg: # email.body = msg email.body = html_content email.attach_alternative(text_content, 'text/plain') email.content_subtype = "html" email.mixed_subtype = 'related' fp = open('static/image/logo.png', 'rb') msg_img1 = MIMEImage(fp.read()) fp.close() msg_img1.add_header('Content-ID', '<{}>'.format("logo.png")) email.attach(msg_img1) fp = open(context['order'].door_image.image.url.replace('/', '', 1), 'rb') msg_img2 = MIMEImage(fp.read()) fp.close() msg_img2.add_header('Content-ID', '<{}>'.format("door.png")) email.attach(msg_img2) fp = open(context['order'].frame_image.image.url.replace('/', '', 1), 'rb') msg_img3 = MIMEImage(fp.read()) fp.close() msg_img3.add_header('Content-ID', '<{}>'.format("frame.png")) email.attach(msg_img3) fp = open(context['order'].handle.image.url.replace('/', '', 1), 'rb') msg_img4 = MIMEImage(fp.read()) fp.close() msg_img4.add_header('Content-ID', '<{}>'.format("handle.png")) email.attach(msg_img4) return email.send(fail_silently=True)
def _convert_to_django_msg(msg): from django.core.mail import EmailMessage, EmailMultiAlternatives body, alternatives = _get_content(msg) if alternatives: email = EmailMultiAlternatives(body=body, alternatives=alternatives) else: email = EmailMessage(body=body) email.subject = _parse_header(msg['Subject']) email.to = _parse_header(msg['To']) email.cc = _parse_header(msg.get('Cc', None)) email.bcc = _parse_header(msg.get('Bcc', None)) email.from_email = _parse_header(msg['From']) return email
def message(self): m = EmailMultiAlternatives(self.subject, self.body) m.to = self.to m.cc = self.cc m.bcc = self.bcc m.from_email = self.from_email m.alternatives = \ [(att.content, att.mimetype) for att in self.alternatives()] for attachment in self.attachments(): m.attach(attachment.filename, attachment.content.read(), attachment.mimetype) m.extra_headers = self.extra_headers return m
def send(self): if not self.sent: self.last_attempt = datetime.datetime.now() try: subject, from_email, to = self.subject, self.from_address, self.to_address text_content = self.content msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) if self.html_content: html_content = self.html_content msg.attach_alternative(html_content, "text/html") if self.bcc_address: msg.bcc = [self.bcc_address] msg.send() self.sent = True except Exception, e: print("mail queue exception %s" % e) self.save()
def _send(self): if not self.sent: self.last_attempt = timezone.now() subject, from_email = self.subject, self.from_address text_content = self.content msg = EmailMultiAlternatives(subject, text_content, from_email) if getattr(settings, "EMAIL_TEST_MODE", None): msg.to = settings.MAIL_ADMINS else: msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()] msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()] # Add any additional attachments for attachment in self.attachment_set.all(): filename = os.path.join(settings.MEDIA_ROOT, attachment.file_attachment.name) if attachment.inline_content_id: try: with open(filename, 'rb') as fo: to_attach = MIMEImage(fo.read()) except TypeError: # invalid image, skip continue to_attach.add_header('Content-ID', '<%s>' % attachment.inline_content_id) msg.attach(to_attach) msg.mixed_subtype = 'related' elif attachment.name: with open(filename, 'rb') as fo: msg.attach(attachment.name, fo.read()) else: msg.attach_file(filename) if self.html_content: html_content = self.html_content msg.attach_alternative(html_content, "text/html") try: msg.send() self.sent = True except Exception as e: self.do_not_send = True logger.error('Mail Queue Exception: {0}'.format(e)) self.save()
def send_email(self, documents): rendered = self.render_message(documents) msg = EmailMultiAlternatives( self.get_subject_line(documents), rendered['text'], '*****@*****.**', [self.user.email] ) if not self.topic.politician_hansard_alert: msg.bcc = ['*****@*****.**'] if rendered.get('html'): msg.attach_alternative(rendered['html'], 'text/html') if getattr(settings, 'PARLIAMENT_SEND_EMAIL', False): msg.send() self.last_sent = datetime.datetime.now() self.save() else: logger.warning("settings.PARLIAMENT_SEND_EMAIL must be True to send mail") print msg.subject print msg.body
def send_30day_till_expired_email(self, membership): email = EmailMultiAlternatives() email.subject = "30 days until your Rhizome Membership expires!" email.to = [membership.user.email] email.bcc = [settings.MEMBERSHIP_GROUP_EMAIL] email.from_email = settings.MEMBERSHIP_GROUP_EMAIL content = { "user": membership.user, "email_body": AutoGeneratedEmail.objects.get(email_title = '30_day_renewal').email_body } plaintext_template = get_template('accounts/emails/renewal_email_30day.txt') plaintext_message = plaintext_template.render(Context(content)) html_template = get_template('accounts/emails/renewal_email_30day.html') html_message = html_template.render(Context(content)) #send plaintext and html version email.attach_alternative(html_message, "text/html") email.send(fail_silently=False)
def send_mail(self, sender, recipients, context=None, cc=None, bcc=None, sender_name="", attachments=None): """ This method sends the mail with the given parameters, replacing any variable fields with those in the context """ if cc is None: cc = [] if bcc is None: bcc = [] if attachments is None: attachments = {} plainBody = Template(self.email_object.plainBody).render( Context(context)) htmlBody = Template(self.email_object.htmlBody).render( Context(context)) email = EmailMultiAlternatives() email.subject = Template(self.email_object.subject).render( Context(context)) email.body = plainBody email.attach_alternative(htmlBody, 'text/html') email.from_email = "%s <%s>" % (sender_name, sender) email.to = recipients email.cc = cc email.bcc = bcc for attachment in self.email_object.attachments.all(): email.attach( "%s.%s" % (attachment.name, attachment.fileAttachment.file.name.split(".")[-1]), attachment.fileAttachment.file.read()) for attachment in attachments: email.attach(attachment['filename'].encode('ascii', 'ignore'), attachment['data']) email.tags = map(unicode.strip, self.email_object.tags.split(',')) email.track_clicks = True return email.send()
def send_email(self, documents): rendered = self.render_message(documents) msg = EmailMultiAlternatives( self.get_subject_line(documents), rendered["text"], "*****@*****.**", [self.user.email], headers={"List-Unsubscribe": "<" + self.get_unsubscribe_url(full=True) + ">"}, ) if not self.topic.politician_hansard_alert: msg.bcc = ["*****@*****.**"] if rendered.get("html"): msg.attach_alternative(rendered["html"], "text/html") if getattr(settings, "PARLIAMENT_SEND_EMAIL", False): msg.send() self.last_sent = datetime.datetime.now() self.save() else: logger.warning("settings.PARLIAMENT_SEND_EMAIL must be True to send mail") print msg.subject print msg.body
def send_email(self, documents): rendered = self.render_message(documents) msg = EmailMultiAlternatives( self.get_subject_line(documents), rendered['text'], '*****@*****.**', [self.user.email], headers={'List-Unsubscribe': '<' + self.get_unsubscribe_url(full=True) + '>'} ) if getattr(settings, 'PARLIAMENT_ALERTS_BCC', ''): msg.bcc = [settings.PARLIAMENT_ALERTS_BCC] if rendered.get('html'): msg.attach_alternative(rendered['html'], 'text/html') if getattr(settings, 'PARLIAMENT_SEND_EMAIL', False): msg.send() self.last_sent = datetime.datetime.now() self.save() else: logger.warning("settings.PARLIAMENT_SEND_EMAIL must be True to send mail") print msg.subject print msg.body
def default_delivery_handler(sender, **kwargs): message = kwargs.get('message', None) if message and 'email' in message.message_format: msg = EmailMultiAlternatives() msg.subject = message.subject msg.body = message.body if message.sender(): msg.from_email = message.sender().contact_info msg.to = [r.contact_info for r in message.recipients() if r.role == 'to'] # FIXME: Django doesn't yet support the CC field, so just add CC'ed # recipients in the To: field for now. msg.to += [r.contact_info for r in message.recipients() if r.role == 'cc'] msg.bcc = [r.contact_info for r in message.recipients() if r.role == 'bcc'] for attachment in getattr(message, 'attachments', []): if isinstance(attachment, (list, tuple)): if len(attachment) >= 1 and attachment[0] is None: msg.attach_alternative(*attachment[1:]) else: msg.attach(*attachment) else: msg.attach(attachment) return msg.send()
def send_60_day_user_conversion_email(self, user): # sent 60 days after signup email = EmailMultiAlternatives() email.subject = "Support Rhizome by Becoming a Member!" email.to = [user.email] email.bcc = [settings.MEMBERSHIP_GROUP_EMAIL] email.from_email = settings.MEMBERSHIP_GROUP_EMAIL content = { "user": user, "email_body": AutoGeneratedEmail.objects.get(email_title = '60_day_conversion').email_body } plaintext_template = get_template('accounts/emails/conversion_email_60day.txt') plaintext_message = plaintext_template.render(Context(content)) html_template = get_template('accounts/emails/conversion_email_60day.html') html_message = html_template.render(Context(content)) #send plaintext and html version email.attach_alternative(html_message, "text/html") email.send(fail_silently=False)
def send_email(self, documents): rendered = self.render_message(documents) msg = EmailMultiAlternatives( self.get_subject_line(documents), rendered['text'], '*****@*****.**', [self.user.email], headers={ 'List-Unsubscribe': '<' + self.get_unsubscribe_url(full=True) + '>' }) if getattr(settings, 'PARLIAMENT_ALERTS_BCC', ''): msg.bcc = [settings.PARLIAMENT_ALERTS_BCC] if rendered.get('html'): msg.attach_alternative(rendered['html'], 'text/html') if getattr(settings, 'PARLIAMENT_SEND_EMAIL', False): msg.send() self.last_sent = datetime.datetime.now() self.save() else: logger.warning( "settings.PARLIAMENT_SEND_EMAIL must be True to send mail") print(msg.subject) print(msg.body)
def email_order(permanence_id, all_producers=True, closed_deliveries_id=None, producers_id=None): from repanier.apps import REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_BOARD, \ REPANIER_SETTINGS_GROUP_NAME, REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_PRODUCER, \ REPANIER_SETTINGS_SEND_ABSTRACT_ORDER_MAIL_TO_PRODUCER, \ REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_CUSTOMER cur_language = translation.get_language() for language in settings.PARLER_LANGUAGES[settings.SITE_ID]: language_code = language["code"] translation.activate(language_code) permanence = Permanence.objects.get(id=permanence_id) config = Configuration.objects.get(id=DECIMAL_ONE) filename = "{0}-{1}.xlsx".format( slugify(_("Order")), slugify(permanence) ) group_filename = "{0}-{1}.xlsx".format( slugify(REPANIER_SETTINGS_GROUP_NAME), slugify(filename) ) sender_email, sender_function, signature, cc_email_staff = get_signature(is_reply_to_order_email=True) board_composition, board_composition_and_description = get_board_composition(permanence.id) # Orders send to the preparation team group_wb = xlsx_order.export_abstract(permanence=permanence, deliveries_id=closed_deliveries_id, wb=None) if group_wb is not None: abstract_ws = group_wb.get_active_sheet() else: abstract_ws = None if all_producers: if group_wb is not None: # At least one order group_wb = xlsx_order.export_customer_label( permanence=permanence, deliveries_id=closed_deliveries_id, wb=group_wb ) group_wb = xlsx_order.export_preparation( permanence=permanence, deliveries_id=closed_deliveries_id, wb=group_wb ) group_wb = xlsx_stock.export_permanence_stock( permanence=permanence, customer_price=True, wb=group_wb ) group_wb = xlsx_order.export_customer( permanence=permanence, deliveries_id=closed_deliveries_id, deposit=True, wb=group_wb ) group_wb = xlsx_order.export_customer( permanence=permanence, deliveries_id=closed_deliveries_id, wb=group_wb ) to_email_board = [] for permanence_board in PermanenceBoard.objects.filter( permanence=permanence.id).order_by('?'): if permanence_board.customer: to_email_board.append(permanence_board.customer.user.email) try: order_staff_mail = config.order_staff_mail except TranslationDoesNotExist: order_staff_mail = EMPTY_STRING # order_staff_mail_subject = "%s - %s - %s" % ( # _('Permanence preparation list'), permanence, REPANIER_SETTINGS_GROUP_NAME) order_staff_mail_subject = "%s - %s" % (REPANIER_SETTINGS_GROUP_NAME, permanence) template = Template(order_staff_mail) context = TemplateContext({ 'permanence_link' : mark_safe('<a href="http://%s%s">%s</a>' % ( settings.ALLOWED_HOSTS[0], reverse('order_view', args=(permanence.id,)), permanence)), 'board_composition' : mark_safe(board_composition), 'board_composition_and_description': mark_safe(board_composition_and_description), 'signature' : mark_safe( '%s<br/>%s<br/>%s' % (signature, sender_function, REPANIER_SETTINGS_GROUP_NAME)) }) html_content = template.render(context) email = EmailMultiAlternatives( order_staff_mail_subject, strip_tags(html_content), from_email=sender_email, to=to_email_board, cc=cc_email_staff ) if group_wb is not None: email.attach(group_filename, save_virtual_workbook(group_wb), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') email.attach_alternative(html_content, "text/html") if not REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_BOARD: email.to = cc_email_staff email.cc = [] email.bcc = [] send_email(email=email) # Orders send to our producers if REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_PRODUCER: producer_set = Producer.objects.filter( permanence=permanence.id, language=language_code, ).order_by('?') if producers_id is not None: # Do not send order twice # all_producers is True if we are sending the order to the last group of selected producers producer_set = producer_set.filter(id__in=producers_id) for producer in producer_set: long_profile_name = producer.long_profile_name if producer.long_profile_name is not None else producer.short_profile_name wb = xlsx_order.export_producer_by_product(permanence=permanence, producer=producer, wb=None) if wb is None: order_empty = True duplicate = False else: order_empty = False if not producer.manage_replenishment: duplicate = True wb = xlsx_order.export_producer_by_customer( permanence=permanence, producer=producer, wb=wb) else: duplicate = False try: order_producer_mail = config.order_producer_mail except TranslationDoesNotExist: order_producer_mail = EMPTY_STRING # order_producer_mail_subject = "%s - %s - %s" % ( # _('Permanence preparation list'), permanence, REPANIER_SETTINGS_GROUP_NAME) order_producer_mail_subject = "%s - %s" % (REPANIER_SETTINGS_GROUP_NAME, permanence) template = Template(order_producer_mail) context = TemplateContext({ 'name' : long_profile_name, 'long_profile_name': long_profile_name, 'order_empty' : order_empty, 'duplicate' : duplicate, 'permanence_link' : mark_safe('<a href="http://%s%s">%s</a>' % ( settings.ALLOWED_HOSTS[0], reverse('order_view', args=(permanence.id,)), permanence)), 'signature' : mark_safe( '%s<br/>%s<br/>%s' % (signature, sender_function, REPANIER_SETTINGS_GROUP_NAME)) }) html_content = template.render(context) producer_invoice = models.ProducerInvoice.objects.filter( producer_id=producer.id, permanence_id=permanence.id ).only("total_price_with_tax").order_by('?').first() if producer_invoice is not None \ and producer_invoice.total_price_with_tax < producer.minimum_order_value: to = cc_email_staff html_content = \ order_producer_mail_subject + '<br/><br/>' + html_content cc = [] order_producer_mail_subject = _( '/!\ Mail not send to our producer %s because the minimum order value has not been reached.') % long_profile_name else: to_email_producer = [] if producer.email: to_email_producer.append(producer.email) if producer.email2: to_email_producer.append(producer.email2) if producer.email3: to_email_producer.append(producer.email3) cc = cc_email_staff email = EmailMultiAlternatives( order_producer_mail_subject, strip_tags(html_content), from_email=sender_email, to=to_email_producer, cc=cc ) if REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_PRODUCER and wb is not None: if REPANIER_SETTINGS_SEND_ABSTRACT_ORDER_MAIL_TO_PRODUCER: if abstract_ws is not None: wb.add_sheet(abstract_ws, index=0) email.attach( filename, save_virtual_workbook(wb), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) email.attach_alternative(html_content, "text/html") send_email(email=email) if all_producers: # Orders send to our customers only if they don't have already received it # ==> customerinvoice__is_order_confirm_send=False # customerinvoice__permanence_id=permanence.id if REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_CUSTOMER: all_producers_closed = not (ProducerInvoice.objects.filter( permanence_id=permanence_id, status=PERMANENCE_OPENED ).order_by('?').exists()) if all_producers_closed: if closed_deliveries_id is None: customer_set = Customer.objects.filter( represent_this_buyinggroup=False, customerinvoice__is_order_confirm_send=False, customerinvoice__permanence_id=permanence.id, language=language_code ).order_by('?') else: customer_set = Customer.objects.filter( represent_this_buyinggroup=False, customerinvoice__is_order_confirm_send=False, customerinvoice__permanence_id=permanence.id, customerinvoice__delivery_id__in=closed_deliveries_id, language=language_code ).order_by('?') for customer in customer_set: export_order_2_1_customer( customer, filename, permanence, sender_email, sender_function, signature, abstract_ws) # confirm_customer_invoice(permanence_id, customer.id) customer_invoice = CustomerInvoice.objects.filter( customer_id=customer.id, permanence_id=permanence_id ).order_by('?').first() customer_invoice.confirm_order() customer_invoice.save() translation.activate(cur_language)
def notify_client(self, request, queryset): for app in queryset.all(): recipients = [] if app.user and app.user.email: recipients.append(app.user.email) if app.groups.count() > 0: group_users = User.objects.filter(groups__in=app.groups.all()) for user in group_users: if user.email and user.email not in recipients: recipients.append(user.email) if recipients: recipient_count = len(recipients) if request.user.email and request.user.email not in recipients: recipients.append(request.user.email) try: # Try and send email in client's preferred language # This doesn't make much sense for apps distributed to groups # hence the catch all except clause lang = app.user.userinfo.language translation.activate(lang) except Exception: pass domain = get_current_site(request).domain index_url = reverse('django_mobile_app_distribution_index') data = { 'email_link_color_hex': _settings.EMAIL_LINK_COLOR_HEX, 'app_name': app.name, 'app_version': app.version, 'os': app.operating_system, 'download_url': '/'.join(s.strip('/') for s in (domain, index_url)) } email = EmailMultiAlternatives() email.bcc = recipients email.subject = _('Version %(app_version)s of %(app_name)s for %(os)s is available for download') % data email.body = _( 'Version %(app_version)s of %(app_name)s for %(os)s is available for download.\n' 'Please visit %(download_url)s to install the app.' ) % data email.attach_alternative( render_to_string('django_mobile_app_distribution/email_notification.html', data), 'text/html' ) # Reset to system language translation.deactivate() email.send(fail_silently=False) messages.add_message( request, messages.INFO, ungettext_lazy( '%(recipient_count)s user was notified of %(app_name)s %(app_version)s availability.', '%(recipient_count)s users were notified of %(app_name)s %(app_version)s availability.', recipient_count) % { 'recipient_count' : recipient_count, 'app_name' : app.name, 'app_version': app.version }, fail_silently=True) else: messages.add_message( request, messages.ERROR, _('Nobody was notified by email because nobody\'s email address is set.'), fail_silently=True )
def notify_client(self, request, queryset): for app in queryset.all(): recipients = [] if app.user and app.user.email: recipients.append(app.user.email) if app.groups.count() > 0: group_users = User.objects.filter(groups__in=app.groups.all()) for user in group_users: if user.email and user.email not in recipients: recipients.append(user.email) if recipients: recipient_count = len(recipients) if request.user.email and request.user.email not in recipients: recipients.append(request.user.email) try: # Try and send email in client's preferred language # This doesn't make much sense for apps distributed to groups # hence the catch all except clause lang = app.user.userinfo.language translation.activate(lang) except Exception: pass data = { 'email_link_color_hex': _settings.EMAIL_LINK_COLOR_HEX, 'app_name': app.name, 'app_version': app.version, 'os': app.operating_system, 'download_url': '/'.join( s.strip('/') for s in ( get_current_site(request).domain, reverse('django_mobile_app_distribution_index'))) } email = EmailMultiAlternatives() email.bcc = recipients email.subject = _( 'Version %(app_version)s of %(app_name)s for %(os)s is available for download' ) % data email.body = _( 'Version %(app_version)s of %(app_name)s for %(os)s is available for download.\nPlease visit %(download_url)s to install the app.' ) % data email.attach_alternative( render_to_string( 'django_mobile_app_distribution/email_notification.html', data), 'text/html') # Reset to system language translation.deactivate() email.send(fail_silently=False) messages.add_message( request, messages.INFO, ungettext_lazy( '%(recipient_count)s user was notified of %(app_name)s %(app_version)s availability.', '%(recipient_count)s users were notified of %(app_name)s %(app_version)s availability.', recipient_count) % { 'recipient_count': recipient_count, 'app_name': app.name, 'app_version': app.version }, fail_silently=True) else: messages.add_message( request, messages.ERROR, _('Nobody was notified by email because nobody\'s email address is set.' ), fail_silently=True)
def handle_new_posting(sender, **kwargs): '''Signal handler whenever a job posting is created Refer: http://localhost/docs/django-docs/ref/signals.html#django.db.models.signals.post_save This signal handler does the following: If a jobposting is approved: Emails all the eligible group students the jobposting. ''' if sender == posting: if kwargs['created'] == False: #we want to handle only APPROVED jobpostings jp = kwargs['instance'] print dir(jp) print jp.get_status_display() if jp.get_status_display() != 'approved': #ONLY do the things on APPROVED job postings print "Not approved, returning" return print "Processing, it's approved" try: to_be_emailed = []; #list of email addresses to be emailed print "For jobposting ", jp for g in jp.for_programmes.all(): print 'Got group',g for u in g.user_set.all(): print 'Got user',u.username try: to_be_emailed.append("*****@*****.**" % (u.username)) c = student.objects.get(prn=u.username) if c is student: to_be_emailed.append(student.objects.get(prn=u.username)).email except student.DoesNotExist as s: print "%s hasn't yet filled in details...so couldn't get his personal email address" % u.username continue; except Exception as e: print e continue; poster_id = jp.posted_by poster_full_name = "Unknown User" if jp.non_sicsr_poster: record = User.objects.get(username=poster_id) poster_full_name = record.get_full_name() if record.get_full_name().strip()!= '' else record.username #TODO: to get the provider name properly and fix this #provider = UserSocialAuth.objects.get(uid=poster_id).provider #poster_full_name = "%s from %s" % (poster_full_name, provider) else: u = user.objects.get(username = poster_id) poster_full_name = u.fullname if u.fullname.strip()!= '' else u.username print "Poster's Full name : ", poster_full_name html_content = """ Hi, A new job posting has been put up on LaResume-X by <b>%s</b> for <b>%s</b>. It's detail are as follows : <ul> <li>Organization's Website: %s </li> <li>Description: <p>%s</p> </li> <li>How to Apply ? %s </li> </ul> To register your interest in it go to <a href='http://projects.sdrclabs.in/laresumex/jobposting/views/view'>here</a> <br/> Thanks! <br/> Regards,<br/> Team LaResume-X """ % (poster_full_name, jp.company_name, jp.company_url, jp.description, jp.how_to_apply) text_content = """ Hi, A new job posting has been put up on LaResume-X by %s for %s. To register your interest in it go to http://projects.sdrclabs.in/laresumex/jobposting/views/view It's detail are as follows : Organization's Website: %s Description: %s How to Apply ? %s Thanks! Regards, Team LaResume-X """ % (poster_full_name, jp.company_name, jp.company_url, jp.description, jp.how_to_apply) email = EmailMultiAlternatives('[LaResume-X]New job posting',text_content) email.attach_alternative(html_content, 'text/html') #add the managers for x in MANAGERS: email.bcc.append(x[1]); email.bcc = to_be_emailed; email.subject = "[LaResume-X] New job posting" email.send(fail_silently=False) print "Sent email succesfully to ", to_be_emailed print "Total addresses emailed :", len(to_be_emailed) except SMTPException as e: print 'Exception occured when trying to actually send the email' print e except Exception as e: print 'Exception occurred when constructing email messages' print e mail_managers(subject = "Emailing problem", message = "Couldn't send email about jobposting for %s by %s" % (jp.company_name, poster_full_name), fail_silently = False)
def run(self): msg = EmailMultiAlternatives(self.subject, self.body, self.from_email, bcc=self.recipient_list) if self.html: msg.attach_alternative(self.html, "text/html") msg.content_subtype = 'html' msg.mixed_subtype = 'related' if self.images: for image in self.images: # Create an inline attachment ext = '.' + image.image.url.split('.')[-1] image = MIMEImage(image.image.read(), _subtype=ext) image.add_header('Content-ID', '<{}>'.format(image.image_filename)) msg.attach(image) i = 0 recipients_list_ = self.recipient_list[i:i + NBR_RECIPIENTS_BY_TIME] while len(recipients_list_) > 0: recipients_list_ = self.recipient_list[i:i + NBR_RECIPIENTS_BY_TIME] msg.bcc = recipients_list_ try: msg.send(self.fail_silently) except smtplib.SMTPDataError: print("SMTPDataError.......................") print("recipients_list_:") print(str(recipients_list_)) is_ok = False msg2 = MIMEMultipart('alternative') msg2['Subject'] = self.subject msg2['From'] = self.from_email msg2['bcc'] = ", ".join(recipients_list_) part1 = MIMEText(self.body, 'plain') part2 = MIMEText(self.html, 'html') msg2.attach(part1) msg2.attach(part2) msg2.content_subtype = 'html' msg2.mixed_subtype = 'related' if self.images: for image in self.images: ext = '.' + image.image.url.split('.')[-1] image = MIMEImage(image.image.read(), _subtype=ext) image.add_header('Content-ID', '<{}>'.format(image.image_filename)) msg2.attach(image) for added_email_account in settings.ADDED_EMAILS_ACCOUNTS: print("is_ok: " + str(is_ok)) if is_ok: break try: send_python_email(added_email_account['host_user'], added_email_account['host_password'], msg2, recipients_list_) is_ok = True except Exception as e: # for the repr print("the repr: ") print(repr(e)) # for just the message, or str(e), since print calls str under the hood print("just the message, or str(e): ") print(e) # the arguments that the exception has been called with. # the first one is usually the message. (OSError is different, though) print( "the arguments that the exception has been called with: " ) print(e.args) i += NBR_RECIPIENTS_BY_TIME if self.args_tuple and self.args_tuple[0] is False: SendNewsletterAfterActivating.objects.filter( item_id=self.args_tuple[1]).delete()
def send_messages(data, template, sheet_title, data_index=None, email_to=None, email_column=None, bcc_column=None, email_splitter=',', email_settings=None): heads = data[0] if email_settings: smtp_host = email_settings['smtp_host'] smtp_port = email_settings['smtp_port'] smtp_username = email_settings['smtp_username'] smtp_password = email_settings['smtp_password'] mail_backend = EmailBackend(host=smtp_host, port=smtp_port, password=smtp_password, username=smtp_username, use_tls=True, timeout=10) else: mail_backend = None if data_index != None: data = data[1:][data_index] current_task.update_state(state='PROGRESS', meta={ 'current': 0, 'total': 1 }) html_template = generate_email_template(template, heads, data) if email_settings: pass from_email = email_settings['smtp_from_email'] else: from_email = settings.DEFAULT_FROM_EMAIL if email_to: sended = send_mail(sheet_title, message=strip_tags(html_template), html_message=html_template, recipient_list=(email_to, ), from_email=from_email, connection=mail_backend) current_task.update_state(state='PROGRESS', meta={ 'current': 1, 'total': 1 }) else: data = data[1:] data_size = len(data) current_task.update_state(state='PROGRESS', meta={ 'current': 0, 'total': data_size }) if email_column: email_column_index = heads.index(email_column) else: email_column_index = None if bcc_column: bcc_column_index = heads.index(bcc_column) else: bcc_column_index = None for i, el_data in enumerate(data): sleep(1) email_to = el_data[email_column_index] html_template = generate_email_template(template, heads, el_data) if email_settings: from_email = email_settings['smtp_from_email'] else: from_email = settings.DEFAULT_FROM_EMAIL msg = EmailMultiAlternatives(subject=sheet_title, body=strip_tags(html_template), from_email=from_email) msg.attach_alternative(html_template, 'text/html') if bcc_column_index: msg.bcc = el_data[bcc_column_index].split(email_splitter) if email_column_index: msg.cc = el_data[email_column_index].split(email_splitter) if mail_backend: msg.connection = mail_backend msg.send() current_task.update_state(state='PROGRESS', meta={ 'current': i, 'total': data_size })
def handle_new_posting(sender, **kwargs): '''Signal handler whenever a job posting is created Refer: http://localhost/docs/django-docs/ref/signals.html#django.db.models.signals.post_save This signal handler does the following: If a jobposting is approved: Emails all the eligible group students the jobposting. ''' if sender == posting: if kwargs[ 'created'] == False: #we want to handle only APPROVED jobpostings jp = kwargs['instance'] print dir(jp) print jp.get_status_display() if jp.get_status_display( ) != 'approved': #ONLY do the things on APPROVED job postings print "Not approved, returning" return print "Processing, it's approved" try: to_be_emailed = [] #list of email addresses to be emailed print "For jobposting ", jp for g in jp.for_programmes.all(): print 'Got group', g for u in g.user_set.all(): print 'Got user', u.username try: to_be_emailed.append("*****@*****.**" % (u.username)) c = student.objects.get(prn=u.username) if c is student: to_be_emailed.append( student.objects.get(prn=u.username)).email except student.DoesNotExist as s: print "%s hasn't yet filled in details...so couldn't get his personal email address" % u.username continue except Exception as e: print e continue poster_id = jp.posted_by poster_full_name = "Unknown User" if jp.non_sicsr_poster: record = User.objects.get(username=poster_id) poster_full_name = record.get_full_name( ) if record.get_full_name().strip( ) != '' else record.username #TODO: to get the provider name properly and fix this #provider = UserSocialAuth.objects.get(uid=poster_id).provider #poster_full_name = "%s from %s" % (poster_full_name, provider) else: u = user.objects.get(username=poster_id) poster_full_name = u.fullname if u.fullname.strip( ) != '' else u.username print "Poster's Full name : ", poster_full_name html_content = """ Hi, A new job posting has been put up on LaResume-X by <b>%s</b> for <b>%s</b>. It's detail are as follows : <ul> <li>Organization's Website: %s </li> <li>Description: <p>%s</p> </li> <li>How to Apply ? %s </li> </ul> To register your interest in it go to <a href='http://projects.sdrclabs.in/laresumex/jobposting/views/view'>here</a> <br/> Thanks! <br/> Regards,<br/> Team LaResume-X """ % (poster_full_name, jp.company_name, jp.company_url, jp.description, jp.how_to_apply) text_content = """ Hi, A new job posting has been put up on LaResume-X by %s for %s. To register your interest in it go to http://projects.sdrclabs.in/laresumex/jobposting/views/view It's detail are as follows : Organization's Website: %s Description: %s How to Apply ? %s Thanks! Regards, Team LaResume-X """ % (poster_full_name, jp.company_name, jp.company_url, jp.description, jp.how_to_apply) email = EmailMultiAlternatives('[LaResume-X]New job posting', text_content) email.attach_alternative(html_content, 'text/html') #add the managers for x in MANAGERS: email.bcc.append(x[1]) email.bcc = to_be_emailed email.subject = "[LaResume-X] New job posting" email.send(fail_silently=False) print "Sent email succesfully to ", to_be_emailed print "Total addresses emailed :", len(to_be_emailed) except SMTPException as e: print 'Exception occured when trying to actually send the email' print e except Exception as e: print 'Exception occurred when constructing email messages' print e mail_managers( subject="Emailing problem", message="Couldn't send email about jobposting for %s by %s" % (jp.company_name, poster_full_name), fail_silently=False)