Beispiel #1
0
    def post(self,request,*args,**kwargs):
        error = None
        success = None

        form = CustomerRegistrationForm(request.POST)
        #password = request.POST['password']
        #email = request.POST['email']

        if form.is_valid():

            #form = CustomerRegistrationForm()


            #Send verification code to user to activate account



            try:
                data = form.cleaned_data
                password = data['password']
                email = data['email']

                user = form.save(commit=False)
                user.set_password(password)
                user.save()
                email = email.strip()
                user = Customer.objects.get_verify_code(email)

                context = {'user': user, 'SITE_NAME': settings.SITE_NAME, 'DOMAIN': settings.DOMAIN}
                print(context)
                msg_subject = 'Activate Account'
                text_content = render_to_string("accounts/email/email_signup_confirm.txt",context)
                to_email = '%s <%s>' % (user.get_full_name(),user)
                html_content = render_to_string('accounts/email/email_signup_confirm.html', context)
                msg = EmailMultiAlternatives(msg_subject, text_content)
                msg.attach_alternative(html_content, "text/html")

                msg.from_email = '*****@*****.**'
                msg.to = [to_email]

                # Send a notification copy to admin
                text_content2 = render_to_string("accounts/email/admin_notify.txt",context)
                html_content2 = render_to_string('accounts/email/admin_notify.html', context)
                msg_copy = EmailMultiAlternatives("New Customer Registration", text_content2)
                msg_copy.attach_alternative(html_content2, "text/html")
                msg_copy.to = ['*****@*****.**']
                msg_copy.from_email = '*****@*****.**'

                msg.send()
                msg_copy.send()


                return HttpResponseRedirect('/accounts/register_complete/')

            except ValidationError as e:
                error = e.message


        return super(RegisterView,self).get(request,form=form,success=success,error=error)
    def send_order_confirmation(self, order_number, total, lineitems,
                                customer):
        """Sends email to user confirming order and contents"""
        items = []
        for mydict in lineitems:
            product_id = CustomerPrice.objects.get(id=mydict['product_id'])
            items.append({
                'product': product_id.product,
                'price': mydict['price'],
                'quantity': mydict['quantity'],
                'sub_total': mydict['line_total']
            })

        context = {
            'user': customer.last_name,
            'order_items': items,
            'order_number': order_number,
            'total': total,
            #'order_status':order_status,
            'MEDIA_URL': settings.MEDIA_URL,
            'SITE_URL': settings.SITE_URL
        }

        subject = 'Thanks for your purchase at Gaea! Order ' + str(
            order_number)
        from_email = 'Sales gaeafoods <*****@*****.**>'

        # If at order screen, user provided an email address

        to = customer

        text_content = render_to_string('orders/email/order_confirmation.txt',
                                        context)
        html_content = render_to_string('orders/email/order_confirmation.html',
                                        context)
        msg = EmailMultiAlternatives(subject, text_content)
        msg.attach_alternative(html_content, "text/html")
        msg.to = [to]
        msg.from_email = from_email

        # Send a copy to me after finished as well
        msg_copy = EmailMultiAlternatives(
            "#Order " + str(order_number) + '--' + str(customer.company),
            text_content)
        msg_copy.attach_alternative(html_content, "text/html")
        msg_copy.to = ['*****@*****.**']
        msg_copy.from_email = from_email

        msg.send()
        msg_copy.send()
Beispiel #3
0
def add_bounce_sender_global(sender, message: EmailMultiAlternatives, order,
                             user, customer, **kwargs):
    if not settings.CONFIG_FILE.has_section('bounces') or order:
        return message

    from_domain = settings.CONFIG_FILE.get('bounces',
                                           'from_domain',
                                           fallback='')
    if from_domain and '@' + from_domain not in message.from_email:
        return message

    if user:
        alias = generate_new_user_alias(user)
    elif customer:
        alias = generate_new_customer_alias(customer)
    else:
        return message
    from_email = message.from_email

    if 'Reply-To' not in message.extra_headers:
        message.extra_headers['Reply-To'] = from_email

    message.from_email = alias
    message.extra_headers.update({'From': from_email, 'Sender': alias})
    return message
Beispiel #4
0
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
Beispiel #5
0
    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
