Esempio n. 1
0
    def send_html_mail_from_email_template(cls,
                                           template_name,
                                           recipient_list,
                                           attachments=None,
                                           cached_template_obj=None,
                                           **kwargs):

        for attr_name in ('language_code', 'context_data', 'from_email',
                          'priority', 'fail_silently', 'auth_user',
                          'auth_password', 'headers', 'message'):
            kwargs[attr_name] = kwargs.get(
                attr_name, getattr(cls, 'default_%s' % attr_name))

        context = Context(kwargs['context_data'])
        email_template = cls.get_email_template_object(template_name,
                                                       cached_template_obj)

        html_template = cls.before_render(email_template,
                                          kwargs['language_code'])
        html_message = Template(html_template).render(context).encode('utf-8')
        html_message = cls.after_render(html_message)

        kwargs['subject'] = getattr(email_template,
                                    'subject_%s' % kwargs['language_code'])
        kwargs['message_html'] = html_message
        kwargs['recipient_list'] = recipient_list
        kwargs['attachments'] = attachments

        del kwargs['context_data']
        del kwargs['language_code']

        send_html_mail(**kwargs)
        return True
Esempio n. 2
0
def send_email(request):
    "Send an E-mail to users"
    if not request.user.is_admin:
        return redirect('home')

    if request.POST:
        subject = request.POST.get('subject')
        message = request.POST.get('message')
        #print(render_to_string('email/invite.txt', {'domain': settings.DOMAIN, 'token': token, 'subject': subject}))
        msg_plain = render_to_string('email/announce.txt', {'message': message, 'subject': subject})
        msg_html = render_to_string('email/announce.html', {'message': message, 'subject': subject})

        # right now, this is just to send messages to all of the users
        users = WhatTheUser.objects.filter(email__isnull=False)
        recipients = [u.email for u in users]
        for u in users:
            send_html_mail(subject, msg_plain, msg_html, settings.DEFAULT_FROM_EMAIL, [u.email, ])
        
        return redirect('admin-dashboard')

        #try:
        #send_html_mail(subject, msg_plain, msg_html, settings.DEFAULT_FROM_EMAIL, recipients)
        #finally:
        #    return redirect('admin-dashboard')

    return render_to_response("send_email.html", 
        RequestContext(request, {})
    )
Esempio n. 3
0
def record_payment(request):
    userprofile_object = UserProfile.objects.get(user=request.user)
    if request.method == 'POST':
        payment_form = PartialBillForm(request.POST)
        lender = UserProfile.objects.get(user__email=request.POST['lender'])
        borrower = UserFriend.objects.get(user_profile=lender, friend_email=userprofile_object.user.email)
        bill_value = 0
        if payment_form.is_valid():
            if request.POST['overall_bill_id'] != '000': 
                bill_detail = BillDetails.objects.get(bill__overall_bill_id=request.POST['overall_bill_id'], borrower=borrower)
                bill_detail.bill_cleared='Y'
                bill_detail.save()
                bill_description = bill_detail.bill.description
            else:
                bill_details = BillDetails.objects.filter(bill__lender=lender, borrower=borrower)
                for bill_detail in bill_details:
                    bill_detail.bill_cleared='Y'
                    bill_detail.save()
                    bill_value += bill_detail.individual_amount
                bill_description = 'All Bills (Total: SGD ' + str(bill_value) + ')'
            # Send Email Start
            context = Context({ 'userprofile_object': userprofile_object, 'description': bill_description })
            subject = 'New Payment by: ' + userprofile_object.user.first_name + ' ' + userprofile_object.user.last_name
            payment_creation_txt_content = payment_creation_txt.render(context)
            payment_creation_html_content = payment_creation_html.render(context)
            send_html_mail(subject, payment_creation_txt_content, payment_creation_html_content, settings.DEFAULT_FROM_EMAIL, [ lender.user.email ])
            # Send Email End

            return HttpResponseRedirect('/who-i-owe/')
    else:
        return HttpResponseRedirect('/record-payment/')
Esempio n. 4
0
    def test_send_html(self):
        with self.settings(MAILER_EMAIL_BACKEND=
                           "django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_html_mail("Subject",
                                  "Body",
                                  "<html><body>Body</body></html>",
                                  "*****@*****.**",
                                  ["*****@*****.**"],
                                  priority=PRIORITY_HIGH)

            # Ensure deferred was not deleted
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            self.assertEqual(len(mail.outbox), 1)
            sent = mail.outbox[0]

            # Default "plain text"
            self.assertEqual(sent.body, "Body")
            self.assertEqual(sent.content_subtype, "plain")

            # Alternative "text/html"
            self.assertEqual(sent.alternatives[0],
                             ("<html><body>Body</body></html>", "text/html"))
Esempio n. 5
0
def sendmail_task(current_mail_id):
    """
    Task to send Mail
    """
    logger.info("TASK :: sendmail_task")

    current_mailspooler = MailSpooler.objects.get(id=current_mail_id)

    if current_mailspooler.mailspooler_type != MAILSPOOLER_TYPE.IN_PROCESS:
        logger.info(
            "ERROR :: Trying to send mail which is not set as IN_PROCESS")
        return False

    mailtemplate = MailTemplate.objects.get(
        pk=current_mailspooler.mailtemplate.id)
    #contact_email = current_mailspooler.contact.email

    send_html_mail(
        mailtemplate.subject,
        mailtemplate.message_plaintext,
        mailtemplate.message_html,
        mailtemplate.from_email,
        [current_mailspooler.contact_email],
    )

    current_mailspooler.mailspooler_type = MAILSPOOLER_TYPE.SENT
    current_mailspooler.save()

    logger.info("Mail Sent - ID:%d" % current_mailspooler.id)
def flag_handler(flagged_instance, flagged_content, **kw):
    from django.conf import settings  # circular deps
    target = flagged_content.content_object
    # Does this need to be our custom user?
    has_email = Profile.objects.exclude(email='').exclude(email__isnull=True)
    q = Q(is_superuser=True)
    if flagged_instance.flag_type == 'inappropriate':
        q = q | Q(groups__name='content_moderator')
    if flagged_instance.flag_type == 'broken':
        q = q | Q(groups__name='dev_moderator')
    recps = has_email.filter(q)
    if recps.count() == 0:
        # What do we do here?
        # _logger.warning('No recipients for flag')
        return
    link = settings.SITEURL + 'admin/flag/flaginstance/%s' % flagged_instance.pk
    message = loader.render_to_string("flag/email.txt", {
        'flag': flagged_instance,
        'url': link,
        'display': '%s[%s]' % (target._meta.object_name, target.id)
    })
    send_html_mail("[MapStory] Notification",
                   message=message,
                   message_html=message,
                   from_email="*****@*****.**",
                   recipient_list=[u.email for u in recps])
Esempio n. 7
0
def send_email(request, extra_context, subject_template, body_template,
               from_email, recipients, priority="medium"):
    """
    Sends an email based on templates for subject and body.

    :param request: The current request instance.
    :param extra_context: A dictionary of items that should be added to the
        templates' contexts.
    :param subject_template: A string representing the path to the template of
        of the email's subject.
    :param body_template: A string representing the path to the template of
        the email's body.
    :param from_email: String that represents the sender of the email.
    :param recipients: A list of tuples of recipients. The tuples are similar
        to the ADMINS setting.

    """
    if request:
        context = RequestContext(request, extra_context)
    else:
        context = extra_context
    subject = render_to_string(subject_template, context)
    subject = ''.join(subject.splitlines())
    message_html = render_to_string(body_template, context)
    message_plaintext = html_to_plain_text(message_html)
    send_html_mail(subject, message_plaintext, message_html, from_email,
                   recipients, priority=priority)
