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 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()
Example #3
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)
Example #4
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()
Example #5
0
    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()
Example #6
0
def send_email(to,
               subject,
               email_template,
               cc=None,
               images=None,
               context=None,
               attachments=None,
               use_bcc=False):
    to = list(to)
    if not to:
        return

    connection = get_connection()
    html_content = render_to_string(email_template, context)
    text_content = strip_tags(html_content)

    email = EmailMultiAlternatives(subject, text_content, settings.EMAIL_FROM,
                                   to, cc, connection)
    if use_bcc:
        email.to = []
        email.bcc = to
    email.attach_alternative(html_content, "text/html")

    if images:
        email.mixed_subtype = 'related'
        for i in images:
            #email.headers()
            image_name = i.split("/")[-1]
            fp = open(settings.BASE_DIR + i, 'rb')
            msg_img = MIMEImage(fp.read())
            msg_img.add_header('Content-Id', '<' + image_name + '>')
            email.attach(msg_img)
            fp.close()
    if attachments:
        for a in attachments:
            if isinstance(a, dict):
                email.attach(filename=a['filename'], content=a['file'])
            elif isinstance(a.attachment, FieldFile):
                email.attach_file(a.attachment.path)

    if settings.DEBUG:
        if settings.EMAIL_ADMIN:
            email.to = [settings.EMAIL_ADMIN]
            email.bcc = [settings.EMAIL_ADMIN]
            email.send()
        else:
            print(email.body)
    else:
        email.send()
Example #7
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
 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)
Example #9
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, '{0} <{1}>'.format(self.from_name, self.from_address)
            text_content = self.content
            
            msg = EmailMultiAlternatives(subject, text_content, from_email)
            
            if self.reply_to:
                msg.extra_headers.update({"reply-to": self.reply_to})

            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")

            msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()]
            msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                msg.attach_file(os.path.join(settings.MEDIA_ROOT, attachment.file_attachment.name))
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
def mail(request):
    url_parts = RequestGrabber(request)
    fullname = request.POST.get('fullname', '')
    contact_email = request.POST.get('email', '')
    phone = request.POST.get('phone', '')
    message = request.POST.get('message', '')

    context = {
        'fullname' : fullname,
        'email' : contact_email,
        'phone' : phone,
        'message' : message,
        'base_url': url_parts.protocol() + url_parts.domain(),
    }
    mail_template = render_to_string('portfolio/mails/base_template.html', context)

    if request.method == 'POST':
        if fullname and message and contact_email:
            try:
                validate_email(contact_email)
                try:
                    email = EmailMultiAlternatives(fullname, mail_template)
                    email.attach_alternative(mail_template, "text/html")
                    email.to = [contact_email]
                    email.send()
                except BadHeaderError:
                    return HttpResponse('Invalid header found. Please contact software developer.')
                return HttpResponse('Thank you!')
            except forms.ValidationError:
                return HttpResponse('Invalid Email Address.')
        else:
            return HttpResponse('Make sure all fields are entered and valid.')
    else:
        return HttpResponse('Invalid request!')
Example #11
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, self.from_address
            text_content = self.content

            msg = EmailMultiAlternatives(subject, text_content, from_email)

            if self.reply_to:
                msg.extra_headers.update({"reply-to": self.reply_to})

            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")

            msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()]
            msg.cc = [email.strip() for email in self.cc_address.split(',') if email.strip()]
            msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                path = attachment.file_attachment.path
                if os.path.isfile(path):
                    with open(path, 'rb') as f:
                        content = f.read()
                    msg.attach(attachment.original_filename, content, None)
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
Example #12
0
    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!")