Beispiel #6
0
def send_mail(self: MonitoredTask,
              message: dict[Any, Any],
              email_stage_pk: Optional[int] = None):
    """Send Email for Email Stage. Retries are scheduled automatically."""
    self.save_on_success = False
    message_id = make_msgid(domain=DNS_NAME)
    self.set_uid(slugify(message_id.replace(".", "_").replace("@", "_")))
    try:
        if not email_stage_pk:
            stage: EmailStage = EmailStage(use_global_settings=True)
        else:
            stage: EmailStage = EmailStage.objects.get(pk=email_stage_pk)
        backend = stage.backend
        backend.open()
        # Since django's EmailMessage objects are not JSON serialisable,
        # we need to rebuild them from a dict
        message_object = EmailMultiAlternatives()
        for key, value in message.items():
            setattr(message_object, key, value)
        if not stage.use_global_settings:
            message_object.from_email = stage.from_address
        # Because we use the Message-ID as UID for the task, manually assign it
        message_object.extra_headers["Message-ID"] = message_id

        LOGGER.debug("Sending mail", to=message_object.to)
        stage.backend.send_messages([message_object])
        self.set_status(
            TaskResult(
                TaskResultStatus.SUCCESSFUL,
                messages=["Successfully sent Mail."],
            ))
    except (SMTPException, ConnectionError) as exc:
        LOGGER.debug("Error sending email, retrying...", exc=exc)
        self.set_status(TaskResult(TaskResultStatus.ERROR).with_error(exc))
        raise exc
Beispiel #7
0
    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)
Beispiel #8
0
def send_email(to, subject, message_text, message_html=None, sender=settings.DEFAULT_FROM_EMAIL):
    email = EmailMultiAlternatives(subject, message_text)
    if message_html:
        email.attach_alternative(message_html, "text/html")
    email.to = [to]
    email.from_email = sender
    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 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()
Beispiel #11
0
    def post(self, request):
        error = None
        success = None
        email = request.POST.get('email', None)

        if email:
            email = email.strip()
            try:
                user = Customer.objects.get_reset_code(email)

                # Sending password reset link email to user

                context = {'user': user, 'SITE_NAME': settings.SITE_NAME, 'DOMAIN': settings.DOMAIN}
                msg_subject = 'Password Reset'
                text_content = render_to_string("accounts/email/password_reset_subject.txt",context)
                to_email = '%s <%s>' % (user.get_full_name(),user)
                html_content = render_to_string('accounts/email/password_reset.html', context)
                msg = EmailMultiAlternatives(msg_subject, text_content)
                msg.attach_alternative(html_content, "text/html")

                msg.from_email = '*****@*****.**'
                msg.to = [to_email]

                msg.send()

                success = 'Password reset intructions has been sent to your email address.'
            except Exception as e:
                error = e.message
        else:
            error = 'Please provide an email address'

        return self.get(request, error=error, success=success)
Beispiel #12
0
    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)
Beispiel #13
0
    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)
Beispiel #14
0
def async_send_mail(title, message, alert_id, sender_id):
    from hub.models import Alert, Log
    Log.objects.create(
        type='n',
        tag="async_send_mail",
        message='Sending email. Title: "%s" Text: "%s" Alert: %d Sender: %d' %
        (title, message, alert_id, sender_id))
    alert = Alert.objects.filter(id=alert_id)
    if alert:
        alert = alert.first()
    else:
        return False

    html = render_to_string('mails/alert_template.html', {'message': message})
    email = EmailMultiAlternatives(title, html, to=[SERVICE_EMAIL])
    email.attach_alternative(html, "text/html")
    email.from_email = BOX_EMAIL
    # send_mail(title, html, BOX_EMAIL, [SERVICE_EMAIL])
    email.send()
    alert.email_timestamp = datetime.now()
    alert.email_sender_id = sender_id
    alert.email_sent = True
    alert.save()
    Log.objects.create(type='n',
                       tag="async_send_mail",
                       message='Sent successfully')
    return True