Esempio n. 8
0
def _send_mail_to_user(user, subject, templateName, contextData):
    if (user.getUserInfo() and user.getUserInfo().receiveAllEmail):
        template = get_template(templateName)
        context = Context(contextData)
        html_content = template.render(context)
        send_html_mail(subject, html_content, html_content,
                       settings.DEFAULT_FROM_EMAIL, [user.email])
Esempio n. 9
0
    def put(self, request, picture_id, *args, **kwargs):
        picture = MultiuploaderImage.objects.get(id=picture_id)
        picture.is_inappropriate = True
        picture.save()

        #email to admin
        user = request.user
        email_body = render_to_string(
            'emails/picture_report_email.html', {
                'user': user,
                'title': 'Picture report',
                'site_name': settings.SITE_NAME,
                'domain': request.build_absolute_uri(reverse('index')),
                'picture_id': picture_id
            })

        manager_emails = [t[1] for t in settings.MANAGERS]

        if "mailer" in settings.INSTALLED_APPS:
            send_html_mail("Picture report", email_body, email_body,
                           settings.DEFAULT_FROM_EMAIL, manager_emails)
        else:
            send_mail("Picture report", email_body,
                      settings.DEFAULT_FROM_EMAIL, manager_emails)

        return Response({}, status=status.HTTP_200_OK)
Esempio n. 10
0
def send_email(request, extra_context, subject_template, body_template_plain,
               body_template, from_email, recipients):
    """
    Sends an email based on templates for subject and body.

    :param request: The current request instance.
    :param extra_context: A dictionary of items that should be added to the
        templates' contexts.
    :param subject_template: A string representing the path to the template of
        of the email's subject.
    :param body_template: A string representing the path to the template of
        the email's body.
    :param from_email: String that represents the sender of the email.
    :param recipients: A list of tuples of recipients. The tuples are similar
        to the ADMINS setting.

    """
    if request:
        context = RequestContext(request, extra_context)
    else:
        context = extra_context
    subject = render_to_string(subject_template, context)
    subject = ''.join(subject.splitlines())
    message_plaintext = render_to_string(body_template_plain, context)
    message_html = render_to_string(body_template, context)
    send_html_mail(subject, message_plaintext, message_html, from_email,
                   recipients)
Esempio n. 11
0
def send_email_template(template_key, target_user, ctxt):
    """
    Send email via mail backend
    """
    try:
        mailtemplate = MailTemplate.objects.get(template_key=template_key)
    except:
        #No Mail Template
        return False

    message_plaintext = mailtemplate.message_plaintext
    message_html = mailtemplate.message_html

    # Replace tags
    for ctag in ctxt:
        mtag = '%' + ctag + '%'
        vtag = ctxt[ctag]
        message_plaintext = message_plaintext.replace(mtag, vtag.encode('utf-8'))
        message_html = message_html.replace(mtag, vtag.encode('utf-8'))

    send_html_mail(
        mailtemplate.subject,
        message_plaintext,
        message_html,
        mailtemplate.from_email,
        [target_user.email],
        headers={'From': '%s <%s>' % (mailtemplate.from_name, mailtemplate.from_email)},
    )
Esempio n. 12
0
    def send_html_mail_from_email_template(self, template_name, recipient_list, attachments=None,
                                           cached_template_obj=None, **kwargs):

        for attr_name in ('language_code', 'context_data', 'from_email', 'priority', 'fail_silently', 'auth_user',
                          'auth_password', 'headers', 'message'):
            kwargs[attr_name] = kwargs.get(attr_name, getattr(self, 'default_%s' % attr_name))

        context = Context(kwargs['context_data'])
        email_template = self.get_email_template_object(template_name, cached_template_obj)

        subject_template = self.subject_before_render(email_template, kwargs['language_code'])
        subject = Template(subject_template).render(context).encode('utf-8')
        subject = self.subject_after_render(subject)

        html_template = self.before_render(email_template, kwargs['language_code'])
        html_message = Template(html_template).render(context).encode('utf-8')
        html_message = self.after_render(html_message)

        kwargs['subject'] = subject
        kwargs['message_html'] = html_message
        kwargs['recipient_list'] = recipient_list
        kwargs['attachments'] = attachments

        del kwargs['context_data']
        del kwargs['language_code']

        self.before_sent(**kwargs)
        send_html_mail(**kwargs)
        self.after_sent(**kwargs)
        return True
Esempio n. 13
0
def sendmail_task(current_mail_id):
    """
    Task to send Mail
    """
    logger.info("TASK :: sendmail_task")

    current_mailspooler = MailSpooler.objects.get(id=current_mail_id)

    if current_mailspooler.mailspooler_type != MAILSPOOLER_TYPE.IN_PROCESS:
        logger.info("ERROR :: Trying to send mail which is not set as IN_PROCESS")
        return False

    mailtemplate = MailTemplate.objects.get(pk=current_mailspooler.mailtemplate.id)
    #contact_email = current_mailspooler.contact.email

    send_html_mail(
        mailtemplate.subject,
        mailtemplate.message_plaintext,
        mailtemplate.message_html,
        mailtemplate.from_email,
        [current_mailspooler.contact_email],
    )

    current_mailspooler.mailspooler_type = MAILSPOOLER_TYPE.SENT
    current_mailspooler.save()

    logger.info("Mail Sent - ID:%d" % current_mailspooler.id)
Esempio n. 14
0
def send_email_template(template_key, target_user, ctxt):
    """
    Send email via mail backend
    """
    try:
        mailtemplate = MailTemplate.objects.get(template_key=template_key)
    except:
        #No Mail Template
        return False

    message_plaintext = mailtemplate.message_plaintext
    message_html = mailtemplate.message_html

    # Replace tags
    for ctag in ctxt:
        mtag = '%' + ctag + '%'
        vtag = ctxt[ctag]
        message_plaintext = message_plaintext.replace(mtag,
                                                      vtag.encode('utf-8'))
        message_html = message_html.replace(mtag, vtag.encode('utf-8'))

    send_html_mail(
        mailtemplate.subject,
        message_plaintext,
        message_html,
        mailtemplate.from_email,
        [target_user.email],
        headers={
            'From':
            '%s <%s>' % (mailtemplate.from_name, mailtemplate.from_email)
        },
    )
Esempio n. 15
0
def flag_handler(flagged_instance, flagged_content, **kw):
    from django.conf import settings  # circular deps
    target = flagged_content.content_object
    has_email = User.objects.exclude(email='').exclude(email__isnull=True)
    q = Q(is_superuser=True)
    if flagged_instance.flag_type == 'inappropriate':
        q = q | Q(groups__name='content_moderator')
    if flagged_instance.flag_type == 'broken':
        q = q | Q(groups__name='dev_moderator')
    recps = has_email.filter(q)
    if recps.count() == 0:
        _logger.warning('No recipients for flag')
        return
    link = settings.SITEURL + 'admin/flag/flaginstance/%s' % flagged_instance.pk
    message = loader.render_to_string(
        "flag/email.txt", {
            'flag': flagged_instance,
            'url': link,
            'display': '%s[%s]' % (target._meta.object_name, target.id)
        })
    send_html_mail("[MapStory] Notification",
                   message=message,
                   message_html=message,
                   from_email="*****@*****.**",
                   recipient_list=[u.email for u in recps])
Esempio n. 16
0
def SendAllUser(subject, message):
    """
    send html email for all users
    """
    for user in User.objects.all().values_list('email', flat = True):
        send_html_mail('[RS] ' + subject,message ,message, settings.EMAIL_HOST_USER,
        [user])