Example #13
0
 def send(self):
     if self.is_valid():
         mail = EmailMultiAlternatives(
             subject=EMAIL_SETTINGS.get("SUBJECT", DEFAULT_SUBJECT),
             from_email=EMAIL_SETTINGS.get("FROM"),
             bcc=EMAIL_SETTINGS.get("BCC"),
             headers={"Reply-To": EMAIL_SETTINGS.get("REPLY_TO")}
         )
         mail.attach_alternative(self.get_body(), "text/html")
         if EMAIL_SETTINGS.get("ACTIVE", False):
             mail.to = [self.contributor.email]
         else:
             mail.to = EMAIL_SETTINGS.get("TO")
         mail.send()
     else:
         logger.error("""No email sent for {}""".format(self.contributor.get_full_name()))
Example #14
0
 def send_email(self):
     text_content = render_to_string('emails/contact.txt', {'data': self.cleaned_data})
     html_content = render_to_string('emails/contact.html', {'data': self.cleaned_data})
     email = EmailMultiAlternatives('Subject', text_content)
     email.attach_alternative(html_content, "text/html")
     email.to = ['*****@*****.**']
     email.send()
Example #15
0
def mobile_order(request):
    '''
    Shows order page
    '''
    if request.method == 'POST':
        orders = []
        for i in range(15):
            i = i + 1 
            if request.POST.get('active-%s' % i) == '1':
                orders.insert(0, [
                    request.POST.get('model-' + str(i)),
                    request.POST.get('color-' + str(i)),
                    request.POST.get('quantity-' + str(i)),
                    request.POST.get('size-' + str(i)),
                ])
        c = Context({
            'orders': orders,
            'username': request.user.username,
            'client': request.POST.get('name-1'),
        })
        text_content = render_to_string('mail/order_from_mobile.txt', c)
        html_content = render_to_string('mail/order_from_mobile.html', c)
        email = EmailMultiAlternatives(settings.SUBJECT, text_content)
        email.attach_alternative(html_content, "text/html")
        email.to = [SiteConfiguration.objects.all().first().email_to_notifications]
        email.send()
        return render(request, "mobile_order_sent.html")
    return render(request, "mobile_order.html", {
        'loop': [i+1 for i in range(16)]
    })
Example #16
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)
Example #17
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)
Example #18
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)
Example #19
0
def registration_view(request):
    user = request.data['username']
    string2 = 'W0' + ''.join(choice(digits) for i in range(7))
    randomstring = string2
    serializer = RegistrationSerializer(data=request.data)
    data = {}
    if serializer.is_valid():
        unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
        now_aware = unaware.replace(tzinfo=pytz.UTC)
        account = serializer.save()
        account.username = randomstring
        account.is_active = False
        account.tz = now_aware
        account.save()
        # EMAIL VERIFICATION
        current_site = get_current_site(request)
        html_content = render_to_string(
            'acc_active_email.html', {
                'user': account,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(account.pk)),
                'token': account_activation_token.make_token(account),
            })
        email = EmailMultiAlternatives('Confirm your Artomate Account')
        email.attach_alternative(html_content, "text/html")
        email.to = [request.data['email']]
        email.send()
        data['response'] = 'successfully registered new user and ' \
                           'Please confirm your email address to complete the registration '
        data['status'] = 100

    else:
        data = serializer.errors
    return Response(data)
 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()
Example #21
0
def send_mail_worker(self, host, campaign, sector, campaign_log):
    # Build cache key to show progress
    cache_key = 'progress-campaign:{}'.format(campaign_log.id)
    body = campaign.html_mail.read()
    connection = get_connection()

    messages = []
    for email in sector.email_set.all():
        # Build message
        msg = EmailMultiAlternatives(
            subject=campaign.title,
            body='',
            from_email=u"{from_name} <{from_email}>".format(from_name=campaign.from_name,
                                                            from_email=campaign.from_email),
        )

        # Optional Mandrill-specific extensions:
        msg.tags = campaign.get_tags()
        msg.async = True
        msg.track_opens = True
        msg.track_clicks = True
        msg.to = [email.address]
        msg.attach_alternative(attach_remove_link(host, body, email), "text/html")
        messages.append(msg)

    # Send mass emails
    connection.send_messages(messages, cache_key)

    # Change status
    campaign_log.is_sent = True
    campaign_log.save()
    cache.delete(cache_key)