Beispiel #15
0
def send_mail(self: MonitoredTask, message: dict[Any, Any], email_stage_pk: Optional[int] = None):
    """Send Email for Email Stage. Retries are scheduled automatically."""
    self.save_on_success = False
    message_id = make_msgid(domain=DNS_NAME)
    self.set_uid(slugify(message_id.replace(".", "_").replace("@", "_")))
    try:
        if not email_stage_pk:
            stage: EmailStage = EmailStage(use_global_settings=True)
        else:
            stages = EmailStage.objects.filter(pk=email_stage_pk)
            if not stages.exists():
                self.set_status(
                    TaskResult(
                        TaskResultStatus.WARNING,
                        messages=["Email stage does not exist anymore. Discarding message."],
                    )
                )
                return
            stage: EmailStage = stages.first()
        try:
            backend = stage.backend
        except ValueError as exc:
            # pyright: reportGeneralTypeIssues=false
            LOGGER.warning(exc)
            self.set_status(TaskResult(TaskResultStatus.ERROR).with_error(exc))
            return
        backend.open()
        # Since django's EmailMessage objects are not JSON serialisable,
        # we need to rebuild them from a dict
        message_object = EmailMultiAlternatives()
        for key, value in message.items():
            setattr(message_object, key, value)
        if not stage.use_global_settings:
            message_object.from_email = stage.from_address
        # Because we use the Message-ID as UID for the task, manually assign it
        message_object.extra_headers["Message-ID"] = message_id

        LOGGER.debug("Sending mail", to=message_object.to)
        backend.send_messages([message_object])
        Event.new(
            EventAction.EMAIL_SENT,
            message=(f"Email to {', '.join(message_object.to)} sent"),
            subject=message_object.subject,
            body=get_email_body(message_object),
            from_email=message_object.from_email,
            to_email=message_object.to,
        ).save()
        self.set_status(
            TaskResult(
                TaskResultStatus.SUCCESSFUL,
                messages=["Successfully sent Mail."],
            )
        )
    except (SMTPException, ConnectionError, OSError) as exc:
        LOGGER.debug("Error sending email, retrying...", exc=exc)
        self.set_status(TaskResult(TaskResultStatus.ERROR).with_error(exc))
        raise exc
Beispiel #16
0
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)
Beispiel #17
0
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
Beispiel #18
0
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
Beispiel #20
0
    def send_order_confirmation(self, request, order_email):
        """Sends email to user confirming order and contents"""

        user = self.profile.user

        context = Context({
            'user': user,
            'cart': self.cart,
            'MEDIA_URL': settings.MEDIA_URL,
            'SITE_URL': settings.SITE_URL
        })

        subject = 'Thanks for the biz! Here\'s your order confirmation.'
        from_email = 'Sean Dominguez <*****@*****.**>'

        # If at order screen, user provided an email address
        if order_email != '':
            to = order_email
        else:
            to = self.profile.user.email

        text_content = render_to_string('orders/email/order_confirmation.txt',
                                        context)
        html_content = render_to_string('orders/email/order_confirmation.html',
                                        context)
        msg = EmailMultiAlternatives(subject, text_content)
        msg.attach_alternative(html_content, "text/html")
        msg.to = [to]
        msg.from_email = from_email

        # Send a copy to me after finished as well
        msg_copy = EmailMultiAlternatives("Copy of order confirmation",
                                          text_content)
        msg_copy.attach_alternative(html_content, "text/html")
        msg_copy.to = ['*****@*****.**']
        msg_copy.from_email = from_email

        msg.send()
        msg_copy.send()
Beispiel #21
0
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}))
Beispiel #22
0
    def form_valid(self, form):
        # Create a user, but remember to set inactive!
        user = User()
        user.username = form.cleaned_data['email']
        user.email = form.cleaned_data['email']
        user.is_active = False
        try:
            user.save()
        except IntegrityError:
            form.add_error('email',
                           gettext('Shop with this email already exists.'))
            return super(ShopRegisterView, self).form_invalid(form)

        self.object = form.save(commit=False)
        self.object.postcode = Postcode.objects.get(
            postcode=form.cleaned_data['postcode_special'])
        self.object.user = user
        self.object.save()

        current_site = get_current_site(self.request)
        context = {
            'shopname': self.object.name,
            'user': user,
            'domain': current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': account_activation_token.make_token(user),
        }

        html_message = render_to_string('emails/account_activation.html',
                                        context)
        txt_message = render_to_string('emails/account_activation.txt',
                                       context)

        email = EmailMultiAlternatives(gettext('FOODBEE - Confirm email'),
                                       txt_message)
        email.from_email = settings.DEFAULT_FROM_EMAIL
        email.to = [self.object.email]
        email.attach_alternative(html_message, "text/html")
        email.content_subtype = 'html'
        email.mixed_subtype = 'related'

        with open('base/static/base/img/fb_logo.png', mode='rb') as f:
            image = MIMEImage(f.read())
            image.add_header('Content-ID', "<Foodbee_logo_long.png>")
            email.attach(image)

        email.send()

        return super().form_valid(form)