Esempio n. 17
0
def new_users_handler(sender, user, response, details, **kwargs):
    user.is_new = True

    # Start - Send Email
    context = Context({})
    subject, to = "Welcome to BridgeBill", user.email
    account_creation_txt_content = account_creation_txt.render(context)
    account_creation_html_content = account_creation_html.render(context)
    send_html_mail(
        subject, account_creation_txt_content, account_creation_html_content, settings.DEFAULT_FROM_EMAIL, [to]
    )
    # End - Send Email

    # Start - Add User as his own friend
    userprofile_id = create_userprofile_id()
    user_profile = UserProfile(userprofile_id=userprofile_id, user=user)
    user_profile.save()

    userfriend_id = create_userfriend_id()
    user_own_friend = UserFriend(
        userfriend_id=userfriend_id,
        user_profile=user_profile,
        friend_email=user.email,
        friend_name=user.first_name + " " + user.last_name,
    )
    user_own_friend.save()
    # End - Add User as his own friend

    return False
    def handle(self, **options):
        """ Send Report E-mails """ 

        from django.conf import settings
        translation.activate(settings.LANGUAGE_CODE)

        backend = get_backend() 

        # This command is a NOOP if using the Mixpanel backend 
        if backend == 'app_metrics.backends.mixpanel': 
            print "Useless use of metrics_send_email when using Mixpanel backend."
            return 

        # Determine if we should also send any weekly or monthly reports 
        today = datetime.date.today() 
        if today.weekday == 0: 
            send_weekly = True
        else: 
            send_weekly = False 

        if today.day == 1: 
            send_monthly = True 
        else: 
            send_monthly = False 

        qs = MetricSet.objects.filter(Q(no_email=False), Q(send_daily=True) | Q(send_monthly=send_monthly) | Q(send_weekly=send_weekly))

        if "mailer" in settings.INSTALLED_APPS: 
            from mailer import send_html_mail 
            USE_MAILER = True 
        else: 
            from django.core.mail import EmailMultiAlternatives
            USE_MAILER = False 

        for s in qs: 
            subject = _("%s Report") % s.name 

            recipient_list = s.email_recipients.values_list('email', flat=True)
            
            (message, message_html) = generate_report(s, html=True)

            if message == None:
                continue

            if USE_MAILER: 
                send_html_mail(subject=subject, 
                               message=message, 
                               message_html=message_html, 
                               from_email=settings.DEFAULT_FROM_EMAIL, 
                               recipient_list=recipient_list)
            else: 
                msg = EmailMultiAlternatives(subject=subject,
                                             body=message,
                                             from_email=settings.DEFAULT_FROM_EMAIL,
                                             to=recipient_list)
                msg.attach_alternative(message_html, "text/html")
                msg.send()

        translation.deactivate()
Esempio n. 19
0
def notify_responsible_adult(msg):
    """Send an email to some responsible adult(s)"""
    adults = getattr(settings, 'RESPONSIBLE_ADULTS', None)
    if adults:
        from_email = getattr(settings, 'DEFAULT_FROM_EMAIL',
                             '*****@*****.**')
        send_html_mail(_('Open Knesset requires attention'), msg, msg,
                       from_email, adults)
Esempio n. 20
0
def send_mail(msg_parts, user):
    """
    Queue mail to the user.
    """
    (course, text_body, html_body) = msg_parts
    email = user.user.email
    if email:
        send_html_mail(course, text_body, html_body, MASS_MAIL_FROM, [email])
Esempio n. 21
0
    def handle(self, **options): 
        """ Send Report E-mails """ 

        translation.activate(settings.LANGUAGE_CODE)

        backend = get_backend() 

        # This command is a NOOP if using the Mixpanel backend 
        if backend == 'app_metrics.backends.mixpanel': 
            print("Useless use of metrics_send_email when using Mixpanel backend.")
            return 

        # Determine if we should also send any weekly or monthly reports 
        today = datetime.date.today() 
        if today.weekday == 0: 
            send_weekly = True
        else: 
            send_weekly = False 

        if today.day == 1: 
            send_monthly = True 
        else: 
            send_monthly = False 

        qs = MetricSet.objects.filter(Q(no_email=False), Q(send_daily=True) | Q(send_monthly=send_monthly) | Q(send_weekly=send_weekly))

        if "mailer" in settings.INSTALLED_APPS: 
            from mailer import send_html_mail 
            USE_MAILER = True 
        else: 
            from django.core.mail import EmailMultiAlternatives
            USE_MAILER = False 

        for s in qs: 
            subject = _("%s Report") % s.name 

            recipient_list = s.email_recipients.values_list('email', flat=True)
            
            (message, message_html) = generate_report(s, html=True)

            if message is None:
                continue

            if USE_MAILER:
                send_html_mail(subject=subject,
                               message=message, 
                               message_html=message_html, 
                               from_email=settings.DEFAULT_FROM_EMAIL, 
                               recipient_list=recipient_list)
            else:
                msg = EmailMultiAlternatives(subject=subject,
                                             body=message,
                                             from_email=settings.DEFAULT_FROM_EMAIL,
                                             to=recipient_list)
                msg.attach_alternative(message_html, "text/html")
                msg.send()

        translation.deactivate()
Esempio n. 22
0
    def handle_noargs(self, **options):

        daily = options.get('daily', False)
        weekly = options.get('weekly', False)
        if not daily and not weekly:
            print "use --daily or --weekly"
            return

        translation.activate(self.lang)

        email_notification = []
        if daily:
            email_notification.append('D')
        if weekly:
            email_notification.append('W')

        queued = 0
        g = Group.objects.get(name='Valid Email')
        for user in User.objects.all():
            try:
                user_profile = user.get_profile()
            except UserProfile.DoesNotExist:
                logger.warn('user %s has no userprofile' % user.username)
                continue

            if user_profile and user_profile.email_notification in email_notification and g in user.groups.all(
            ):
                # if this user has a profile (should always be true)
                # requested emails in the frequency we are handling now
                # and has validated his email
                email_body, email_body_html = self.get_email_for_user(user)
                if email_body:  # there are some updates. generate email
                    header = render_to_string(('notify/header.txt'),
                                              {'user': user})
                    footer = render_to_string(('notify/footer.txt'), {
                        'user': user,
                        'domain': self.domain
                    })
                    header_html = render_to_string(('notify/header.html'),
                                                   {'user': user})
                    footer_html = render_to_string(('notify/footer.html'), {
                        'user': user,
                        'domain': self.domain
                    })
                    send_html_mail(
                        _('Open Knesset Updates'),
                        "%s\n%s\n%s" % (header, '\n'.join(email_body), footer),
                        "%s\n%s\n%s" %
                        (header_html, ''.join(email_body_html), footer_html),
                        self.from_email,
                        [user.email],
                    )
                    queued += 1

        print "%d email notifications queued for sending" % queued

        translation.deactivate()
Esempio n. 23
0
    def handle_noargs(self, **options):

        daily = options.get('daily', False)
        weekly = options.get('weekly', False)
        if not daily and not weekly:
            print "use --daily or --weekly"
            return

        translation.activate(self.lang)

        email_notification = []
        if daily:
            email_notification.append('D')
        if weekly:
            email_notification.append('W')

        queued = 0
        g = Group.objects.get(name='Valid Email')
        for user in User.objects.filter(groups=g,
                                        profiles__isnull=False)\
                                .exclude(email=''):
            try:
                user_profile = user.get_profile()
            except UserProfile.DoesNotExist:
                logger.warn('can\'t access user %d userprofile' % user.id)
                continue
            if (user_profile.email_notification in email_notification):
                # if this user has requested emails in the frequency we are
                # handling now
                email_body, email_body_html = self.get_email_for_user(user)
                if email_body:  # there are some updates. generate email
                    header = render_to_string(('notify/header.txt'),
                                              {'user': user})
                    footer = render_to_string(('notify/footer.txt'), {
                        'user': user,
                        'domain': self.domain
                    })
                    header_html = render_to_string(('notify/header.html'),
                                                   {'user': user})
                    footer_html = render_to_string(('notify/footer.html'), {
                        'user': user,
                        'domain': self.domain
                    })
                    send_html_mail(
                        _('Open Knesset Updates'),
                        "%s\n%s\n%s" % (header, '\n'.join(email_body), footer),
                        "%s\n%s\n%s" %
                        (header_html, ''.join(email_body_html), footer_html),
                        self.from_email,
                        [user.email],
                    )
                    queued += 1

        logger.info("%d email notifications queued for sending" % queued)

        translation.deactivate()