Example #22
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, self.from_address
            text_content = self.content
            msg = EmailMultiAlternatives(subject, text_content, from_email)
            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")

            msg.to = [
                email.strip() for email in self.to_address.split(',')
                if email.strip()
            ]
            msg.bcc = [
                email.strip() for email in self.bcc_address.split(',')
                if email.strip()
            ]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                msg.attach_file(
                    os.path.join(settings.MEDIA_ROOT,
                                 attachment.file_attachment.name))
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
Example #23
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, self.from_address
            text_content = self.content

            msg = EmailMultiAlternatives(subject, text_content, from_email)

            if self.reply_to:
                msg.reply_to = [email.strip() for email in self.reply_to.split(',')
                                if email.strip()]

            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")

            msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()]
            msg.cc = [email.strip() for email in self.cc_address.split(',') if email.strip()]
            msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                path = attachment.file_attachment.path
                if os.path.isfile(path):
                    with open(path, 'rb') as f:
                        content = f.read()
                    msg.attach(attachment.original_filename, content, None)
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
Example #24
0
 def send(self):
     if self.is_valid():
         mail = EmailMultiAlternatives(
             subject=EMAIL_SETTINGS.get("SUBJECT", DEFAULT_SUBJECT),
             from_email=EMAIL_SETTINGS.get("FROM"),
             bcc=EMAIL_SETTINGS.get("BCC"),
             headers={"Reply-To": EMAIL_SETTINGS.get("REPLY_TO")})
         mail.attach_alternative(self.get_body(), "text/html")
         if EMAIL_SETTINGS.get("ACTIVE", False):
             mail.to = [self.contributor.email]
         else:
             mail.to = EMAIL_SETTINGS.get("TO")
         mail.send()
     else:
         logger.error("""No email sent for {}""".format(
             self.contributor.get_full_name()))
Example #25
0
    def send_activation_mail(self, request, form, user):
        # Envoi du mail à l'utilisateur avec le token
        mail_subject = _(
            'Activation du compte A.X.E.L. pour l\'utilisateur {0}').format(
                user)
        from_email = settings.EMAIL_HOST_USER
        to_email = user.email
        current_site = get_current_site(request)
        uid = urlsafe_base64_encode(force_bytes(user.pk))
        token = account_activation_token.make_token(user)
        activation_link = "{0}/activate/{1}/{2}".format(
            current_site, uid, token)
        params = {
            'user': user,
            'domain': current_site.domain,
            'uid': uid,
            'token': token,
            'activation_link': activation_link,
        }
        html_message = render_to_string('WebAXEL/mail/activation_mail.html',
                                        params)
        text_message = render_to_string('WebAXEL/mail/activation_mail.txt',
                                        params)

        msg = EmailMultiAlternatives(mail_subject, text_message, from_email)
        msg.attach_alternative(html_message, "text/html")
        msg.to = [to_email]
        msg.send()
        messages.success(request, _("Lien d'activation envoyé par mail"))
Example #26
0
def newsletter_unsubscribe(request):
    back = request.META.get('HTTP_REFERER')
    form_unsubscribe = NewsletterSignUpForm(request.POST or None)
    if request.method == 'POST' and 'unsubscribe' in request.POST:
        if form_unsubscribe.is_valid():
            instance = form_unsubscribe.save(commit=False)
            if NewsletterUser.objects.filter(email=instance.email).exists():
                NewsletterUser.objects.filter(email=instance.email).delete()
                messages.success(
                    request,
                    "Successfully unsubscribed. You will no longer get email for new deal from Teenkanya",
                    "alert alert-warning alert-dismissible")
                text_content = render_to_string(
                    'pages/newsletters/unsubscribe_email.txt')
                html_content = render_to_string(
                    'pages/newsletters/unsubscribe_email.html')
                email = EmailMultiAlternatives("Newsletter Unsubscription",
                                               text_content)
                email.attach_alternative(html_content, "text/html")
                email.to = [instance.email]
                email.send()
                return redirect(back)
            else:
                messages.error(request, "No Email Found",
                               "alert alert-warning alert-dismissible")
                return redirect(back)
    else:
        context = {
            'form_unsubscribe': form_unsubscribe,
            'title': "Newsletter Unsubscribe",
        }

        template = "pages/newsletters/unsubscribe.html"
        return render(request, template, context)