Beispiel #23
0
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
Beispiel #25
0
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 message(self):
        m = EmailMultiAlternatives(self.subject, self.body)
        m.to = self.to
        m.cc = self.cc
        m.bcc = self.bcc
        m.from_email = self.from_email

        m.alternatives = \
            [(att.content, att.mimetype) for att in self.alternatives()]
        for attachment in self.attachments():
            m.attach(attachment.filename, attachment.content.read(),
                     attachment.mimetype)

        m.extra_headers = self.extra_headers

        return m
Beispiel #27
0
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 _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
Beispiel #29
0
    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)
Beispiel #30
0
 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()
Beispiel #31
0
    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)
Beispiel #32
0
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()
Beispiel #33
0
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__()
Beispiel #34
0
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__()
Beispiel #35
0
    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)
Beispiel #36
0
def add_bounce_sender(sender, message: EmailMultiAlternatives, order,
                      **kwargs):
    if not settings.CONFIG_FILE.has_section('bounces') or not order:
        return message

    if order.event.settings.smtp_use_custom:
        return message

    from_domain = settings.CONFIG_FILE.get('bounces',
                                           'from_domain',
                                           fallback='')
    if from_domain and '@' + from_domain not in message.from_email:
        return message

    alias = generate_new_alias(order)
    from_email = message.from_email

    if 'Reply-To' not in message.extra_headers:
        message.extra_headers['Reply-To'] = from_email

    message.from_email = alias
    message.extra_headers.update({'From': from_email, 'Sender': alias})

    return message
Beispiel #37
0
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!"
Beispiel #38
0
    def enviar_cotizacion(self, cotizacion, user, email_adicional=None):
        version_cotizacion = cotizacion.version

        from_ventas_email = EmailConfiguration.objects.first(
        ).email_ventas_from
        if not from_ventas_email:
            from_ventas_email = settings.DEFAULT_FROM_EMAIL

        enviar_como = user.user_extendido.email_envio_como
        if enviar_como:
            enviar_como = '%s - %s' % (user.user_extendido.email_envio_como,
                                       user.get_full_name())
        else:
            enviar_como = 'ODECOPACK - %s' % (user.get_full_name())

        if user.email:
            email_split = user.email.split('@')
            if email_split[-1] in list(
                    DominiosEmail.objects.values_list('dominio',
                                                      flat=True).all()):
                from_email = "%s <%s>" % (enviar_como, user.email)
            else:
                from_email = "%s <%s>" % (enviar_como, from_ventas_email)
        else:
            from_email = "%s <%s>" % (enviar_como, from_ventas_email)
        if email_adicional:
            to = [cotizacion.email, email_adicional]
        else:
            to = [cotizacion.email]
        subject = "%s - %s" % ('Cotizacion', cotizacion.nro_cotizacion)
        if version_cotizacion > 1:
            subject = "%s, version %s" % (subject, cotizacion.version)

        ctx = {
            'object': cotizacion,
        }

        try:
            colaborador = Colaborador.objects.get(usuario__user=user)
        except Colaborador.DoesNotExist:
            colaborador = None

        if not cotizacion.cliente_nuevo:
            colaboradores = SucursalBiable.objects.values(
                'vendedor_real__colaborador_id').filter(
                    cliente_id=cotizacion.cliente_biable_id,
                    vendedor_real__isnull=False).distinct()
            if colaboradores.exists():
                if colaboradores.count() == 1:
                    colaborador = Colaborador.objects.get(
                        pk=colaboradores.first()
                        ['vendedor_real__colaborador_id'])
                    cotizacion.usuario = colaborador.usuario.user

                    cotizacion.save()
            else:
                colaborador = Colaborador.objects.get(usuario__user=user)

        if colaborador:
            if colaborador.foto_perfil:
                url_avatar = colaborador.foto_perfil.url
                ctx['avatar'] = url_avatar

        nombre_archivo_cotizacion = "Cotizacion Odecopack - CB %s.pdf" % (
            cotizacion.id)
        if version_cotizacion > 1:
            ctx['version'] = cotizacion.version
            nombre_archivo_cotizacion = "Cotizacion Odecopack - CB %s ver %s.pdf" % (
                cotizacion.id, cotizacion.version)

        text_content = render_to_string('cotizaciones/emails/cotizacion.html',
                                        ctx)

        html_content = get_template(
            'cotizaciones/emails/cotizacion.html').render(Context(ctx))

        output = BytesIO()
        HTML(string=html_content).write_pdf(target=output)
        msg = EmailMultiAlternatives(subject,
                                     text_content,
                                     from_email,
                                     to=to,
                                     reply_to=[user.email])
        msg.attach_alternative(html_content, "text/html")

        msg.attach(nombre_archivo_cotizacion, output.getvalue(),
                   'application/pdf')

        if cotizacion.mis_imagenes:
            for imagen in cotizacion.mis_imagenes.all():
                try:
                    docfile = imagen.imagen.read()
                    if docfile:
                        nombre_archivo = imagen.imagen.name.split("/")[-1]
                        msg.attach(nombre_archivo, docfile)
                        docfile.close()
                    else:
                        pass
                except:
                    pass

        msg.send()

        # Envio al asesor
        msg.from_email = "Confirmación <*****@*****.**>"
        msg.to = [user.email]
        msg.reply_to = None
        msg.send()

        output.close()
        cotizacion.save()

        if not cotizacion.cliente_nuevo:
            seguimiento = SeguimientoComercialCliente()
            seguimiento.cotizacion = cotizacion
            seguimiento.creado_por = self.request.user
            seguimiento.cliente = cotizacion.cliente_biable

            observacion_adicional = "<p> Valor Cotización: " + str(
                cotizacion.total) + "</p>"
            if cotizacion.descuento:
                observacion_adicional += "<p> Descuento Cotización: " + str(
                    cotizacion.descuento) + "</p>"

            seguimiento.observacion_adicional = observacion_adicional
            if version_cotizacion > 1:
                seguimiento.tipo_accion = "Envío version " + str(
                    version_cotizacion)
            else:
                seguimiento.tipo_accion = "Nueva"
            seguimiento.save()