Esempio n. 24
0
def batch_notification(days=1):
    for u in User.objects.filter(useractivity__notification_preference='S'):
        day_ago = datetime.datetime.now() - datetime.timedelta(days=days)
        actions = u.useractivity.other_actor_actions.filter(timestamp_gte=day_ago)
        if not actions: continue
        send_html_mail("[MapStory] Daily Summary Notification",
                       message=activity_summary(actions, plain_text=True),
                       message_html=activity_summary(actions),
                       from_email="*****@*****.**", 
                       recipient_list=[user.email])
 def handle(self, *args, **options):
     nl = Newsletter.objects.active()
     ss = Subscription.objects.filter(subscribed=True)
     for n in nl:
         for s in ss:
             if n.content_html:
                 send_html_mail(n.name, n.content, n.content_html, from_email, [s.email])
             else:
                 send_mail(n.name, n.content, from_email, [s.email])
         n.sent = True
         n.save()
Esempio n. 26
0
def batch_notification(days=1):
    for u in User.objects.filter(useractivity__notification_preference='S'):
        day_ago = datetime.datetime.now() - datetime.timedelta(days=days)
        actions = u.useractivity.other_actor_actions.filter(timestamp__gte=day_ago)
        if not actions: continue
        _logger.info('sending %d notifications to %s', len(actions), u)
        send_html_mail("[MapStory] Daily Summary Notification",
                       message=activity_summary(actions, plain_text=True),
                       message_html=activity_summary(actions),
                       from_email="*****@*****.**", 
                       recipient_list=[u.email])
Esempio n. 27
0
def notify_handler(sender, instance, action, model, pk_set, **kwargs):
    if action != 'post_add': return
    if instance.notification_preference != 'E':
        return
    assert len(pk_set) == 1
    real_action = getattr(model,'objects').get(id=iter(pk_set).next())
    send_html_mail("[MapStory] Notification", 
                   message=mapstory_tags.activity_item(real_action, plain_text=True),
                   message_html=mapstory_tags.activity_item(real_action),
                   from_email="*****@*****.**", 
                   recipient_list=[instance.user.email])
Esempio n. 28
0
def send_mail(subject, from_email, recipients, message_html):
    if "mailer" in settings.INSTALLED_APPS:
        from mailer import send_html_mail
        send_html_mail(subject=subject, message=strip_tags(message_html), message_html=message_html, from_email=from_email, recipient_list=recipients)
    else:
        from django.core.mail import EmailMultiAlternatives

        msg = EmailMultiAlternatives(subject, strip_tags(message_html), from_email, recipients)
        msg.attach_alternative(message_html, "text/html")
        msg.content_subtype = "html"
        msg.send()
Esempio n. 29
0
    def test_send_html_mail(self):
        "mailer.send_html_mail: Test the HTML mail sender."
        
        # Test sending in DEBUG mode - should go into OUTBOX.
        send_html_mail("subject", "plain", "html", "*****@*****.**", ["*****@*****.**"])
        self.assertEquals(len(mail.outbox), 1)

        # Test sending without DEBUG - should create a mail instance.
        settings.DEBUG = False
        send_html_mail("subject", "plain", "html", "*****@*****.**", ["*****@*****.**"])
        Message.objects.get(from_address="*****@*****.**")
Esempio n. 30
0
def notify_handler(sender, instance, action, model, pk_set, **kwargs):
    if action != 'post_add': return
    if instance.notification_preference != 'E':
        return
    assert len(pk_set) == 1
    real_action = getattr(model,'objects').get(id=iter(pk_set).next())
    send_html_mail("[MapStory] Notification", 
                   message=mapstory_tags.activity_item(real_action, plain_text=True),
                   message_html=mapstory_tags.activity_item(real_action),
                   from_email="*****@*****.**", 
                   recipient_list=[instance.user.email])