Example #27
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()
Example #28
0
 def send_email(self):
     text_content = render_to_string("emails/contact.txt", {"data": self.cleaned_data})
     html_content = render_to_string("emails/contact.html", {"data": self.cleaned_data})
     email = EmailMultiAlternatives("Subject", text_content)
     email.attach_alternative(html_content, "text/html")
     email.to = ["*****@*****.**"]
     email.send()
Example #29
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
Example #30
0
File: mail.py Project: La0/coach
  def build(self, context, headers=None):

    # Activate language
    translation.activate(self.language)

    # Render template
    site = get_current_site(None)
    message = u'Envoyé via %s' % site
    context.update({
      'site' : site,
    })
    mail_html = render_to_string(self.template, context)
    if settings.DEBUG:
      self.dump(mail_html)

    # Configure mail
    mail = EmailMultiAlternatives(self.subject, message, headers=headers)
    mail.to = self.to
    mail.cc = self.cc

    # Attach the rendered html
    mail.attach_alternative(mail_html, 'text/html')

    # Do not send, it's responsability of caller
    return mail
Example #31
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)
Example #32
0
    def build(self, context, headers=None):

        # Activate language
        translation.activate(self.language)

        # Render template
        site = get_current_site(None)
        message = u'Envoyé via %s' % site
        context.update({
            'site': site,
        })
        mail_html = render_to_string(self.template, context)
        if settings.DEBUG:
            self.dump(mail_html)

        # Configure mail
        mail = EmailMultiAlternatives(self.subject, message, headers=headers)
        mail.to = self.to
        mail.cc = self.cc

        # Attach the rendered html
        mail.attach_alternative(mail_html, 'text/html')

        # Do not send, it's responsability of caller
        return mail
Example #33
0
def email_send(template_name, context, mail_subject, to_email):
    mail_subject = mail_subject
    html_content = render_to_string(template_name, context)

    email = EmailMultiAlternatives(mail_subject, "")
    email.attach_alternative(html_content, "text/html")
    email.to = to_email
    email.send()
Example #34
0
 def send_email(self, **data):
     html_content = render_to_string(
         'genopedia/home/reset_passwrod_mail_template.html', data['params'])
     email = EmailMultiAlternatives(data['subject'],
                                    settings.EMAIL_HOST_USER)
     email.attach_alternative(html_content, "text/html")
     email.to = data['recievers']
     email.send()
Example #35
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, self.from_address
            text_content = self.content
            msg = EmailMultiAlternatives(subject, text_content, from_email)

            if getattr(settings, "EMAIL_TEST_MODE", None):
                msg.to = settings.MAIL_ADMINS
            else:
                msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()]
                msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                filename = os.path.join(settings.MEDIA_ROOT, attachment.file_attachment.name)
                if attachment.inline_content_id:
                    try:
                        with open(filename, 'rb') as fo:
                            to_attach = MIMEImage(fo.read())
                    except TypeError:
                        # invalid image, skip
                        continue

                    to_attach.add_header('Content-ID', '<%s>' % attachment.inline_content_id)
                    msg.attach(to_attach)
                    msg.mixed_subtype = 'related'

                elif attachment.name:
                    with open(filename, 'rb') as fo:
                        msg.attach(attachment.name, fo.read())
                else:
                    msg.attach_file(filename)

            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
Example #36
0
 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)
Example #37
0
 def send_email(self, email_to='*****@*****.**'):
     text_content = render_to_string('emails/contact.txt',
                                     {'data': self.cleaned_data})
     html_content = render_to_string('emails/contact.html',
                                     {'data': self.cleaned_data})
     email = EmailMultiAlternatives('Subject', text_content)
     email.attach_alternative(html_content, "text/html")
     email.to = [email_to]
     email.send()