Beispiel #39
0
    def form_valid(self, form):
        self.object = form.save()

        # Fetch all products
        basket = self.request.session.get('basket', [])
        products_in_basket = [item.get('product') for item in basket]
        products = Product.objects.filter(pk__in=products_in_basket,
                                          active=True,
                                          shop__active=True).order_by('shop')
        products_dict = {product.pk: product for product in products}

        # Total cost & valid items list per shop
        shop_items_and_cost = dict.fromkeys(
            {product.shop
             for product in products})
        for key in shop_items_and_cost:
            shop_items_and_cost[key] = {
                'total_cost': Decimal(0.00),
                'order_items': [],
                'item_count': 0
            }

        # Create orderItems
        for item in basket:
            product = products_dict[item.get('product')]
            count = item.get('count')
            # If product is not found, skip product
            if product is None:
                continue

            # If count is 0 or below, skip item
            if count < 1:
                continue

            order_item = OrderItem()
            order_item.product = product
            order_item.order = self.object
            order_item.count = count
            # Save the offer/on sale price if any, else use normal price
            order_item.price = product.offer_price if product.offer_price else product.price
            order_item.save()

            shop_items_and_cost[product.shop]['item_count'] += count
            shop_items_and_cost[product.shop]['total_cost'] += Decimal(
                order_item.subtotal())
            shop_items_and_cost[product.shop]['order_items'].append(order_item)

        context = {
            'order': self.object,
            'shop_items_and_cost': shop_items_and_cost
        }
        html_message = render_to_string('emails/order_confirmation.html',
                                        context)
        txt_message = render_to_string('emails/order_confirmation.txt',
                                       context)
        subject = gettext('Order confirmation')

        self.object.status = Order.ORDERED

        email = EmailMultiAlternatives(subject, txt_message)
        email.from_email = settings.DEFAULT_FROM_EMAIL
        email.to = [self.object.email]
        email.attach_alternative(html_message, "text/html")
        email.content_subtype = 'html'
        email.mixed_subtype = 'related'

        with open('base/static/base/img/fb_logo.png', mode='rb') as f:
            image = MIMEImage(f.read())
            image.add_header('Content-ID', "<Foodbee_logo_long.png>")
            email.attach(image)

        email.send()

        # Clear session
        self.request.session.flush()
        return HttpResponseRedirect(self.get_success_url())
Beispiel #40
0
    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 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
Beispiel #43
0
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