Esempio n. 31
0
    def test_html_messages(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_html_mail('sub', 'body', '<strong>body</strong>',
                                  '*****@*****.**', ['*****@*****.**'], queue=0)
            q = Queue.objects.get(pk=0)
            self.assertEqual(Message.objects.filter(queue=q).count(), 1)

            q = Queue.objects.create(name='test', mail_enabled=True)
            mailer.send_html_mail('sub', 'body', '<strong>body</strong>',
                                  '*****@*****.**', ['*****@*****.**'], queue=1)
            self.assertEqual(Message.objects.filter(queue=q).count(), 1)
            self.assertEqual(Message.objects.count(), 2)
Esempio n. 32
0
    def _send_mail(self, body, body_html=None, header=None):

        if body_html:
            mail_header = header or dict()
            send_html_mail(self.subject, body, body_html, self.auth_user,
                           self.recipient_list, self.priority,
                           self.fail_silently, self.auth_user,
                           self.auth_password, mail_header)
        else:
            send_mail(self.subject, body, self.auth_user, self.recipient_list,
                      self.priority, self.fail_silently, self.auth_user,
                      self.auth_password)
Esempio n. 33
0
    def save(self):
        super(Notification, self).save()

        if self.is_sent:
            return

        if hasattr(self, 'send_by_mailer') and self.send_by_mailer:
            try:
                send_html_mail(self.subject, self.body, self.html_body, self.sent_from, self.recipients.split(','))
            except Exception, e:
                # log this error
                print str(e)
Esempio n. 34
0
def send_user_welcome(user):
    from django.conf import settings # circular deps
    WELCOME_EMAIL_TXT = loader.get_template('account/email/welcome_message.txt')
    WELCOME_EMAIL_HTML = loader.get_template('account/email/welcome_message.html')
    site_prefix = settings.SITEURL
    if site_prefix[-1] == '/': site_prefix = site_prefix[:-1]
    c = Context({'user': user, 'site_prefix': site_prefix})
    _logger.info('sending welcome message to %s', user.email)
    send_html_mail("[MapStory] Welcome To MapStory!",
                   message=WELCOME_EMAIL_TXT.render(c),
                   message_html=WELCOME_EMAIL_HTML.render(c),
                   from_email="*****@*****.**",
                   recipient_list=[user.email])
Esempio n. 35
0
def send_invite_email(recipient, invite_design, ctx={}):
    context = Context(ctx)

    subject_tmpl = Template(invite_design.subject)
    body_tmpl = Template(invite_design.html)

    recipient_list = []
    recipient_list.append(recipient)
    context.update({recipient: recipient})

    send_html_mail(subject_tmpl.render(context), 'text message',
                   body_tmpl.render(context), settings.DEFAULT_FROM_EMAIL,
                   recipient_list)
Esempio n. 36
0
def send_mass_html_mail(emails, *args, **kwargs):
    """
    Sends emails with html alternative if email item has html content.
    Email item is a tuple with an optionnal html message version :
        (subject, text_msg, sender, recipient, [html_msg])
    """
    for email in emails:
        subject, text_msg, sender, recipient = email[0:4]
        html_msg = email[4] if len(email) > 4 else ''
        if html_msg:
            send_html_mail(subject, text_msg, html_msg, sender, recipient, *args, **kwargs)
        else:
            send_mail(subject, text_msg, sender, recipient, *args, **kwargs)
Esempio n. 37
0
def send_letter(subject, template_name, context, email):
    template_html = render_to_string('emails/' + template_name, context)
    if not type(email) is list:
        email = [email]

    send_html_mail(
        subject,
        template_html,
        template_html,
        DEFAULT_FROM_EMAIL,
        email,
        # message_html=template_html,
    )
Esempio n. 38
0
def send_mass_html_mail(emails, *args, **kwargs):
    """
    Sends emails with html alternative if email item has html content.
    Email item is a tuple with an optionnal html message version :
        (subject, text_msg, sender, recipient, [html_msg])
    """
    for email in emails:
        subject, text_msg, sender, recipient = email[0:4]
        html_msg = email[4] if len(email) > 4 else ''
        if html_msg:
            send_html_mail(subject, text_msg, html_msg, sender, recipient, *args, **kwargs)
        else:
            send_mail(subject, text_msg, sender, recipient, *args, **kwargs)
Esempio n. 39
0
def auto_update_response_time(sender, instance, **kwargs):
	"""
	auto update the response_timestamp field if the status changes to 3 or 4
	- sends user email as a result

	# check if current status is 3 or 4
	# if current status is 3 or 4 - don't do anything
	# if current status is 1 or 2 and the update_field is to update it to 3 or 4
		#  then update response_timestamp
		#  send user email about update
	"""
	try:
		current_app = Application.objects.filter(id=instance.id)
		if current_app.count() > 0:
			# update of application status
			current_app = current_app[0]
			if (current_app.status == 1 or current_app.status == 2) and (instance.status == 3 or instance.status == 4):
				# update response_time
				instance.response_timestamp = datetime.datetime.now()
				# send user email that he got rejected/called for interview
				template_html = 'emails/new_notification.html'
				template_text = 'emails/new_notification.txt'

				subject = "[Occuhunt] "+current_app.company.name+" Application Update"
				from_email = '*****@*****.**'
				recruiter_email = instance.recruiter_email
				recruiter_message = instance.recruiter_message
				to_email = current_app.user.email

				text_content = render_to_string(template_text, {'name':current_app.user.first_name+' '+current_app.user.last_name, 'company':current_app.company.name, 'old_status':current_app.status, 'updated_status':instance.status, 'recruiter_message':recruiter_message})
				html_content = render_to_string(template_html, {'name':current_app.user.first_name+' '+current_app.user.last_name, 'company':current_app.company.name, 'old_status':current_app.status, 'updated_status':instance.status, 'recruiter_message':recruiter_message})

				if recruiter_email:
					send_html_mail(subject, text_content, html_content, from_email, [to_email, recruiter_email])
				else:
					send_html_mail(subject, text_content, html_content, from_email, [to_email])
		else:
			# new application from offrhunt
			if instance.added_by_offrhunt:
				instance.response_timestamp = datetime.datetime.now()
				# send user email that he got rejected/called for interview
				template_html = 'emails/new_notification.html'
				template_text = 'emails/new_notification.txt'

				subject = "[Occuhunt] "+instance.company.name+" Application Update"
				from_email = '*****@*****.**'
				recruiter_email = instance.recruiter_email
				recruiter_message = instance.recruiter_message
				to_email = instance.user.email

				text_content = render_to_string(template_text, {'name':instance.user.first_name+' '+instance.user.last_name, 'company':instance.company.name, 'old_status':instance.status, 'updated_status':instance.status, 'recruiter_message':recruiter_message})
				html_content = render_to_string(template_html, {'name':instance.user.first_name+' '+instance.user.last_name, 'company':instance.company.name, 'old_status':instance.status, 'updated_status':instance.status, 'recruiter_message':recruiter_message})

				if recruiter_email:
					send_html_mail(subject, text_content, html_content, from_email, [to_email, recruiter_email])
				else:
					send_html_mail(subject, text_content, html_content, from_email, [to_email])
	except Exception, e:
		print e
Esempio n. 40
0
def send(
    subject: str,
    html_body: str,
    recipients: Iterable[str],
    reason: str,
    priority: int = PRIORITY_MEDIUM
) -> None:
    """Send an e-mail, using the django-mailer queue."""
    html_part, text_part = _make_payload(html_body, reason)
    subject = f'[PyWeek] {subject.strip()}'

    #TODO: identify sending user rather than using default
    from_email = settings.DEFAULT_FROM_EMAIL
    for recip in recipients:
        if isinstance(recip, EmailAddress):
            to_email = f'"{recip.user.username}" <{recip.address}>'
            token_key = recip.user.username
        else:
            token_key = to_email = recip

        token = UNSUBSCRIBE_SIGNER.sign(rot13(token_key))

        to_email = clean_header(to_email)
        subject = clean_header(subject.strip())

        # FIXME: substituting a token into the generated output is not
        # infallible, but this might be a lot faster than re-rendering a
        # template for each user, which matters when sending to 1000+ users.
        user_html = html_part.replace(TOKEN_KEY, token)
        user_text = text_part.replace(TOKEN_KEY, token)

        if priority == PRIORITY_IMMEDIATE:
            django.core.mail.send_mail(
                subject=subject,
                message=user_text,
                html_message=user_html,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[to_email],
                fail_silently=False,
            )
        else:
            mailer.send_html_mail(
                subject=subject,
                message=user_text,
                message_html=user_html,
                from_email=from_email,
                recipient_list=[to_email],
                priority=priority,
            )
Esempio n. 41
0
def render_and_send_email(subject,
                          template,
                          template_html,
                          data,
                          recipient_list,
                          from_email=MASS_MAIL_FROM):

    con = Context(data)
    tem = get_template(template)
    plaintext_body = tem.render(con)
    tem = get_template(template_html)
    html_body = tem.render(con)

    send_html_mail(subject, plaintext_body, html_body, from_email,
                   recipient_list)
Esempio n. 42
0
def send_user_welcome(user):
    from django.conf import settings  # circular deps
    WELCOME_EMAIL_TXT = loader.get_template(
        'account/email/welcome_message.txt')
    WELCOME_EMAIL_HTML = loader.get_template(
        'account/email/welcome_message.html')
    site_prefix = settings.SITEURL
    if site_prefix[-1] == '/': site_prefix = site_prefix[:-1]
    c = Context({'user': user, 'site_prefix': site_prefix})
    _logger.info('sending welcome message to %s', user.email)
    send_html_mail("[MapStory] Welcome To MapStory!",
                   message=WELCOME_EMAIL_TXT.render(c),
                   message_html=WELCOME_EMAIL_HTML.render(c),
                   from_email="*****@*****.**",
                   recipient_list=[user.email])
Esempio n. 43
0
    def handle_noargs(self, **options):

        daily = options.get('daily', False)
        weekly = options.get('weekly', False)
        if not daily and not weekly:
            print "use --daily or --weekly"
            return

        translation.activate(self.lang)

        email_notification = []
        if daily:
            email_notification.append('D')
        if weekly:
            email_notification.append('W')

        queued = 0
        g = Group.objects.get(name='Valid Email')
        for user in User.objects.all():
            try:
                user_profile = user.get_profile()
            except UserProfile.DoesNotExist:
                logger.warn('user %s has no userprofile' % user.username)
                continue

            if (user.email and
                user_profile and
                user_profile.email_notification in email_notification and
                g in user.groups.all()):
                # if this user has a profile (should always be true)
                # requested emails in the frequency we are handling now
                # and has validated his email
                email_body, email_body_html = self.get_email_for_user(user)
                if email_body: # there are some updates. generate email
                    header = render_to_string(('notify/header.txt'),{ 'user':user })
                    footer = render_to_string(('notify/footer.txt'),{ 'user':user,'domain':self.domain })
                    header_html = render_to_string(('notify/header.html'),{ 'user':user })
                    footer_html = render_to_string(('notify/footer.html'),{ 'user':user,'domain':self.domain })
                    send_html_mail(_('Open Knesset Updates'), "%s\n%s\n%s" % (header, '\n'.join(email_body), footer),
                                                              "%s\n%s\n%s" % (header_html, ''.join(email_body_html), footer_html),
                                                              self.from_email,
                                                              [user.email],
                                                              )
                    queued += 1

        print "%d email notifications queued for sending" % queued

        translation.deactivate()
Esempio n. 44
0
def send_email(to, kind, **kwargs):
    
    current_site = Site.objects.get_current()
    
    ctx = {
        "current_site": current_site,
        "STATIC_URL": settings.STATIC_URL,
    }
    ctx.update(kwargs.get("context", {}))
    subject = render_to_string("emails/%s/subject.txt" % kind, ctx).strip()
    message_html = render_to_string("emails/%s/message.html" % kind, ctx)
    message_plaintext = strip_tags(message_html)
    
    from_email = settings.DEFAULT_FROM_EMAIL
    
    send_html_mail(subject, message_plaintext, message_html, from_email, to)
Esempio n. 45
0
def send_email(to, kind, **kwargs):

    current_site = Site.objects.get_current()

    ctx = {
        "current_site": current_site,
        "STATIC_URL": settings.STATIC_URL,
    }
    ctx.update(kwargs.get("context", {}))
    subject = render_to_string("emails/%s/subject.txt" % kind, ctx).strip()
    message_html = render_to_string("emails/%s/message.html" % kind, ctx)
    message_plaintext = strip_tags(message_html)

    from_email = settings.DEFAULT_FROM_EMAIL

    send_html_mail(subject, message_plaintext, message_html, from_email, to)
Esempio n. 46
0
    def handle_noargs(self, **options):
        site = Site.objects.get_current()
        subject = "Daily Digest: %s" %( site.name)
        from_address = '%s notifications <admin@%s>' %(site.name, site.domain)
        to_address = User.objects.filter(dinetteuserprofile__is_subscribed_to_digest=True).values_list('email', flat=True)
        
        yesterday = datetime.datetime.now() - datetime.timedelta(1)
        topics = Ftopics.objects.filter(created_on__gt=yesterday)
        replies = Reply.objects.filter(updated_on__gt=yesterday)
        users = DinetteUserProfile.objects.filter(user__date_joined__gt=yesterday)
        active_users = DinetteUserProfile.objects.filter(user__last_login__gt=yesterday)

        if any([topics, replies, users, active_users]):
            variables = {'site': site, 'topics': topics, 'replies': replies, 'users': users, 'active_users': active_users}
            html_message = render_to_string('dinette/email/daily_updates.html', variables)
            send_html_mail(subject, html_message, html_message, from_address, to_address)
Esempio n. 47
0
def send_mail(subject, message=None, from_email=None, recipient_list=None, fail_silently=False, auth_user=None,
              auth_password=None, connection=None, html_message=None):
    """
    Replacement for monkey-patching Django's send_mail function for sending html email by default
    """
    if recipient_list is None:
        raise ValueError('You must specified recipient_list attribute')

    bcc_addrs = list(getattr(settings, 'EMAIL_BCC_ADDRESSES', []))
    admins = [a[1] for a in settings.ADMINS] if getattr(settings, 'EMAIL_ADMIN_DUPLICATE', False) else []
    bcc_addrs.extend(admins)
    from_email = from_email or settings.DEFAULT_FROM_EMAIL
    subject = settings.EMAIL_SUBJECT_PREFIX + subject.replace('\n', '')

    message = html_message or message

    if message.find('<html') != -1:
        message_plaintext = html2text(extract_urllinks(message))
        message_plaintext = re.sub(r'http://\n', 'http://', message_plaintext)
        if 'mailer' in settings.INSTALLED_APPS:
            from mailer import send_html_mail

            return send_html_mail(subject=subject, message=message_plaintext, message_html=message,
                                  from_email=from_email, recipient_list=recipient_list, bcc=bcc_addrs,
                                  fail_silently=fail_silently, auth_user=auth_user,
                                  auth_password=auth_password)
        else:
            email = EmailMultiAlternatives(subject=subject, body=message_plaintext, from_email=from_email,
                                           to=recipient_list, bcc=bcc_addrs, connection=connection)
            email.attach_alternative(message, "text/html")
            return email.send(fail_silently=fail_silently)

    else:
        email = EmailMessage(subject, message, from_email, recipient_list, bcc_addrs)
        email.send(fail_silently=fail_silently)
Esempio n. 48
0
def new_message_email(sender, instance, signal,
                      subject_prefix=_(u'New Message: %(subject)s'),
                      template_name="django_messages/new_message.html",
                      html_template_name="django_messages/new_message_html.html",
                      default_protocol=None,
                      *args, **kwargs):
    """
    This function sends an email and is called via Django's signal framework.
    Optional arguments:
        ``template_name``: the template to use
        ``html_template_name``: the template to use
        ``subject_prefix``: prefix for the email subject.
        ``default_protocol``: default protocol in site URL passed to template
    """
    if default_protocol is None:
        default_protocol = getattr(settings, 'DEFAULT_HTTP_PROTOCOL', 'http')

    if 'created' in kwargs and kwargs['created']:
        try:
            current_domain = Site.objects.get_current().domain
            subject = subject_prefix % {'subject': instance.subject}
            message = render_to_string(template_name, {
                'site_url': '%s://%s' % (default_protocol, current_domain),
                'message': instance,
            })
            html_message = render_to_string(html_template_name, {
                'site_url': '%s://%s' % (default_protocol, current_domain),
                'message': instance,
            })

            if instance.recipient.email != "":
                recipients = [instance.recipient.email, ]

                if django.VERSION[:2] >= (1, 7):
                    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
                              recipients, html_message=html_message)
                else:
                    if "mailer" in settings.INSTALLED_APPS:
                        send_html_mail(subject, message, html_message, settings.DEFAULT_FROM_EMAIL, recipients)
                    else:
                        msg = EmailMultiAlternatives(subject, message, settings.DEFAULT_FROM_EMAIL, recipients)
                        # html version
                        msg.attach_alternative(html_message, "text/html")
                        msg.send()
        except Exception as e:
            #print e
            pass #fail silently