Example #38
0
def send_email(con, subject, email_to, email_from):
    c = Context(con)
    text_content = render_to_string('mail/user_register_welcome.txt', c)
    html_content = render_to_string('mail/user_register_welcome.html', c)

    email = EmailMultiAlternatives(subject, text_content, email_from)
    email.attach_alternative(html_content, "text/html")
    email.to = [email_to]
    email.send()
Example #39
0
def mail(request,receiver,subject,body):
    c = Context({'username': settings.EMAIL_HOST_USER })    
    text_content = render_to_string(subject, c)
    html_content = render_to_string(body, c)

    email = EmailMultiAlternatives('Subject', text_content)
    email.attach_alternative(html_content, "text/html")
    email.to = [receiver]
    email.send()
Example #40
0
def mail(request, receiver, subject, body):
    c = Context({'username': settings.EMAIL_HOST_USER})
    text_content = render_to_string(subject, c)
    html_content = render_to_string(body, c)

    email = EmailMultiAlternatives('Subject', text_content)
    email.attach_alternative(html_content, "text/html")
    email.to = [receiver]
    email.send()
Example #41
0
def newsletter_signup(request):
    form = NewsletterSignUpForm(request.POST or None)
    back = request.META.get('HTTP_REFERER')
    if form.is_valid():
        if request.method == 'POST' and 'subscribe' in request.POST:
            instance = form.save(commit=False)
            if NewsletterUser.objects.filter(email=instance.email).exists():
                messages.warning(request, instance.email+ ' already exist. Please enter new email address',
                                 "alert alert-warning alert-dismissible")
                form = NewsletterSignUpForm()
            else:
                instance.save()
                messages.success(request, "Successfully Subscribed. You will receive email from Teenkanya at "+ instance.email, "alert alert-success alert-dismissible")
                text_content = render_to_string('pages/newsletters/sign_up_email.txt')
                html_content = render_to_string('pages/newsletters/sign_up_email.html')
                email = EmailMultiAlternatives("Newsletter Subscription", text_content)
                email.attach_alternative(html_content, "text/html")
                email.to = [instance.email]
                email.send()
                form = NewsletterSignUpForm()

        elif request.method == 'POST' and 'unsubscribe' in request.POST:
            instance = form.save(commit=False)
            if NewsletterUser.objects.filter(email=instance.email).exists():
                NewsletterUser.objects.filter(email=instance.email).delete()
                messages.success(request,
                                 "Successfully unsubscribed. You will no longer get email from Teenkanya",
                                 "alert alert-warning alert-dismissible")
                text_content = render_to_string('pages/newsletters/unsubscribe_email.txt')
                html_content = render_to_string('pages/newsletters/unsubscribe_email.html')
                email = EmailMultiAlternatives("Newsletter Unsubscription", text_content)
                email.attach_alternative(html_content, "text/html")
                email.to = [instance.email]
                email.send()
                form = NewsletterSignUpForm()
            else:
                messages.error(request, instance.email+ " has not subscribed for Newsletter" ,
                               "alert alert-warning alert-dismissible")
                form = NewsletterSignUpForm()

    context = {
        'form': form
    }
    return context
 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)
Example #43
0
def mail(request):
    c = Context({'username': settings.EMAIL_HOST_USER })    
    text_content = render_to_string('mail/email.txt', c)
    html_content = render_to_string('mail/fancy-1-2-3.html', c)

    email = EmailMultiAlternatives('Subject', text_content)
    email.attach_alternative(html_content, "text/html")
    email.to = ['*****@*****.**']
    email.send()
    return HttpResponse("SUCCESS")
Example #44
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)
Example #45
0
 def form_valid(self, form):
     text_content = render_to_string('emails/contact.txt',
                                     {'data': form.data})
     html_content = render_to_string('emails/contact.html',
                                     {'data': form.data})
     email = EmailMultiAlternatives('Subject', text_content)
     email.attach_alternative(html_content, "text/html")
     email.to = ['*****@*****.**']
     email.send()
     form.save()
     return JsonResponse({'text': 'Consulta enviada', 'sent': True})
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
Example #47
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
Example #48
0
    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)
