def patch(self, request, *args, **kwargs): challenge = Challenge.objects.get(id=kwargs['id']) candidate = User.objects.get(id=challenge.candidate_id) creator = User.objects.get(id=challenge.creator_id) candidate_email = EmailMultiAlternatives() candidate_email.subject = 'Propulsion Academy - Challenge Results' candidate_email.to = [candidate.email] creator_email = EmailMultiAlternatives() creator_email.subject = f'Challenge Results - Candidate: {candidate.first_name} {candidate.last_name}' creator_email.to = [creator.email] if challenge.score < 40: html_content_candidate_email = generate_challenge_score_failed_candidate( candidate) html_content_creator_email = generate_challenge_score_failed_creator( creator, candidate, challenge) elif 40 <= challenge.score < 70: html_content_candidate_email = generate_challenge_score_needs_review_candidate( candidate, challenge) html_content_creator_email = generate_challenge_score_needs_review_creator( creator, candidate, challenge) else: html_content_candidate_email = generate_challenge_score_passed_candidate( candidate) html_content_creator_email = generate_challenge_score_passed_creator( creator, candidate, challenge) candidate_email.attach_alternative(html_content_candidate_email, "text/html") candidate_email.send(fail_silently=False) creator_email.attach_alternative(html_content_creator_email, "text/html") creator_email.send(fail_silently=False) return Response(status=200)
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_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 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_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_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 create(self, request, *args, **kwargs): candidate = User.objects.get(id=request.data['candidate']) challenge = Challenge(creator=request.user, candidate=candidate) challenge.status = 'SENT' challenge.save() easy_questions = random.sample( list(Question.objects.filter(difficulty='1')), 3) intermediate_questions = random.sample( list(Question.objects.filter(difficulty='2')), 2) hard_questions = random.sample( list(Question.objects.filter(difficulty='3')), 1) challenge.questions.set(easy_questions + intermediate_questions + hard_questions) email = EmailMultiAlternatives() email.subject = 'Propulsion Academy - You have a new Challenge!' email.to = [candidate.email] if candidate.is_active: email.attach_alternative( generate_challenge_created_content(candidate), "text/html") else: email.attach_alternative( generate_challenge_created_when_inactive_content(candidate), "text/html") email.send(fail_silently=False) return Response(status=200)
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_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 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 patch(self, request, *args, **kwargs): new_user = User.objects.get(id=kwargs['id']) email = EmailMultiAlternatives() email.subject = 'Propulsion Academy - New User Validation' email.to = [new_user.email] html_content = generate_new_user(new_user) email.attach_alternative(html_content, "text/html") email.send(fail_silently=False) return Response(status=200)
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 patch(self, request, *args, **kwargs): challenge = Challenge.objects.get(id=kwargs['id']) candidate = User.objects.get(id=challenge.candidate_id) email = EmailMultiAlternatives() email.subject = 'Propulsion Academy - You have a new Challenge!' email.to = [candidate.email] email.attach_alternative(generate_challenge_created_content(candidate), "text/html") email.send(fail_silently=False) return Response(status=200)
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 _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_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 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 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 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_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 _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 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 perform_create(self, serializer): new_user = User(email=serializer.validated_data['email'], username=serializer.validated_data['email'], is_active=False, is_staff=self.request.data['is_staff'], first_name=self.request.data['first_name'], last_name=self.request.data['last_name'], phone=self.request.data['phone']) new_user.set_password("Propulsion2020") new_user.save() email = EmailMultiAlternatives() email.subject = 'Propulsion Academy - New User Verification' email.to = [new_user.email] html_content = generate_new_user(new_user) email.attach_alternative(html_content, "text/html") email.send(fail_silently=False) return new_user
def create(self, request, *args, **kwargs): try: target_user = User.objects.all().get(email=request.data['email']) target_user.code = code_generator() target_user.save() email = EmailMultiAlternatives() email.subject = 'Propulsion Academy - Password Reset' email.to = [target_user.email] html_content = generate_password_reset(target_user) email.attach_alternative(html_content, "text/html") email.send(fail_silently=False) return Response(status=status.HTTP_202_ACCEPTED) except User.DoesNotExist: return Response( { "detail": "Your email doesn't match any profile or is invalid." }, status=status.HTTP_400_BAD_REQUEST)
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_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 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 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 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 setUp(self): organization, created = Organization.objects.get_or_create(name='Example Corp') self.mailbox = Mailbox.objects.create( name='test_mailbox', uri='maildir://' + MAILDIR_PATH, from_email='*****@*****.**' ) # clear any pre-existing messages in the local mailbox self.maildir.clear() self.team, created = Team.objects.get_or_create( name='Example Department', slug='example_dept', mailbox=self.mailbox ) self.ticket, created = Ticket.objects.get_or_create( title='Testing 123 Ticket', organization=organization, priority=4 ) self.ticket.teams.add(self.team) self.sender_email = EmailAddress.objects.create(email_address=self._sender_email) self.sender = Person.objects.create( first_name='sender_first_name', last_name='sender_last_name' ) self.sender.email_addresses.add(self.sender_email) self.recipient_email = EmailAddress.objects.create(email_address=self._recipient_email) self.recipient = Person.objects.create( first_name='recipient_first_name', last_name='recipient_last_name', ) self.recipient.email_addresses.add(self.recipient_email) cc_people, cc_emails = list(), list() for addr in self._cc_emails: email = EmailAddress.objects.create(email_address=addr) person = Person.objects.create( first_name='{}_first_name'.format(addr.split('@')[0]), last_name='{}_last_name'.format(addr.split('@')[0]) ) person.email_addresses.add(email) cc_emails.append(email) cc_people.append(person) self.cc_emails = cc_emails self.cc_people = cc_people email_message = EmailMultiAlternatives() email_message.body = 'Test message testing 123' email_message.from_email = self._sender_email email_message.to = self._recipient_email, email_message.cc = self._cc_emails email_message.subject = 'tests message subject' email_message.extra_headers['Message-Id'] = 'unique_id_goes_here' self.email_message_no_hashid_plain = copy.deepcopy(email_message) email_message.attach_alternative( '<html><body><p>Test message testing 123</p></body></html>', 'text/html' ) self.email_message_no_hashid = email_message
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
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 email(subject, template_name, merge_data={}, merge_global_data={}, recipients=[], preheader=None, bcc=None, reply_to=None, send=True): from django.conf import settings if not (subject and template_name and recipients): raise NameError() if not isinstance(recipients, list): raise TypeError("recipients must be a list") # bcc is set to False by default. # make sure bcc is in a list form when sent over if bcc not in [False, None] and not isinstance(bcc, list): raise TypeError("recipients must be a list") merge_global_data['subject'] = subject merge_global_data['current_year'] = timezone.now().year merge_global_data['company_name'] = settings.SITE_NAME merge_global_data['site_url'] = settings.SITE_URL if preheader: merge_global_data['preheader'] = preheader msg = EmailMultiAlternatives() msg.body = render_to_string(f"{template_name}.html") msg.content_subtype = "html" msg.from_email = f"CoderDojoChi<{settings.DEFAULT_FROM_EMAIL}>" msg.merge_data = merge_data msg.merge_global_data = merge_global_data msg.subject = subject msg.to = recipients if reply_to: msg.reply_to = reply_to if send: try: msg.send() except Exception as e: logger.error(e) logger.error(msg) raise e for recipient in msg.anymail_status.recipients.keys(): send_attempt = msg.anymail_status.recipients[recipient] if send_attempt.status not in ['queued', 'sent']: logger.error(f"user: {recipient}, {timezone.now()}") from coderdojochi.models import CDCUser user = CDCUser.objects.get(email=recipient) user.is_active = False user.admin_notes = f"User '{send_attempt.reject_reason}' when checked on {timezone.now()}" user.save() return msg
def create_mail(self): result = None tries = 0 # while (result is None or result is not 1) and tries < 5: print("Sending new email to " + self.receiver_user) legal = LegalSetting.objects.first() self.context['content'] = self.content self.context['legal'] = legal print(self.content) email = EmailMultiAlternatives('Subject', self.subject, connection=self.connection) email.subject = self.subject email.mixed_subtype = 'related' email.content_subtype = 'html' email.to = [self.receiver_user] if self.email_to: email.to.append(self.email_to) try: logo_file = legal.logo.open("rb") logo = MIMEImage(logo_file.read()) logo.add_header('Content-ID', '<{}>'.format(legal.logo.name)) email.attach(logo) logo_file.close() except: pass # Fill context with objects from database for k, v in self.context.items(): if hasattr(v, '__len__') and 'type' in v: clazz = apps.get_model(app_label=v['app'], model_name=v['type']) try: i = clazz.objects.get(id=v['id']) self.context[k] = i except Exception as e: print("Unable to serialize") if 'files' in self.context and self.context['files']: for file_name, file in self.context['files'].items(): email.attach( file_name, open(file, 'rb').read(), ) if 'object' in self.context and isinstance(self.context['object'], OnlineShipment): email.attach_file(self.context['object'].file.path) if 'object' in self.context and isinstance(self.context['object'], OrderDetail): for order_item in self.context['object'].orderitem_set.filter( orderitem__isnull=True): if hasattr(order_item.product, 'product' ) and order_item.product.product.product_picture(): try: product_file = order_item.product.product.product_picture( ).open("rb") product_img = MIMEImage(product_file.read()) product_img.add_header( 'Content-ID', '<{}>'.format(order_item.product.product. product_picture().name)) email.attach(product_img) product_file.close() except: pass html_content = render_to_string(self.email_template, context=self.context) email.attach_alternative(html_content, "text/html") print("from " + email.from_email) print("Sending mail") tries += 1 self.email = email
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