Esempio n. 49
0
	def form_valid(self, form):
		instance = form.save(commit=False)
		#email = instance.email
		#fname = instance.first_name
		email = form.cleaned_data.get("email")
		fname = form.cleaned_data['name']
		if not form.cleaned_data['name']:
			fname = '-'
		instance.obj_interest_id = self.kwargs['pk']
		#phone = instance.phone_number
		instance.save()
		# list_id = 'f5a3186ffc'
		# m = get_mailchimp_api()
		# try:
		#     fields={'FNAME':fname}
		#     m.lists.members.create(list_id, { 'email_address': email, 'status': 'subscribed', 'merge_fields':fields, })
		#     try:
		#         SignUp.objects.get_or_create(email=email, first_name=fname)
		#     except Exception as e:
		#         print(e)
		# except Exception as e:
		#     print(e)
		try:
			remitente = settings.EMAIL_PLATFORM
			destinatario = [settings.EMAIL_MAIN]
			sbj = "%s -%s" %(_('New Newsletter subscriber'), project_name)
			url = "https://%s/newsletter/%s/subscriptions/" %(project_domain, str(instance.obj_interest_id))
			msg = "%s" %(_('New subscriber!'))
			msg_bye = "%s -%s" %(_('Best regards'), project_name)
			send_html_mail(sbj, msg, '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td width="10%" align="center" valign="top" style="font-family:Open Sans, Helvetica Neue, Helvetica, Helvetica, Arial, sans-serif; font-size:2px; font-weight:300; color:#294661;">.</td><td width="80%" align="center" valign="top" bgcolor="#f7f7f7"><h2> '+ msg +' </h2><h2 class="text-center">' + fname + '</h2>(<a href=' + url + '>' + url +'</a>)<h3 class="text-center" style="color:#007D8C;"><a href="mailto:'+ email + '">' + email + '</a></strong></h3><p>'+ msg_bye +'<br><br></p></td><td width="10%" align="center" valign="top" style="font-family:Arial, Helvetica, sans-serif; font-size:2px; color:#ffffff;">.</td></tr></table>', remitente, destinatario, fail_silently=False)
		except Exception as e:
			print('error here 1')
			print(e)
			pass
		try:
			remitente = settings.EMAIL_MAIN
			destinatario = [email]
			sbj = "%s -%s" %(_('Thank you for subscribing'), project_name)
			msg = "%s %s" %(fname, _('Welcome to our Newsletter!'))
			msg2 = "%s" %(_('We will keep you updated with the latest news and updates, and you will receive the exclusive discounts we have for you.'))
			#send_html_mail(sbj, msg, '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td width="10%" align="center" valign="top" style="font-family:Open Sans, Helvetica Neue, Helvetica, Helvetica, Arial, sans-serif; font-size:2px; font-weight:300; color:#294661;">.</td><td width="80%" align="center" valign="top" bgcolor="#f7f7f7"><h2>'+ msg +'</h2><h3>'+ msg2 +'</h3><br><p>' + msg_bye + '</p></td><td width="10%" align="center" valign="top" style="font-family:Arial, Helvetica, sans-serif; font-size:2px; color:#ffffff;">.</td></tr></table>', remitente, destinatario, fail_silently=False)
			#send_html_mail(sbj, msg, "' '",remitente, destinatario, fail_silently=False )
		except Exception as e:
			print('error here 2')
			print(e)
			pass
		return HttpResponseRedirect(self.success_url)