Example #49
0
def send_byline_email(content, removed_bylines):
    context = {
        "content": content,
        "bylines": removed_bylines,
        "contributions": content.contributions.all()
    }
    body = loader.render_to_string("reporting/__byline_report.html", context)
    mail = EmailMultiAlternatives(
        subject="Byline modified for article, {}".format(content.title.encode("ascii", "ignore")),
        from_email=EMAIL_SETTINGS.get("FROM"),
    )
    mail.attach_alternative(body, "text/html")
    mail.to = EMAIL_SETTINGS.get("BYLINE_RECIPIENTS", [])
    mail.send()
Example #50
0
def send_inactive_user_mail(user):
    c = Context({'user': user})
    template_name = 'mails/new_inactive_user'

    t = loader.get_template(template_name + '.txt')
    text_content = t.render(c)
    t = loader.get_template(template_name + '.html')
    html_content = t.render(c)

    msg = EmailMultiAlternatives('Nieuwe inactieve gebruiker', text_content)
    msg.to = [admin[1] for admin in settings.ADMINS]  # email addresses
    msg.attach_alternative(html_content, "text/html")
    msg.send()
    return
Example #51
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}))
Example #52
0
    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
Example #53
0
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
Example #54
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__()
Example #55
0
def send_callbackee_emails(request):
	try:
		if request.session['netid'] is None:
			return check_login(request, '/site_admin')
	
		netid = request.session['netid']
	except:
		return check_login(request, '/site_admin')
	admin = Admin.objects.filter(net_id=netid, site_admin=True)
	if len(admin) is 0:
		print admin
		#no callbackee with this name
		return render_to_response("group_admin_error.html")
	admin = admin[0]
	#zip together callbackee with every group they got called back to
	all_callbackees = []
	their_callbacks = []
	#emails_sent
	for callbackee in Callbackee.objects.filter(email_sent=False):
		all_callbackees.append(callbackee)
		current_callbacks = Callbacks.objects.filter(callbackee=callbackee)
		their_callbacks.append(current_callbacks)
	zipped = zip(all_callbackees, their_callbacks)
	# c = Context({'callbackee': existing_callbackee, 'group': Group.objects.get(name=datadict['group'])})    
	# html_content = render_to_string('email_for_callbackee.html', c)

	# email = EmailMultiAlternatives('yo', '')
	# email.attach_alternative(html_content, "text/html")
	# email.to = ['*****@*****.**']
	# email.send()
	for callbackee, callbacks in zipped:
		c = Context({'callbackee': callbackee, 'callbacks': callbacks})    
		html_content = render_to_string('email_for_callbackee.html', c)

		email = EmailMultiAlternatives('Callbacks from Acaprez', '')
		email.attach_alternative(html_content, "text/html")
		email_address = ''
		email_address += callbackee.net_id
		email_address += '@princeton.edu'
		email.to = [email_address]
		email.send()
		callbackee.email_sent = True
		callbackee.save()
	return HttpResponseRedirect('/site_admin')
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
Example #57
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)
Example #58
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)
Example #59
0
    def send(self, request, queryset):
        """
        Action to send the current newsletter to all registered users
        """
        num_sent_emails = 0
        connection = get_connection()

        for obj in queryset:
            messages = []
            body = obj.html_file.read().decode('utf-8')
            msg = EmailMultiAlternatives(subject=obj.subject,
                                         body='',
                                         from_email=u"{from_name} <{from_email}>".format(from_name=obj.from_name,
                                                                                         from_email=obj.from_address))
            msg.attach_alternative(body, "text/html")
            for obj in get_register_model().objects.all():
                msg.to = obj.email
                messages.append(msg)

            num_sent_emails += connection.send_messages(messages)

        return num_sent_emails