def notify_by_email(sender, to, subject, message_content, cc=False, attachment=False, template='default.txt'): from django.core.mail import EmailMessage from django.core.mail import EmailMultiAlternatives is_array = lambda var: isinstance(var, (list, tuple)) if not sender: sender = settings.EMAILS['sender']['default'] email = EmailMultiAlternatives(subject=str(settings.EMAILS['tag']) + " " + str(subject), from_email=sender, to=[to]) # email.esp_extra = {"sender_domain": settings.EMAIL_SENDER_DOMAIN} if template: message_content['FOOTER'] = settings.EMAILS['footer'] email.body = render_to_string(template, message_content) else: email.body = str(message_content) if attachment: if is_array(attachment): for a in attachment: attach_to_email(email, a) else: attach_to_email(email, attachment) if cc: email.cc = [cc] try: email.send() return True except: return False
def notify_by_email(sender,to,subject,message_content,cc=False,attachment=False,template='default.txt'): from django.core.mail import EmailMessage from django.core.mail import EmailMultiAlternatives is_array = lambda var: isinstance(var, (list, tuple)) if not sender: sender = settings.EMAILS['sender']['default'] email = EmailMultiAlternatives( subject=str(settings.EMAILS['tag']) + " " + str(subject), from_email=sender, to=[to] ) # email.esp_extra = {"sender_domain": settings.EMAIL_SENDER_DOMAIN} if template: message_content['FOOTER'] = settings.EMAILS['footer'] email.body = render_to_string(template,message_content) else: email.body = str(message_content) if attachment: if is_array(attachment): for a in attachment: attach_to_email(email,a) else: attach_to_email(email,attachment) if cc: email.cc=[cc] try: email.send() return True except: return False
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_email(self, request, queryset): """Sends email to selected users using templates on server. The templates are as follows: templates/bookswap/mass_email_sub.html - one line subject templates/bookswap/mass_email_body.html - HTML body templates/bookswap/mass_email_body.txt - text body""" from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from django.core import mail emails = [] for user in queryset: sub = render_to_string('bookswap/mass_email_sub.html', {'user': user}).split("\n")[0] e = EmailMultiAlternatives() e.subject = sub e.to = [user.email,] e.body = render_to_string('bookswap/mass_email_body.txt', {'user':user}) e.attach_alternative(render_to_string( 'bookswap/mass_email_body.html', {'user':user}), "text/html") emails.append(e) connection = mail.get_connection() connection.send_messages(emails) messages.success(request, "Emails sent!")
def send_email(self): message = self.trigger.message context_dict = {'volunteer': self.volunteer, 'assignment': self.assignment} body = message.rendered_body(context_dict) email_params = { 'subject': message.rendered_subject(context_dict), 'to': [self.volunteer.email_address], 'from_email': settings.FROM_ADDRESS, } if message.body_is_html: email = EmailMultiAlternatives(**email_params) email.attach_alternative(body, "text/html") email.auto_text = True else: email = EmailMessage(**email_params) email.body = body email.auto_html = True name_tag = ("name - %s" % message.name)[:50] trigger_tag = ("trigger - %s" % self.trigger.id)[:50] email.tags = [name_tag, trigger_tag] logger.info("Sending %s" % email_params) print("Sending %s" % email_params) try: email.send(fail_silently=False) self.sent_date = date.today() except MandrillAPIError: print("FAILED %s" % email_params) self.send_failed = True self.save() return not self.send_failed
def send_campaign(self, campaign, fail_silently=False): """ Does the actual work """ from campaign.models import BlacklistEntry from_email = self.get_from_email(campaign) from_header = self.get_from_header(campaign, from_email) subject = campaign.template.subject text_template = template.Template(campaign.template.plain) if campaign.template.html is not None and campaign.template.html != "": html_template = template.Template(campaign.template.html) sent = 0 used_addresses = [] for recipient_list in campaign.recipients.all(): for recipient in recipient_list.object_list(): # never send mail to blacklisted email addresses recipient_email = getattr(recipient, recipient_list.email_field_name) if not BlacklistEntry.objects.filter(email=recipient_email).count() and not recipient_email in used_addresses: msg = EmailMultiAlternatives(subject, to=[recipient_email,], from_email=from_header) context = self.context_class(recipient) context.update({'recipient_email': recipient_email}) if campaign.online: context.update({'view_online_url': reverse("campaign_view_online", kwargs={ 'object_id': campaign.pk}), 'site_url': Site.objects.get_current().domain}) msg.body = text_template.render(context) if campaign.template.html is not None and campaign.template.html != "": html_content = html_template.render(context) msg.attach_alternative(html_content, 'text/html') sent += self.send_mail(msg, fail_silently) used_addresses.append(recipient_email) return sent
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, request=None, *mail_args, **mail_kwargs): """ Renders and sends your form as an email. Required args: None Optional args: * ``request``: Pass this if you want a ``RequestContext`` for the form and mail templates Suggested args: * ``subject``, the subject line of the email * ``from_email``, who the email will show as from * ``to``, who the email will be sent to (see https://docs.djangoproject.com/en/dev/topics/email/#django.core.mail.EmailMessage) """ self._request = request context = self._get_context() message = EmailMultiAlternatives(*mail_args, **mail_kwargs) message.body = render_to_string(self.text_mail_template, context) html_content = render_to_string(self.html_mail_template, context) message.attach_alternative(html_content, "text/html") message.send()
def send_email(to, sender, subject, message_content, attachment=False, template='default.txt'): from django.core.mail import EmailMessage from django.core.mail import EmailMultiAlternatives from django import render_to_string is_array = lambda var: isinstance(var, (list, tuple)) if not sender: sender = settings.EMAILS['sender'] email = EmailMultiAlternatives(subject="[" + settings.EMAILS['tag'] + "] " + subject, from_email=sender, to=[to]) if settings.EMAIL_SENDER_DOMAIN: email.esp_extra = {"sender_domain": settings.EMAIL_SENDER_DOMAIN} message_content['FOOTER'] = settings.EMAILS['footer'] email.body = render_to_string(template, message_content) if attachment: if is_array(attachment): for a in attachment: attach_to_email(email, a) else: attach_to_email(email, attachment) try: email.send() return True except: return False
def _send_confirm_swap_email(user, match): logger.info("sending swap confirmation emails: %s", match) for from_profile, to_profile in [ (match.from_profile, match.to_profile), (match.to_profile, match.from_profile)]: logger.info(" sending swap confirmation email from %s to %s", from_profile, to_profile) message = EmailMultiAlternatives( subject=u"Your VoteSwap with {user} is confirmed!".format( user=from_profile.fb_name), from_email='*****@*****.**', to=[to_profile.user.email], reply_to=[from_profile.user.email]) profile_context = ProfileContext(from_profile) paired_profile_context = ProfileContext(to_profile) message.body = _format_email( render_to_string( 'users/emails/confirm_swap_email.txt', {'profile_ctx': profile_context, 'paired_profile_ctx': paired_profile_context})) message.attach_alternative( _format_email( render_to_string( 'users/emails/confirm_swap_email.html', {'profile_ctx': profile_context, 'paired_profile_ctx': paired_profile_context})), 'text/html') try: message.send() except Exception as e: logger.exception( ("Failed to send swap confirmation email for match %s. " "Errors: %s"), match, e) raise
def send_campaign(self, campaign, fail_silently=False): """ Does the actual work """ from campaign.models import BlacklistEntry subject = campaign.template.subject text_template = template.Template(campaign.template.plain) if campaign.template.html is not None and campaign.template.html != u"": html_template = template.Template(campaign.template.html) sent = 0 used_addresses = [] for recipient_list in campaign.recipients.all(): for recipient in recipient_list.object_list(): # never send mail to blacklisted email addresses recipient_email = getattr(recipient, recipient_list.email_field_name) if not BlacklistEntry.objects.filter(email=recipient_email).count() and not recipient_email in used_addresses: msg = EmailMultiAlternatives(subject, to=[recipient_email,]) context = self.context_class(recipient) context.update({'recipient_email': recipient_email}) if campaign.online: context.update({'view_online_url': reverse("campaign_view_online", kwargs={'object_id': campaign.pk}), 'site_url': Site.objects.get_current().domain}) msg.body = text_template.render(context) if campaign.template.html is not None and campaign.template.html != u"": html_content = html_template.render(context) msg.attach_alternative(html_content, 'text/html') sent += self.send_mail(msg, fail_silently) used_addresses.append(recipient_email) return sent
def _send_bugfix_email(user): if not user: logger.info("Skipping nonexistent user") return logger.info("Sending bugfix email to %s", user) if not user.email: logger.error("User %s (%s) doesn't have an email", user, user.id) return message = EmailMultiAlternatives( from_email=u'*****@*****.**', to=[user.email], subject=u"Urgent Voteswap bugfix! Come back and swap again!") message.body = _format_email( render_to_string('users/emails/bugfix-email.txt')) message.attach_alternative( _format_email( render_to_string('users/emails/bugfix-email.html')), 'text/html') try: message.send() except Exception as e: logger.exception( ("Failed to send bugfix email for user %s. " "Errors: %s"), user, e) raise
def send_message(self, recipients: List[str], subject: str, template: str = None, template_context: dict = None, from_address: str = None, text: str = None, **kwargs): """Send emails in the background. For each recipient a new E-Mail is generated. Args: recipients: List of E-Mail addresses we send to. subject: Subject of E-Mail. template: Optional path to a django template. This template is rendered and attached as text/html multipart template_context: Optional conext for template above. from_address: Optional Address we send E-Mail addresses from. If not given, we use the default from Settings text: Optional plaintext for the body """ self.prepare(**kwargs) emails = [] # If we don't have text and template, return now. if not text and not template: raise ValueError("Either text or template must be supplied.") for recipient in recipients: # Create a separate email for each recipient email = EmailMultiAlternatives() email.from_email = from_address if from_address else settings.EMAIL_FROM email.body = text if text else '' email.to = [recipient] email.subject = subject if template: _template = loader.get_template(template) context = template_context if template_context else {} # Lookup user from recipient address, to give it to the template users = User.objects.filter(email=recipient) if users.exists(): context['_user'] = users.first() # If debug is disabled, minify HTML to save bandwidth html = _template.render(context) if not settings.DEBUG: html = html_minify(html) email.attach_alternative(html, 'text/html') LOGGER.debug("Prepared E-Mail '%s' to %s", subject, recipient) emails.append(email) try: with get_connection() as connection: sent = connection.send_messages(emails) return sent == len( emails) # send_messages returns amount of emails sent except SMTPException as exc: # Always return true when debugging if settings.DEBUG: LOGGER.warning("Failed to send emails %r", exc) return True raise
def _send_reject_swap_email(user, match): logger.info("sending swap rejection email: %s", match) message = EmailMultiAlternatives( from_email=u'*****@*****.**', to=[match.from_profile.user.email], subject=u"{user} rejected your VoteSwap".format( user=user.profile.fb_name)) from_profile_context = ProfileContext(match.from_profile) to_profile_context = ProfileContext(match.to_profile) message.body = _format_email( render_to_string( 'users/emails/reject_swap_email.txt', {'from_profile_ctx': from_profile_context, 'to_profile_ctx': to_profile_context})) message.attach_alternative( _format_email( render_to_string( 'users/emails/reject_swap_email.html', {'from_profile_ctx': from_profile_context, 'to_profile_ctx': to_profile_context})), 'text/html') try: message.send() except Exception as e: logger.exception( ("Failed to send swap rejection email for match %s. " "Errors: %s"), match, e) raise
def _send_sad_email(user): if not user: logger.info("Skipping nonexistent user") return logger.info("Sending sad email to %s", user) if not user.email: logger.error("User %s (%s) doesn't have an email", user, user.id) return message = EmailMultiAlternatives( from_email=u'*****@*****.**', to=[user.email], subject=u"Thank you for your help") # nopep8 message.body = _format_email( render_to_string('users/emails/sad-email.txt')) message.attach_alternative( _format_email( render_to_string('users/emails/sad-email.html')), 'text/html') try: message.send() except Exception as e: logger.exception( ("Failed to send sad email for user %s. " "Errors: %s"), user, e) raise
def _send_fb_message_email(user): if not user: logger.info("Skipping nonexistent user") return logger.info("Sending fb-message email to %s", user) if not user.email: logger.error("User %s (%s) doesn't have an email", user, user.id) return message = EmailMultiAlternatives( from_email=u'*****@*****.**', to=[user.email], subject=u"Problems contacting your swap? Facebook might be hiding your messages.") # nopep8 message.body = _format_email( render_to_string('users/emails/fb-message-problem.txt')) message.attach_alternative( _format_email( render_to_string('users/emails/fb-message-problem.html')), 'text/html') try: message.send() except Exception as e: logger.exception( ("Failed to send fb-message email for user %s. " "Errors: %s"), user, e) raise
def _send(self): """ Does the actual work """ subject = self.template.subject text_template = template.Template(self.template.plain) if self.template.html is not None and self.template.html != u"": html_template = template.Template(self.template.html) sent = 0 used_addresses = [] for recipient_list in self.recipients.all(): for recipient in recipient_list.object_list(): # never send mail to blacklisted email addresses recipient_email = getattr(recipient, recipient_list.email_field_name) if not BlacklistEntry.objects.filter(email=recipient_email).count() and not recipient_email in used_addresses: msg = EmailMultiAlternatives(subject, to=[recipient_email,]) context = MailContext(recipient) msg.body = text_template.render(context) if self.template.html is not None and self.template.html != u"": html_content = html_template.render(context) msg.attach_alternative(html_content, 'text/html') sent += backend.send_mail(msg) used_addresses.append(recipient_email) return sent
def send(self): #Create the weekmail content and send it. html_parser = html.parser.HTMLParser() content = {'weekmail': html_parser.unescape(self)} mail_content_txt = render_to_string('communication/weekmail.txt', content) mail_content_html = render_to_string('communication/weekmail.html', content) #You can change the weekmail recipients here. recipients = settings.WEEKMAIL_RECIPIENTS sender = settings.DEFAULT_FROM_EMAIL try: mail = EmailMultiAlternatives() mail.subject = _('[Weekmail] %s') % (self.subject) mail.body = mail_content_txt mail.from_email = sender mail.to = recipients mail.cc = [sender,] mail.attach_alternative(mail_content_html, "text/html") for attachment in self.attached.all(): mail.attach_file(attachment.file.path) mail.send() self.sent_date = timezone.now() self.save() return True except SMTPException: return False return False
def send_installation_email(event_name, postinstall_email, attendee): email = EmailMultiAlternatives() first_name = attendee.first_name last_name = attendee.last_name email.subject = get_installation_subject(first_name, last_name, event_name) email.from_email = postinstall_email.contact_email email.body = '' email.attach_alternative(postinstall_email.message, "text/html") email.to = [attendee.email] email.send(fail_silently=False)
def send_template_mail(subject, template, context, to, fail_silently=False): email = EmailMultiAlternatives(subject=subject, to=to) c = Context(context) if 'txt' in template: email.body = render_to_string(template, c) if 'html' in template: html = render_to_string(template, c) email.attach_alternative(html, 'text/html') return email.send(fail_silently=fail_silently)
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 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 send_activity_email(event, activity, justification=None): event_name = event.name activity_title = activity.title activity_status = activity.status_choices[int(activity.status) - 1][1] email_to = activity.speaker_contact email = EmailMultiAlternatives() email.subject = get_activity_subject(event_name) body_txt, body_html = get_activity_body(event_name, activity_title, activity_status, justification) email.body = body_txt email.attach_alternative(body_html, "text/html") email.to = [email_to] email.send(fail_silently=False)
def installation(request, event_slug): installation_form = InstallationForm(request.POST or None, prefix='installation') hardware_form = HardwareForm(request.POST or None, prefix='hardware') forms = [installation_form, hardware_form] errors = [] if request.POST: if hardware_form.is_valid() and installation_form.is_valid(): try: hardware = hardware_form.save() install = installation_form.save() install.hardware = hardware event = Event.objects.filter(slug__iexact=event_slug).first() if not event: return handler404(request) install.event = event install.installer = EventUser.objects.filter(user=request.user).filter(event=event).first() install.save() # Send post-install email if its defined postinstall_email = InstallationMessage.objects.filter(event=event).first() if postinstall_email: attendee = install.attendee email = EmailMultiAlternatives() subject = _( u"%(first_name)s %(last_name)s, thank you for participating in FLISoL %(event_name)s") % { 'event_name': event.name, 'first_name': attendee.first_name, 'last_name': attendee.last_name} email.from_email = postinstall_email.contact_email email.subject = unicode(subject) email.body = '' email.attach_alternative(postinstall_email.message, "text/html") email.to = [attendee.email] try: email.send(fail_silently=False) except Exception: # Don't raise email exception to form exception pass messages.success(request, _("The installation has been registered successfully. Happy Hacking!")) return HttpResponseRedirect('/event/' + event_slug) except Exception as e: logger.error(e) if hardware is not None: Hardware.delete(hardware) if install is not None: Installation.delete(install) messages.error(request, _("The installation couldn't be registered (check form errors)")) errors = get_forms_errors(forms) return render(request, 'installation/installation-form.html', update_event_info(event_slug, request, {'forms': forms, 'errors': errors, 'multipart': False}))
def send_welcome_email(self): welcome_email = EmailMultiAlternatives() welcome_email.to = [self.email] welcome_email.subject = render_to_string('accounts/emails/welcome_email_subject.txt') d = { 'email_body': AutoGeneratedEmail.objects.get(email_title = 'user_welcome_email').email_body } html_message = render_to_string('accounts/emails/welcome_email.html', d) welcome_email.body = render_to_string('accounts/emails/welcome_email.txt', d) welcome_email.attach_alternative(html_message, 'text/html') welcome_email.send(fail_silently=False)
def send_ticket_email(ticket_data, ticket_svg): event_name = ticket_data['event'].name first_name = ticket_data['first_name'] last_name = ticket_data['last_name'] email_to = ticket_data['email'] ticket_code = ticket_data['ticket'].code email = EmailMultiAlternatives() email.subject = get_ticket_subject(event_name) body_txt, body_html = get_ticket_body(first_name, last_name, event_name) email.body = body_txt email.attach_alternative(body_html, "text/html") email.to = [email_to] email.attach('Ticket-{}.pdf'.format(ticket_code), cairosvg.svg2pdf(bytestring=ticket_svg), 'application/pdf') email.send(fail_silently=False)
def installation(request, event_slug): installation_form = InstallationForm(event_slug, request.POST or None, prefix='installation') hardware_form = HardwareForm(request.POST or None, prefix='hardware') forms = [installation_form, hardware_form] errors = [] if request.POST: if hardware_form.is_valid() and installation_form.is_valid(): try: hardware = hardware_form.save() install = None install = installation_form.save() install.hardware = hardware event = Event.objects.filter(slug__iexact=event_slug).first() if not event: return handler404(request) install.event = event install.installer = EventUser.objects.filter(user=request.user).filter(event=event).first() install.save() #Send post-install email if its defined postinstallemail = InstallationMessage.objects.filter(event=event).first() if postinstallemail: attendee = install.attendee email = EmailMultiAlternatives() subject = _(u"%(first_name)s %(last_name)s, thank you for participating in FLISoL %(event_name)s") % { 'event_name': event.name, 'first_name': attendee.user.first_name, 'last_name': attendee.user.last_name} email.from_email = postinstallemail.contact_email email.subject = unicode(subject) email.body = '' email.attach_alternative(postinstallemail.message, "text/html") email.to = [attendee.user.email] try: email.send(fail_silently=False) except Exception: #Don't raise email exception to form exception pass messages.success(request, _("The installation has been registered successfully. Happy Hacking!")) return HttpResponseRedirect('/event/' + event_slug) except Exception: if hardware is not None: Hardware.delete(hardware) if install is not None: Installation.delete(install) messages.error(request, _("The installation couldn't be registered (check form errors)")) errors = get_forms_errors(forms) return render(request, 'installation/installation-form.html', update_event_info(event_slug, request, {'forms': forms, 'errors': errors, 'multipart': False}))
def check_birthday(info_mail, body_text, subject): """TODO""" today = datetime.date.today() future = today + datetime.timedelta(days=2) members = Member.objects.filter( birthday__day=future.day, birthday__month=future.month) if members.count() == 0: return 'No upcomming birthdays!' message = EmailMessage(subject=subject) template = Template(body_text) context = Context({'member_list': members}) message.body = template.render(context) message.to = [info_mail] message.from_email = 'JUSO Aargau <*****@*****.**>' message.send() return '{x} birthdays sent'.format(x=members.count())
def add_staff(request): response = {} try: event_id = request.POST["event_id"] staff_type = request.POST['staff_type'] username = request.POST['username'] name = request.POST['name'] url = request.POST['url'] imgurl = request.POST['imgurl'] event = Event.objects.get(id=event_id) try: user = User.objects.get(username=username) except User.DoesNotExist: user = None staff = Staff() staff.staff = user staff.name = name staff.url = url staff.event = event staff.type = staff_type staff.imgurl = imgurl staff.save() to = [event.creator.username] for attendee in event.attendee_set.all(): if not to.__contains__(attendee.attendee.username): to.append(attendee.attendee.username) msg = EmailMultiAlternatives() msg.from_email = "*****@*****.**" msg.to = to msg.subject = "New Attendee!" body = "A new " + ("Organizer" if staff_type == "O" else ("Speaker" if staff_type == "S" else "Mentor")) + " has been added to the event <a href='http://events-finder.appspot.com/event/" + event_id + "'>" + event.name + "</a>!" msg.body = body msg.attach_alternative(body, 'text/html') send_async_mail(msg) response['staff_id'] = staff.id except Exception, err: response['error'] = err.__str__()
def to_mail(self, mail, with_body=True): """ @param mail : the Mail instance we want to build the Message for @return a EMailMultiAlternatives ready to send """ m = EmailMultiAlternatives(subject=self.subject, body='', from_email=mail.envelope_from, to=[mail.recipient]) m.extra_headers.update({ settings.CAMPAIGNS['X_USER_ID_HEADER']: str(mail.message.author.pk), settings.CAMPAIGNS['X_MESSAGE_ID_HEADER']: mail.identifier, 'Precedence': 'bulk', 'X-Report-Abuse': 'Please report abuse to {}'.format(mail.abuse_url), 'List-Unsubscribe': '<mailto:{}>, <{}>'.format(mail.unsubscribe_addr, mail.unsubscribe_url), 'Message-ID': mk_msgid(), 'From': '{} <{}>'.format(mail.message.sender_name, mail.message.sender_email), }) post_headers_generation.process( m.extra_headers, mail, settings.CAMPAIGNS['HEADERS_FILTERS_PARAMS']) if with_body: plaintext, html = self.mk_body(mail) m.body = plaintext m.attach_alternative(html, "text/html") # attachments for a in self.attachments.all(): m.attach(*a.to_email_attachment()) return m
def send_email(to, addr, pdf, dt_date): # send email email = EmailMultiAlternatives() # TODO: redefining template email.subject = "Your quote for " + addr.address + " is attached" email.to = [to] context = { 'address': addr.address, 'subject': settings.QUOTE_SUBJECT } # Remove CC/BCC to stop spam catchers. #email.bcc = get_bcc_emails() #email.cc = get_cc_emails() email.body = render_to_string('download/email/quote.txt', context) email.attach_alternative(render_to_string('download/email/quote.html', context), 'text/html') with open(str(pdf.upload_file), 'rb') as f: content = f.read() email.attach(pdf.address.address + '.pdf', content, 'application/octate-stream') email.send()
def send_welcome_email(self): welcome_email = EmailMultiAlternatives() welcome_email.to = [self.email] welcome_email.subject = render_to_string( 'accounts/emails/welcome_email_subject.txt') d = { 'email_body': AutoGeneratedEmail.objects.get( email_title='user_welcome_email').email_body } html_message = render_to_string('accounts/emails/welcome_email.html', d) welcome_email.body = render_to_string( 'accounts/emails/welcome_email.txt', d) welcome_email.attach_alternative(html_message, 'text/html') welcome_email.send(fail_silently=False)
def _view_subscriber_verification_context(request, form_class): """ A simple view that shows a form for subscription for the newsletter. """ context = {} if request.POST: context['form'] = form_class(request.POST) if context['form'].is_valid(): subscription = SubscriberVerification() contact = context['form'].save() subscription.contact = context['form'].instance subscription.save() link_id = str(subscription.link_id) mail_context = Context({ 'base_url': "%s://%s" % ("https" if request.is_secure() else "http", request.get_host()), 'link_id': link_id, }) content_html = render_to_string('newsletter/newsletter_mail_verification.html', mail_context) content_text = html2text(content_html) message = EmailMultiAlternatives() message.from_email = smart_str(DEFAULT_HEADER_REPLY) message.extra_headers = {'Reply-to': smart_str(DEFAULT_HEADER_REPLY)} message.to = [smart_str(context['form'].instance.email)] message.subject = render_to_string('newsletter/newsletter_mail_verification_subject.html', context) message.body = smart_str(content_text) message.attach_alternative(smart_str(content_html), "text/html") try: message.send() except Exception, e: print e context['send'] = True
def send(self, context=None): """ When sending an email a set of attributes will be required. The required attributes are mainly dictated by django.core.mail used to send mail: * Message or body. * Subject. * Recipients list or to. * From email :param context: A dictionary with context variables to be used with the subject and the message. :return: A tuple (result, message) where result is a boolean indicating if mail could be sent or not. An a message in case the mail could not be sent the message will be the reason. This could have future uses if logging is implemented. """ subject = self.subject body = self.body if context is None: # Needed whe no context is received so no replacement is tried. pass elif not isinstance(context, dict): raise ValueError( _('The argument for send method must be a ' 'mapping.')) else: subject = replace_context_variable(text=self.subject, context_variable=context) body = replace_context_variable(text=self.body, context_variable=context) msg = EmailMultiAlternatives(subject=subject, from_email=self.from_email, to=clean_address_list(self.to), cc=clean_address_list(self.cc), bcc=clean_address_list(self.bcc), reply_to=clean_address_list( self.reply_to)) msg.body = body msg.attach_alternative(body, 'text/html') return msg.send()
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 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 attend_event(request): response = {} try: event_id = request.POST["event_id"] attendee_type = request.POST['attendee_type'] event = Event.objects.get(id=event_id) if attendee_type != "" and not Attendee.objects.filter(attendee=request.user, event=event).exists(): attendee = Attendee() attendee.attendee = request.user attendee.event = event attendee.type = attendee_type attendee.save() to = [event.creator.username] for attendee in event.attendee_set.all(): if not to.__contains__(attendee.attendee.username): to.append(attendee.attendee.username) msg = EmailMultiAlternatives() msg.from_email = "*****@*****.**" msg.to = to msg.subject = "New Attendee!" body = "<a href='http://events-finder.appspot.com/accounts/view/" + request.user.username + "'>" + request.user.first_name + " " + request.user.last_name + "</a> is now " + ('attending' if attendee_type == 'A' else 'tracking') + " the event <a href='http://events-finder.appspot.com/event/" + event_id + "'>" + event.name + "</a>!" msg.body = body msg.attach_alternative(body, 'text/html') send_async_mail(msg) else: attendee_instance = Attendee.objects.get(attendee=request.user, event=event) attendee_instance.delete() except Exception, err: response['error'] = err.__str__()
def _send(self, connection): """ Does the actual work """ subject = self.template.subject text_template = template.Template(self.template.plain) if self.template.html is not None and self.template.html != u"": html_template = template.Template(self.template.html) sent = 0 used_addresses = [] for recipient_list in self.recipients.all(): for recipient in recipient_list.subscribers.all(): # never send mail to blacklisted email addresses if not BlacklistEntry.objects.filter(email=recipient.email).count() and not recipient.email in used_addresses: msg = EmailMultiAlternatives(subject, connection=connection, to=[recipient.email,]) msg.body = text_template.render(template.Context({'salutation': recipient.salutation,})) if self.template.html is not None and self.template.html != u"": html_content = html_template.render(template.Context({'salutation': recipient.salutation,})) msg.attach_alternative(html_content, 'text/html') sent += msg.send() used_addresses.append(recipient.email) return sent
def post(self, request): data = request.POST if data['content'] == '': return HttpResponse(status=404) user = request.user email = EmailMultiAlternatives() email.from_email = '*****@*****.**' # Change? from user.email email.to = [data['send_to']] email.body = data['content'] if data['subject'] == '': email.subject = f'No subject - ({user.username} #{user.email})' else: email.subject = data['subject'] + f' - ({user.username} #{user.email})' if request.FILES: file = request.FILES['file'] email.attach(file.name, file.read(), file.content_type) email.send(False) return HttpResponse(status=204)
def _send_random_match_email(user): logger.info("Sending random match email to %s", user) if not user.email: logger.error("User %s (%s) doesn't have an email", user, user.id) return message = EmailMultiAlternatives( from_email=u'*****@*****.**', to=[user.email], subject=u"VoteSwap with a random user") message.body = _format_email( render_to_string('users/emails/random-matches.txt')) message.attach_alternative( _format_email( render_to_string('users/emails/random-matches.html')), 'text/html') try: message.send() except Exception as e: logger.exception( ("Failed to send random match email for user %s. " "Errors: %s"), user, e) raise
def send_email(self, verbose=False): # Return whether or not the sendable was sent. message = self.trigger.message body = self.email_body() email_params = { 'subject': message.rendered_subject(self._email_context_dict()), 'to': [self.volunteer.email_address], 'bcc': self.trigger.bcc(), 'from_email': self.trigger.campaign.from_address, } if message.body_is_html: email = EmailMultiAlternatives(**email_params) email.attach_alternative(body, "text/html") email.auto_text = True else: email = EmailMessage(**email_params) email.body = body email.auto_html = True # Tags are a mandril feature. name_tag = ("name - %s" % message.name)[:50] trigger_tag = ("trigger - %s" % self.trigger.id)[:50] email.tags = [name_tag, trigger_tag] logger.info("Sending %s" % email_params) if verbose: print("Sending %s" % email_params) try: email.send(fail_silently=False) self.sent_date = date.today() except MandrillAPIError: print("FAILED %s" % email_params) self.send_failed = True self.save() return not self.send_failed
def send_email_message(msg_path, recipient=None, dry_run=False): email_path = os.path.join(msg_path, "email.html") with open(email_path, "r") as body_f: body = body_f.read() intervention = get_intervention_from_path(email_path) if not intervention: return if intervention.sent: logger.info("Refusing to resend %s", intervention) return logger.info("Sending message to %s", intervention) if settings.DEBUG: # Belt-and-braces to ensure we don't accidentally send to # real users to = settings.TEST_EMAIL_TO else: to = intervention.contact.email if recipient: # Always allow overriding the test fax recipient to = recipient subject = ( "Information about your nimodipine prescribing from OpenPrescribing.net" ) msg = EmailMultiAlternatives( subject=subject, from_email=settings.DEFAULT_FROM_EMAIL, to=[to], reply_to=[settings.DEFAULT_FROM_EMAIL], ) msg = inline_images(msg, body) msg.tags = ["nimodipine"] msg.body = email_as_text(msg.alternatives[0][0]) msg.track_clicks = True if not dry_run: msg.send() intervention.sent = True intervention.save()
def send_mail(content, recipients, attachments): """Docstring""" mails = [] for recipient in serializers.deserialize("json", recipients): mail_ = EmailMessage(content['subject']) message = content['message'].format(member=recipient.object) mail_.body = message message = render_html(message, content['etype'], content['img_url'], content['sender'], content['template']) mail_.attach_alternative(message, 'text/html') mail_.from_email = '{name} <{email}>'.format( email=content['sender'], name=content['name']) mail_.to = [recipient.object.email] for att in attachments: mail_.attach(att['name'], open(att['path'], 'rb').read()) mails.append(mail_) connection = mail.get_connection() for mail_ in mails: try: connection.send_messages([mail_]) except: pass return "Success!"
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 msg_without_gpg(self, subject, frm, recipient, text, html): msg = EmailMultiAlternatives(subject, from_email=frm, to=[recipient]) msg.body = text msg.attach_alternative(html, 'text/html') return msg
def prepare_message(self, contact): from emencia.utils.tokens import tokenize from emencia.utils.newsletter import fix_tinymce_links uidb36, token = tokenize(contact) base_url = self.base_url context = Context({ 'contact': contact, 'base_url': base_url, 'newsletter': self, 'tracking_image_format': TRACKING_IMAGE_FORMAT, 'uidb36': uidb36, 'token': token, 'UNIQUE_KEY': ''.join(sample(UNIQUE_KEY_CHAR_SET, UNIQUE_KEY_LENGTH)) }) message = EmailMultiAlternatives() message.from_email = smart_str(self.header_sender) message.extra_headers = {'Reply-to': smart_str(self.header_reply)} message.to = [contact.mail_format()] # Render only the message provided by the user with the WYSIWYG editor message_template = Template(fix_tinymce_links(self.content)) message_content = message_template.render(context) context.update({'message': message_content}) # link_site_exist = False link_site = render_to_string('newsletter/newsletter_link_site.html', context) context.update({'link_site': link_site}) if INCLUDE_UNSUBSCRIPTION: unsubscription = render_to_string('newsletter/newsletter_link_unsubscribe.html', context) context.update({'unsubscription': unsubscription}) if TRACKING_IMAGE: image_tracking = render_to_string('newsletter/newsletter_image_tracking.html', context) context.update({'image_tracking': image_tracking}) content_template = get_template('mailtemplates/{0}/{1}'.format(self.template, 'index.html')) content = content_template.render(context) if TRACKING_LINKS: from emencia.utils.newsletter import track_links content = track_links(content, context) content = smart_unicode(content) p = Premailer(content, base_url=base_url, preserve_internal_links=True) content = p.transform() # newsletter_template = Template(self.content) message.body = html2text(content) message.attach_alternative(smart_str(content), "text/html") title_template = Template(self.title) title = title_template.render(context) message.subject = title for attachment in self.attachments: message.attach(attachment) return message