Esempio n. 50
0
File: models.py Progetto: braskin/pd
def send_invite_email(recipient, invite_design, ctx={}):
    context = Context(ctx)

    subject_tmpl = Template(invite_design.subject)
    body_tmpl = Template(invite_design.html)

    recipient_list = []
    recipient_list.append(recipient)
    context.update({recipient: recipient})

    send_html_mail(
        subject_tmpl.render(context),
        "text message",
        body_tmpl.render(context),
        settings.DEFAULT_FROM_EMAIL,
        recipient_list,
    )
Esempio n. 51
0
    def create(self,
               template,
               template_html,
               data,
               recipient_list,
               subject='Powiadomienie z Systemu Zapisów',
               from_email=settings.MASS_MAIL_FROM,
               sign=False):

        con = Context(data)
        tem = get_template(template)
        plaintext_body = tem.render(con)
        tem = get_template(template_html)
        html_body = tem.render(con)

        send_html_mail(subject, plaintext_body, html_body, from_email,
                       recipient_list)
Esempio n. 52
0
    def handle_noargs(self, **options):

        daily = options.get('daily', False)
        weekly = options.get('weekly', False)
        if not daily and not weekly:
            print "use --daily or --weekly"
            return

        translation.activate(self.lang)

        email_notification = []
        if daily:
            email_notification.append('D')
        if weekly:
            email_notification.append('W')

        queued = 0
        g = Group.objects.get(name='Valid Email')
        for user in User.objects.filter(groups=g,
                                        profiles__isnull=False)\
                                .exclude(email=''):
            try:
                user_profile = user.get_profile()
            except UserProfile.DoesNotExist:
                logger.warn('can\'t access user %d userprofile' % user.id)
                continue
            if (user_profile.email_notification in email_notification):
                # if this user has requested emails in the frequency we are
                # handling now
                email_body, email_body_html = self.get_email_for_user(user)
                if email_body: # there are some updates. generate email
                    header = render_to_string(('notify/header.txt'),{ 'user':user })
                    footer = render_to_string(('notify/footer.txt'),{ 'user':user,'domain':self.domain })
                    header_html = render_to_string(('notify/header.html'),{ 'user':user })
                    footer_html = render_to_string(('notify/footer.html'),{ 'user':user,'domain':self.domain })
                    send_html_mail(_('Open Knesset Updates'), "%s\n%s\n%s" % (header, '\n'.join(email_body), footer),
                                                              "%s\n%s\n%s" % (header_html, ''.join(email_body_html), footer_html),
                                                              self.from_email,
                                                              [user.email],
                                                              )
                    queued += 1

        logger.info("%d email notifications queued for sending" % queued)

        translation.deactivate()
Esempio n. 53
0
def specific_bill_details(request, overall_bill_id):
    userprofile_object = UserProfile.objects.get(user=request.user)
    if request.method == 'POST':
        if 'mark_bill_paid' in request.POST:
            bill = Bill.objects.get(overall_bill_id=overall_bill_id)
            if 'lender_as_user_yes' in request.POST: 
                bill_details = BillDetails.objects.filter(bill=bill)
                for bill_detail in bill_details:
                    bill_detail.bill_cleared = 'Y'
                    bill_detail.save()
                return HttpResponseRedirect('/home/')
            else:
                lender_as_user = UserProfile.objects.get(user__email=request.POST['lender'])
                user_friend = UserFriend.objects.get(user_profile=lender_as_user, friend_email=userprofile_object.user.email)
                bill_detail = BillDetails.objects.get(bill=bill, borrower=user_friend)
                bill_detail.bill_cleared = 'Y'
                bill_detail.save()

                # Send Email Start
                context = Context({ 'userprofile_object': userprofile_object, 'description': bill.description })
                subject = 'New Payment by: ' + userprofile_object.user.first_name  + ' ' + userprofile_object.user.last_name
                payment_creation_txt_content = payment_creation_txt.render(context)
                payment_creation_html_content = payment_creation_html.render(context)
                send_html_mail(subject, payment_creation_txt_content, payment_creation_html_content, settings.DEFAULT_FROM_EMAIL, [ lender_as_user.user.email ])
                # Send Email End

                return HttpResponseRedirect('/home/')
        elif 'delete_bill' in request.POST:
            bill = Bill.objects.get(overall_bill_id=overall_bill_id)
            bill_details = BillDetails.objects.filter(bill=bill)
            for bill_detail in bill_details:
                bill_detail.delete()
            bill.delete()
            return HttpResponseRedirect('/who-owes-me/')
        elif 'modify_bill' in request.POST:
            modify_bill(request, overall_bill_id)
            return HttpResponseRedirect('/who-owes-me/')
    else: 
        bill = Bill.objects.get(overall_bill_id=overall_bill_id)
        if bill.lender == userprofile_object:
            user_lender = True
        else:
            user_lender = False
        borrowers = BillDetails.objects.filter(bill=bill)
        return render_to_response('specific-bill-details.html', { 'bill': bill, 'borrowers': borrowers, 'user_lender': user_lender, 'userprofile_object': userprofile_object, 'request': request }, context_instance=RequestContext(request))
Esempio n. 54
0
    def handle_noargs(self, **options):

        daily = options.get("daily", False)
        weekly = options.get("weekly", False)
        if not daily and not weekly:
            print "use --daily or --weekly"
            return

        translation.activate(self.lang)

        email_notification = []
        if daily:
            email_notification.append("D")
        if weekly:
            email_notification.append("W")

        queued = 0
        g = Group.objects.get(name="Valid Email")
        for user in User.objects.filter(groups=g, profiles__isnull=False).exclude(email=""):
            try:
                user_profile = user.get_profile()
            except UserProfile.DoesNotExist:
                logger.warn("can't access user %d userprofile" % user.id)
                continue
            if user_profile.email_notification in email_notification:
                # if this user has requested emails in the frequency we are
                # handling now
                email_body, email_body_html = self.get_email_for_user(user)
                if email_body:  # there are some updates. generate email
                    header = render_to_string(("notify/header.txt"), {"user": user})
                    footer = render_to_string(("notify/footer.txt"), {"user": user, "domain": self.domain})
                    header_html = render_to_string(("notify/header.html"), {"user": user})
                    footer_html = render_to_string(("notify/footer.html"), {"user": user, "domain": self.domain})
                    send_html_mail(
                        _("Open Knesset Updates"),
                        "%s\n%s\n%s" % (header, "\n".join(email_body), footer),
                        "%s\n%s\n%s" % (header_html, "".join(email_body_html), footer_html),
                        self.from_email,
                        [user.email],
                    )
                    queued += 1

        logger.info("%d email notifications queued for sending" % queued)

        translation.deactivate()
Esempio n. 55
0
def send_contact_form_email(sender, request, form, **kwargs):
    """sends the email from the contact form"""
    data = form.cleaned_data
    # render the plain text template
    t = loader.get_template('cccontact/message.txt')
    c = Context({
        'email': data.get('email'),
        'name': data.get('name'),
        'message': data.get('m'),
        'phone': data.get('phone')})
    message = t.render(c)
    
    send_html_mail(
            data['subject'],
            strip_tags(message),
            message,
            data['email'],
            c_settings.RECIPIENTS)
Esempio n. 56
0
 def handle_noargs(self, **options):
     translation.activate(self.lang)
     for u in User.objects.filter(agendas__isnull=False).distinct().all():
         msg = ''
         html_msg = ''
         for a in u.agendas.all():
             for usv in UserSuggestedVote.objects.filter(
                     agenda=a, sent_to_editor=False):
                 usv.sent_to_editor = True
                 usv.save()
                 msg += _('User %(user)s suggested vote %(vote)s to agenda '
                          '%(agenda)s with reasoning: %(reasoning)s') % {
                              'user': usv.user.username,
                              'vote': usv.vote,
                              'agenda': a,
                              'reasoning': usv.reasoning,
                          }
                 msg += '\n'
                 html_msg += _(
                     'User <a href="%(user_href)s">%(user)s</a> suggested vote '
                     '<a href="%(vote_href)s">%(vote)s</a> to agenda '
                     '<a href="%(agenda_href)s">%(agenda)s</a> '
                     'with reasoning %(reasoning)s') % {
                         'user_href':
                         self.prefix + usv.user.get_absolute_url(),
                         'user': usv.user.username,
                         'vote_href':
                         self.prefix + usv.vote.get_absolute_url(),
                         'vote': usv.vote,
                         'agenda_href': self.prefix + a.get_absolute_url(),
                         'agenda': a,
                         'reasoning': usv.reasoning,
                     }
                 html_msg += '<br>'
         if msg:
             send_html_mail(
                 _('Open Knesset Agenda Editor Update'),
                 msg,
                 html_msg,
                 self.from_email,
                 [u.email],
             )
Esempio n. 57
0
    def process_feed(self, feed):
        # parse feed
        parsed_feed = feedparser.parse(feed.feed_url)
        if 'feed' not in parsed_feed or not parsed_feed['feed']:
            print "Feed info not found"
            return False

        feed_info = parsed_feed.get('feed')
        feed.title = feed_info.get('title')
        feed.description = feed_info.get('subtitle')
        feed.save()

        # add all feed items into database
        for entry in parsed_feed.get('entries'):
            feed_item, is_new = FeedItem.objects.get_or_create(
                feed=feed, title=entry.title)
            if 'summary' in entry:
                feed_item.content = entry.get('summary')
            elif 'subtitle' in entry:
                feed_item.content = entry.get('subtitle')
            feed_item.link = entry.get('link')

            time_struct = entry.get('updated_parsed')
            updated_datetime = datetime.datetime(time_struct.tm_year, time_struct.tm_mon, \
                                        time_struct.tm_mday, time_struct.tm_hour, \
                                        time_struct.tm_min, time_struct.tm_sec)
            feed_item.updated_datetime = updated_datetime
            if is_new:
                feed_item.published_datetime = updated_datetime
            feed_item.author = entry.get('author', '')

            feed_item.save()

            # send email notification only if new feed item apears with user's keywords
            if is_new and user_filter_check_item(feed_item):
                message = "<a href='%(link)s'>%(title)s</a><br><br>%(content)s" % (
                    dict(link=feed_item.link,
                         title=feed_item.title,
                         content=feed_item.content))
                recipients = [Setting.objects.get_email()]
                send_html_mail("[Feed filter] New feed item", "", message,
                               settings.DEFAULT_FROM_EMAIL, recipients)
Esempio n. 58
0
    def post(self, request, *args, **kwargs):
        email_serializer = EmailSerializer(data=request.DATA)
        if email_serializer.is_valid():
            try:
                email = email_serializer.data.get('email', None)
                user = User.objects.get(email=email)
                user.profile.activationtoken = sha1(
                    "%sxauto%s" %
                    (randrange(1, 1000), randrange(1, 1000))).hexdigest()
                user.profile.save()
                reset_link = request.build_absolute_uri(
                    reverse('change-password',
                            args=(user.profile.activationtoken, )))

                # change Django url to Angular url
                reset_link = reset_link.replace(
                    "{}/api/change_password".format(settings.APP_PREFIX),
                    "/#/account/changePassword")

                email_body = render_to_string(
                    'emails/reset_password_email.html', {
                        'user': user,
                        'title': 'Password reset',
                        'site_name': settings.SITE_NAME,
                        'reset_link': reset_link
                    })
                if "mailer" in settings.INSTALLED_APPS:
                    send_html_mail("Reset Password", email_body, email_body,
                                   settings.DEFAULT_FROM_EMAIL, [user.email])
                else:
                    send_mail("Reset Password", email_body,
                              settings.DEFAULT_FROM_EMAIL, [user.email])

                return Response({'success': True})
            except User.DoesNotExist:
                return Response(
                    {'email': ["User with this email address doesn't exist"]},
                    status=status.HTTP_400_BAD_REQUEST)

        return Response(email_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Esempio n. 59
0
def register(request):
    result = False
    full_form = UserProfileForm(request.POST or None)
    simple_form = RegistrationFormUniqueEmail(request.POST or None)

    if simple_form.is_valid():
        email = simple_form.cleaned_data['email']
        password = simple_form.cleaned_data['password']
        user, __ = User.objects.get_or_create(username=email, email=email)
        user.set_password(password)
        user.save()
        msg = u'<p>Благодарим вас за регистрацию на нашем ивенте. Мы будем оповещать вас о важных событиях.</p><p>Вы уже можете <a href="http://hackpoint.ru/login/">войти на сайт</a> и найти себе команду.</p><p>С уважением организаторы.</p>'
        send_html_mail(u'Спасибо за регистрацию на hackpoint.ru', '', msg,
                       settings.DEFAULT_FROM_EMAIL, [user.email])
        result = True
        new_user = authenticate(username=email, password=password)
        login(request, new_user)
        #return HttpResponseRedirect("/dashboard/")

    if full_form.is_valid():
        profile = full_form.save(commit=False)
        email = request.POST.get('email', None)
        username = request.POST.get('username', None)
        if email:
            user, created = User.objects.get_or_create(username=email,
                                                       email=email)
            user.profile.username = username
            user.profile.user_skills = profile.user_skills
            user.profile.user_role = profile.user_role
            user.profile.has_idea = profile.has_idea
            user.profile.contact = profile.contact
            user.save()
            user.profile.save()
        result = True

    if result:
        return {
            'created': result,
            'url': resolve_url('profile_detail', pk=user.id)
        }
    return redirect('/')