Example #1
0
def send_email(subject, template_name, to=[], context={}, from_email=settings.AWS_SES_RETURN_PATH):
    context = Context(context)
    plaintext = get_template('emails/' + template_name + '.txt').render(context)
    htmly = get_template('emails/' + template_name + '.html').render(context)
    email = EmailMultiAlternatives(subject, plaintext, from_email, to)
    email.attach_alternative(htmly, "text/html")
    email.send()
Example #2
0
def email_everyone(request, *args, **kwargs):

    if request.method == 'POST':
        subject = request.POST.get('subject', '')
        message = request.POST.get('message', '')

        t = get_template('contact/email.html')
        c = Context({'message': message})
        html_content = t.render(c)
        text_content = strip_tags(html_content)

        for profile in Profile.objects.all():
            msg = EmailMultiAlternatives(subject, text_content,
                                         '*****@*****.**',
                                         [profile.user.email])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

        return redirect("/")
    else:
        form = EmailForm()

    return render_to_response('contact/email_everyone.html', {
        'form': form,
    }, RequestContext(request))
Example #3
0
def confirm_cart_to_user(profile, action):
    """send message by email"""

    from_email = getattr(settings, 'DEFAULT_FROM_EMAIL')
    subject = get_cart_confirmation_subject()


    data = {
        'profile': profile,
        'action': action,
        'subject': subject,
    }


    the_template = get_template('Store/cart_confirmation_email.html')
    html_text = the_template.render(Context(data))
    text = dehtml(html_text)

    email = EmailMultiAlternatives(
        subject,
        text,
        from_email,
        [profile.contact.email],
    )
    email.attach_alternative(html_text, "text/html")

    try:
        email.send()
    except Exception:
        logger.exception("confirm_cart_to_user")
Example #4
0
def emergencia_mail(request):
    nombre = request.POST.get("nombre")
    telefono = request.POST.get("telefono")
    latitud = request.POST.get("latitud")
    longitud = request.POST.get("longitud")
    mapa = request.POST.get("mapa")
    gmap = "https://maps.google.com/maps?z=16&t=m&q="+latitud+","+longitud

    from_email = 'Medikus <*****@*****.**>'
    subject = 'Alerta de emergencia enviada desde Medikus'
    tos = ["*****@*****.**","*****@*****.**","*****@*****.**"]
    message = ('<h2>Reporte de emergencia</h2>'
                    '<p>Nombre: '+nombre+'</p>'
                    '<p>Telefono: '+telefono+'</p>'
                    '<p>Latitud: '+latitud+'</p>'
                    '<p>Longitud: '+longitud+'</p>'
                    '<p>'+mapa+'</p>'
                    '<p>Google Maps: '+gmap+'</p>'
                    '<br/><p>Este mensaje ha sido generado autom&aacute;ticamente por Medikus</p>'
    )

    msg = EmailMultiAlternatives(subject, "", from_email,tos)
    msg.attach_alternative(message, "text/html")
    msg.send()
    return HttpResponse("OK", content_type="text/plain")
Example #5
0
def send_activation_email(
        user=None, request=None, from_email=None,
        subject_template='users/activation_email_subject.html',
        email_template='users/activation_email.html', html_email_template=None):

    if not user.is_active and settings.USERS_VERIFY_EMAIL:
        token_generator = EmailActivationTokenGenerator()

        current_site = get_current_site(request)

        context = {
            'email': user.email,
            'site': current_site,
            'expiration_days': settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS,
            'user': user,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': token_generator.make_token(user=user),
            'protocol': 'https' if request.is_secure() else 'http',
        }

        subject = render_to_string(subject_template, context)
        # email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = render_to_string(email_template, context)

        email_message = EmailMultiAlternatives(subject, body, from_email, [user.email])
        if html_email_template is not None:
            html_email = render_to_string(html_email_template, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()
Example #6
0
    def send_premium_expire_email(self, force=False):
        if not self.user.email:
            logging.user(self.user, "~FM~SB~FRNot~FM sending premium expire for user: %s" % (self.user))
            return

        emails_sent = MSentEmail.objects.filter(receiver_user_id=self.user.pk,
                                                email_type='premium_expire')
        day_ago = datetime.datetime.now() - datetime.timedelta(days=360)
        for email in emails_sent:
            if email.date_sent > day_ago:
                logging.user(self.user, "~FM~SBNot sending premium expire email, already sent before.")
                return
        
        delta      = datetime.datetime.now() - self.last_seen_on
        months_ago = delta.days / 30
        user    = self.user
        data    = dict(user=user, months_ago=months_ago)
        text    = render_to_string('mail/email_premium_expire.txt', data)
        html    = render_to_string('mail/email_premium_expire.xhtml', data)
        subject = "Your premium account on NewsBlur has expired"
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.send(fail_silently=True)
        
        MSentEmail.record(receiver_user_id=self.user.pk, email_type='premium_expire')
        logging.user(self.user, "~BB~FM~SBSending premium expire email for user: %s months, %s" % (months_ago, self.user.email))
Example #7
0
def notify_cart_to_admin(profile, action):
    """send message by email"""
    notification_email = getattr(settings, 'BALAFON_NOTIFICATION_EMAIL', '')
    if notification_email:
        from_email = getattr(settings, 'DEFAULT_FROM_EMAIL')
        subject = _(u"New cart purchased on store")
        data = {
            'profile': profile,
            'action': action,
            'subject': subject,
        }
        the_template = get_template('Store/cart_notification_email.html')
        html_text = the_template.render(Context(data))
        text = dehtml(html_text)

        email = EmailMultiAlternatives(
            subject,
            text,
            from_email,
            [notification_email],
            headers={'Reply-To': profile.contact.email}
        )
        email.attach_alternative(html_text, "text/html")

        try:
            email.send()
        except Exception:
            logger.exception("notify_cart_to_admin")
Example #8
0
    def send_new_premium_email(self, force=False):
        subs = UserSubscription.objects.filter(user=self.user)
        message = """Woohoo!
        
User: %(user)s
Feeds: %(feeds)s

Sincerely,
NewsBlur""" % {'user': self.user.username, 'feeds': subs.count()}
        mail_admins('New premium account', message, fail_silently=True)
        
        if not self.user.email or not self.send_emails:
            return
        
        sent_email, created = MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                                               email_type='new_premium')
        
        if not created and not force:
            return
        
        user    = self.user
        text    = render_to_string('mail/email_new_premium.txt', locals())
        html    = render_to_string('mail/email_new_premium.xhtml', locals())
        subject = "Thanks for going premium on NewsBlur!"
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.send(fail_silently=True)
        
        logging.user(self.user, "~BB~FM~SBSending email for new premium: %s" % self.user.email)
Example #9
0
 def send_launch_social_email(self, force=False):
     if not self.user.email or not self.send_emails:
         logging.user(self.user, "~FM~SB~FRNot~FM sending launch social email for user, %s: %s" % (self.user.email and 'opt-out: ' or 'blank', self.user.email))
         return
     
     sent_email, created = MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                                            email_type='launch_social')
     
     if not created and not force:
         logging.user(self.user, "~FM~SB~FRNot~FM sending launch social email for user, sent already: %s" % self.user.email)
         return
     
     delta      = datetime.datetime.now() - self.last_seen_on
     months_ago = delta.days / 30
     user    = self.user
     data    = dict(user=user, months_ago=months_ago)
     text    = render_to_string('mail/email_launch_social.txt', data)
     html    = render_to_string('mail/email_launch_social.xhtml', data)
     subject = "NewsBlur is now a social news reader"
     msg     = EmailMultiAlternatives(subject, text, 
                                      from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                      to=['%s <%s>' % (user, user.email)])
     msg.attach_alternative(html, "text/html")
     msg.send(fail_silently=True)
     
     logging.user(self.user, "~BB~FM~SBSending launch social email for user: %s months, %s" % (months_ago, self.user.email))
Example #10
0
    def send_opml_export_email(self):
        if not self.user.email:
            return
        
        MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                         email_type='opml_export')
        
        exporter = OPMLExporter(self.user)
        opml     = exporter.process()

        params = {
            'feed_count': UserSubscription.objects.filter(user=self.user).count(),
        }
        user    = self.user
        text    = render_to_string('mail/email_opml_export.txt', params)
        html    = render_to_string('mail/email_opml_export.xhtml', params)
        subject = "Backup OPML file of your NewsBlur sites"
        filename= 'NewsBlur Subscriptions - %s.xml' % datetime.datetime.now().strftime('%Y-%m-%d')
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.attach(filename, opml, 'text/xml')
        msg.send(fail_silently=True)
        
        logging.user(self.user, "~BB~FM~SBSending OPML backup email to: %s" % self.user.email)
Example #11
0
    def send_first_share_to_blurblog_email(self, force=False):
        from apps.social.models import MSocialProfile, MSharedStory
        
        if not self.user.email:
            return

        sent_email, created = MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                                               email_type='first_share')
        
        if not created and not force:
            return
        
        social_profile = MSocialProfile.objects.get(user_id=self.user.pk)
        params = {
            'shared_stories': MSharedStory.objects.filter(user_id=self.user.pk).count(),
            'blurblog_url': social_profile.blurblog_url,
            'blurblog_rss': social_profile.blurblog_rss
        }
        user    = self.user
        text    = render_to_string('mail/email_first_share_to_blurblog.txt', params)
        html    = render_to_string('mail/email_first_share_to_blurblog.xhtml', params)
        subject = "Your shared stories on NewsBlur are available on your Blurblog"
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.send(fail_silently=True)
        
        logging.user(self.user, "~BB~FM~SBSending first share to blurblog email to: %s" % self.user.email)
Example #12
0
def email_about_suggested_event_comment(comment, base_url):
    base_url = fix_base_url(base_url)
    emails = _get_add_event_emails()
    event_title = comment.suggested_event.title
    if len(event_title) > 30:
        event_title = '%s...' % event_title[:27]
    subject = (
        '[Air Mozilla] New comment on suggested event: %s' % event_title
    )
    context = {
        'event': comment.suggested_event,
        'comment': comment,
        'base_url': base_url,
        'subject': subject,
    }
    html_body = render_to_string(
        'suggest/_email_comment.html',
        context
    )
    assert emails
    body = html2text(html_body)
    email = EmailMultiAlternatives(
        subject,
        body,
        settings.EMAIL_FROM_ADDRESS,
        emails
    )
    email.attach_alternative(html_body, "text/html")
    email.send()
Example #13
0
def email_about_suggested_event(event, base_url):
    base_url = fix_base_url(base_url)
    emails = _get_add_event_emails()
    event_title = event.title
    if len(event_title) > 30:
        event_title = '%s...' % event_title[:27]
    comments = (
        SuggestedEventComment.objects
        .filter(suggested_event=event)
        .order_by('created')
    )
    subject = (
        '[Air Mozilla] New suggested event: %s' % event_title
    )
    assert emails
    context = {
        'event': event,
        'base_url': base_url,
        'comments': comments,
        'subject': subject,
    }
    html_body = render_to_string(
        'suggest/_email_submitted.html',
        context
    )
    body = html2text(html_body)
    email = EmailMultiAlternatives(
        subject,
        body,
        settings.EMAIL_FROM_ADDRESS,
        emails
    )
    email.attach_alternative(html_body, "text/html")
    email.send()
Example #14
0
    def send_forgot_password_email(self):
        self.forgot_password_token = self._generate_token()
        self.save()

        try:
            to = self.user.email
            from_email = settings.DEFAULT_FROM_EMAIL
            subject = settings.DEFAULT_EMAIL_FORGOT_PASSWORD_SUBJECT
            forgot_password_link = "%s/user/reset-password/token/%s/" % (settings.BASE_URL, self.forgot_password_token)

            body = u"Dear {name},".format(name=self.user.first_name)
            body += u"To update your password access link below:"
            body += u"{link}".format(link=forgot_password_link)
            body += u"Graciously,"
            body += u"Dashboard Team."

            body_html = u"Dear %s,<br /><br />".format(name=self.user.first_name)
            body_html += u"To update your password access link below:<br /><br />"
            body_html += u"<a href='{link}'>{link}</a><br /><br />".format(link=forgot_password_link)
            body_html += u"Graciously,<br />"
            body_html += u"Dashboard Team."

            msg = EmailMultiAlternatives(subject, body, from_email, [to])
            msg.attach_alternative(body_html, "text/html")
            msg.send()
            return True

        except Exception:
            logging.error("[FORGOT PASSWORD] - sending email failure.")
            return False
Example #15
0
def lugati_feedback(request):
    cur_site = get_current_site(request)
    form = LugatiFeedbackForm(request.POST)
    if form.is_valid():
        message = form.cleaned_data['message']
        name = form.cleaned_data['name']
        subject = form.cleaned_data['subject']
        mail = form.cleaned_data['mail']
        phone = form.cleaned_data['phone']

        message_text = ""
        message_text += u"от: " + unicode(name) + " (" + unicode(mail) + ")\n"
        message_text += u"тема: " + unicode(subject) + "\n"
        message_text += u"телефон для связи: " + unicode(phone) + "\n"
        message_text += u"текст: " + unicode(message)

        #to us
        emails  = [settings.DEFAULT_FROM_EMAIL]
        try:
            msg = EmailMultiAlternatives(u"вопрос с сайта primorsk.su", message_text, settings.DEFAULT_FROM_EMAIL, emails)
            msg.send()
        except Exception, e:
            logger.error(str(e))

        return HttpResponse(json.dumps({'response': "Email with a confirmation link has been sent", 'result': 'success'}))
Example #16
0
def maid_profile(request, pk):
	"""
	Home Page
	"""
	success_msg = None
	try:
		maids = Maid.objects.get(pk=pk)
	except Maid.DoesNotExist:
		maids = None
	if request.method == 'POST':

		from django.core.mail import EmailMultiAlternatives
		from django.template.loader import render_to_string
		from django.utils.html import strip_tags

		subject = 'Share maid details'

		html_content = render_to_string('templated_email/share_friend.html', {'maids':maids, 'DOMAIN_URL': settings.DOMAIN_URL,}) # ...
		text_content = strip_tags(html_content) # this strips the html, so people will have the text as well.

		# create the email, and attach the HTML version as well.
		msg = EmailMultiAlternatives(subject, text_content, '*****@*****.**', [request.POST.get('email')])
		msg.attach_alternative(html_content, "text/html")
		msg.send()

		success_msg = "Your request successfully sent to your Friend."

	return render_to_response('maid_profiile.html',{'maids':maids, 'success_msg':success_msg}, context_instance=RequestContext(request))
Example #17
0
def sendMailToContacts(name, html, text):
    # Get a list of all of the current contactees
    contacts = ContactEmail.objects.all()
    email_addresses = []
    # Build E-Mail
    subject = str(name) + " has requested a Quote on SCCS"
    text_message = text
    html_message = html
    from_addr = "*****@*****.**"

    # Create List of e-mail addresses
    for address in contacts:
        email_addresses.append(address.email)

    try:
        # Get django e-mail settings
        connection = mail.get_connection()
        # Open E-Mail server connection
        connection.open()
        # Append RAW Text
        email_message = EmailMultiAlternatives(subject, text_message,
                                               from_addr, email_addresses,
                                               connection=connection)
        # Append HTML
        email_message.attach_alternative(html_message, "text/html")
        # Send Message
        email_message.send()

        connection.close()
    except Exception as err:
        connection.close()
        log(err)
Example #18
0
def send_order_received_mail(order):
    """Sends an order received mail to the shop customer.

    Customer information is taken from the provided order.
    """
    import muecke.core.utils
    shop = muecke.core.utils.get_default_shop()

    try:
        subject = render_to_string("muecke/mail/order_received_subject.txt", {"order": order})
    except TemplateDoesNotExist:
        subject = _(u"Your order has been received")

    from_email = shop.from_email
    to = [order.customer_email]
    bcc = shop.get_notification_emails()

    # text
    text = render_to_string("muecke/mail/order_received_mail.txt", {"order": order})
    mail = EmailMultiAlternatives(
        subject=subject, body=text, from_email=from_email, to=to, bcc=bcc)

    # html
    html = render_to_string("muecke/mail/order_received_mail.html", {
        "order": order
    })

    mail.attach_alternative(html, "text/html")
    mail.send(fail_silently=True)
Example #19
0
def send_customer_added(user):
    """Sends a mail to a newly registered user.
    """
    import muecke.core.utils
    shop = muecke.core.utils.get_default_shop()
    subject = _(u"Welcome to %s" % shop.name)

    from_email = shop.from_email
    to = [user.username]
    bcc = shop.get_notification_emails()

    # text
    text = render_to_string("muecke/mail/new_user_mail.txt", {
        "user": user, "shop": shop})

    # subject
    subject = render_to_string("muecke/mail/new_user_mail_subject.txt", {
        "user": user, "shop": shop})

    mail = EmailMultiAlternatives(
        subject=subject, body=text, from_email=from_email, to=to, bcc=bcc)

    # html
    html = render_to_string("muecke/mail/new_user_mail.html", {
        "user": user, "shop": shop,
    })

    mail.attach_alternative(html, "text/html")
    mail.send(fail_silently=True)
Example #20
0
def send_mail_template(subject, template, addr_from, addr_to, context=None,
                       attachments=None, fail_silently=False, addr_bcc=None):
    """
    Send email rendering text and html versions for the specified
    template name using the context dictionary passed in.
    """
    if context is None:
        context = {}
    if attachments is None:
        attachments = []
    # Allow for a single address to be passed in.
    if not hasattr(addr_to, "__iter__"):
        addr_to = [addr_to]
    if addr_bcc is not None and not hasattr(addr_bcc, "__iter__"):
        addr_bcc = [addr_bcc]
    # Loads a template passing in vars as context.
    render = lambda type: loader.get_template("%s.%s" %
                          (template, type)).render(Context(context))
    # Create and send email.
    msg = EmailMultiAlternatives(subject, render("txt"),
                                 addr_from, addr_to, addr_bcc)
    msg.attach_alternative(render("html"), "text/html")
    for attachment in attachments:
        msg.attach(*attachment)
    msg.send(fail_silently=fail_silently)
Example #21
0
def send_review_added(review):
    """Sends a mail to shop admins that a new review has been added
    """
    import muecke.core.utils
    shop = muecke.core.utils.get_default_shop()

    subject = _(u"New review has been added")
    from_email = shop.from_email
    to = shop.get_notification_emails()

    ctype = ContentType.objects.get_for_id(review.content_type_id)
    product = ctype.get_object_for_this_type(pk=review.content_id)

    # text
    text = render_to_string("muecke/mail/review_added_mail.txt", {
        "review": review,
        "product": product,
    })

    mail = EmailMultiAlternatives(
        subject=subject, body=text, from_email=from_email, to=to)

    # html
    html = render_to_string("muecke/mail/review_added_mail.html", {
        "site": "http://%s" % Site.objects.get(id=settings.SITE_ID),
        "review": review,
        "product": product,
    })

    mail.attach_alternative(html, "text/html")
    mail.send(fail_silently=True)
    def send_to(self, to):
        """ Send email """
        if settings.DEVELOPMENT:
            print "[MAGICEMAIL][DEVELOPMENT] Skipping send email: {0} >>>".format(
                self._subject.encode('utf-8'))
            return True
        self._to = to
        if not self._reply_to:
            self._reply_to = self._from

        email_headers = {'h:Reply-To': self._reply_to, 
                         'Reply-To': self._reply_to, }
        if self._extra_data:
            email_headers['v:my-custom-data'] = self._extra_data

        email = EmailMultiAlternatives(
                    subject=self._subject,
                    body=self._data.get('body'),
                    from_email=self._from,
                    to=self._to,
                    headers=email_headers
                )
        email.attach_alternative(self._template_content(), "text/html")
        if self._extra_data:
            email.extra_headers['X-Mailgun-Variables'] = email_headers

        email.send()
        return True
Example #23
0
File: token.py Project: Renzo04/api
def enviar_mail_activacion(usuario):
    # Se genera token con email del usuario.
    token_link = generar_token(usuario.email, url=True)
    token_clave = generar_token(usuario.id)

    # Creación de URL de confirmación
    confirm_url = FRONTEND_URL + 'activar-cuenta/' + token_link

    # Obtención de templates html y txt de emails.
    htmly = loader.get_template('emails/html/confirmar_cuenta.html')
    text = loader.get_template('emails/txt/confirmar_cuenta.txt')

    # Definición de variables de contexto
    variables = {
        'usuario': usuario,
        'confirm_url': confirm_url,
        'clave': token_clave
    }
    html_content = htmly.render(variables)
    text_content = text.render(variables)

    # Creación y envío de email.
    msg = EmailMultiAlternatives(
        'Bienvenido a Manos por gotas',
        text_content,
        to=[usuario.email]
    )

    msg.attach_alternative(html_content, "text/html")
    msg.send()
Example #24
0
def send_email(request):
    if request.method == 'POST':
        try:
            from django.core.mail import EmailMultiAlternatives
            behalf = request.POST['behalf']
            to = request.POST['to']
            cc = request.POST['cc']
            bcc = request.POST['bcc']

            subject = request.POST['subject']
            body = request.POST['body']

            if hasattr(settings, 'REPLY_TO'):
                reply_to = {'Reply-To': settings.REPLY_TO, 'Return-Path': settings.REPLY_TO}
            else:
                reply_to = {}

            e = EmailMultiAlternatives(
                subject=subject,
                from_email=behalf,
                to=to.split(';'),
                cc=cc.split(';'),
                bcc=bcc.split(';'),
                headers=reply_to
            )
            e.attach_alternative(body, 'text/html')
            e.content_subtype = 'html'
            e.send()

            return HttpResponse(dumps({'status': 'ok'}), content_type="application/json")

        except Exception, e:
            return HttpResponse(dumps({'status': 'ko', 'error': str(e)}), content_type="application/json")
Example #25
0
    def email_submission(self, form_data, request, referrer):
        mail_to = re.compile('\s*[,;]+\s*').split(self.form_definition.email_to)
        mail_from = self.form_definition.email_from or None
        mail_subject = self.form_definition.email_subject or \
            'Form Submission - %s' % self.form_definition.name
        context = {
            'form': self.form_definition,
            'referrer': referrer,
            'title': mail_subject,
            'form_data': form_data,
            'request': request,
            'recipients': mail_to,
        }

        message = render_to_string('djangocms_forms/email_template/email.txt', context)
        message_html = render_to_string('djangocms_forms/email_template/email.html', context)

        email = EmailMultiAlternatives(mail_subject, message, mail_from, mail_to)
        email.attach_alternative(message_html, 'text/html')

        if self.form_definition.email_uploaded_files:
            for field, filedata in self.files.items():
                filedata.open('r')
                content = filedata.read()
                filedata.close()
                email.attach(filedata.name, content, filedata.content_type)

        email.send(fail_silently=False)
Example #26
0
def register(request):
    if request.method == "POST":
        #Preparing the user to store in the database
        user = User(
            username=request.POST.get('username'),
            password=make_password(request.POST.get('password')),
            email=request.POST.get('email'),
            isWarned=False,
            isAdmin=False,
            activationLink="".join( [random.choice(string.letters) for i in xrange(32)] ),
            registrationDate=timezone.now()
        )

        #Preparing the response
        response_data = {}
        response_data['username_already_taken'] = 'false'
        response_data['invalid_email']='false'
        response_data['email_already_taken'] = 'false'
        response_data['result'] = 'success'

        #Checking if the username exists in the database
        try:
            User.objects.get(username=user.username)
            usernameTaken = True
        except User.DoesNotExist:
            usernameTaken = False

        if usernameTaken==False:
            try:
                validate_email(user.email)
                user.save()
                #Preparing the email to send
                subject, from_email, to = 'SurveyVor Activation', '*****@*****.**', user.email
                html_content = render_to_string('Account/activation_mail.html', {'activationLink':user.activationLink})
                text_content = """
Congratulations!

Your registration is almost complete. To be able to access your account, click on the activation link bellow:
http://www.okarrakchou.com/account/activate/%s

Regards,
The Surveyvor Team
""" % (user.activationLink)
                # create the email, and attach the HTML version as well.
                msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
                msg.attach_alternative(html_content, "text/html")
                msg.send()
            except ValidationError:
                response_data['result'] = 'failure'
                response_data['invalid_email']='true'
            except IntegrityError:
                response_data['result'] = 'failure'
                response_data['email_already_taken']='true'
        else:
            response_data['result'] = 'failure'
            response_data['username_already_taken']='true'

        return HttpResponse(json.dumps(response_data), mimetype="application/json")
    else:
        return HttpResponse(0)
Example #27
0
 def handle(self, *args, **options):
     plaintext = get_template('email/weekly.txt')
     htmly = get_template('email/weekly.html')
     all_users = User.objects.exclude(extra__emails=False)
     for user in all_users:
         # start by finding the ideas posted by a user
         commented_on_ideas = user.get_profile().comments_on_owned_ideas(7)
         self.stdout.write("user %s\n" %user)
         for idea in commented_on_ideas:
             self.stdout.write("you've got new comments on: %s\n" % idea.idea)
         #new_slates = user.slates.all()
         new_slates = user.slates.filter(
                 date_created__gte = datetime.date.today()-datetime.timedelta(7)
                 )
         self.stdout.write("you've joined %i slates \n" % len(new_slates))
         
         d = Context({ 'user': user })
         #actually send the e-mail
         if new_slates and commented_on_ideas:
             subject, from_email, to = 'Weekly Digest', '*****@*****.**', user.email
             text_content = plaintext.render(d)
             html_content = htmly.render(d)
             msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
             msg.attach_alternative(html_content, "text/html")
             if "final" in args:
                 try:
                     msg.send()
                 except:
                     self.stdout.write("failed to send email")
             else:
                 self.stdout.write("test success")
Example #28
0
File: token.py Project: Renzo04/api
def enviar_mail_reiniciar_password(usuario):
    # Se genera token con email del usuario.
    token_link = generar_token(usuario.email, url=True)

    # Creación de URL de confirmación
    reset_url = FRONTEND_URL + 'reset-password/' + token_link

    # Obtención de templates html y txt de emails.
    htmly = loader.get_template('emails/html/reiniciar_password.html')
    text = loader.get_template('emails/txt/reiniciar_password.txt')

    # Definición de variables de contexto
    variables = {
        'usuario': usuario,
        'reset_url': reset_url,
    }
    html_content = htmly.render(variables)
    text_content = text.render(variables)

    # Creación y envío de email.
    msg = EmailMultiAlternatives(
        'Reiniciar contraseña',
        text_content,
        to=[usuario.email]
    )

    msg.attach_alternative(html_content, "text/html")
    msg.send()
Example #29
0
def send_mail(subject, message_plain, message_html, email_from, email_to,
              custom_headers={}, attachments=()):
    """
    Build the email as a multipart message containing
    a multipart alternative for text (plain, HTML) plus
    all the attached files.
    """
    if not message_plain and not message_html:
        raise ValueError(_("Either message_plain or message_html should be not None"))

    if not message_plain:
        message_plain = html2text(message_html)

    message = {}

    message['subject'] = subject
    message['body'] = message_plain
    message['from_email'] = email_from
    message['to'] = email_to
    if attachments:
        message['attachments'] = attachments
    if custom_headers:
        message['headers'] = custom_headers

    msg = EmailMultiAlternatives(**message)
    if message_html:
        msg.attach_alternative(message_html, "text/html")
    msg.send()
def send_warning_email(date=None, url=None, addr=None, job_name=None):
    """
    Args:
        date: A datetime object representing when the run will expire
        url: The url to the detail page of the export
        addr: The email address to which the email will be sent

    Returns: None
    """

    subject = "Your EventKit DataPack is set to expire."
    to = [addr]
    from_email = getattr(
        settings,
        'DEFAULT_FROM_EMAIL',
        'Eventkit Team <*****@*****.**>'
    )
    ctx = {'url': url, 'date': str(date), 'job_name': job_name}

    text = get_template('email/expiration_warning.txt').render(ctx)
    html = get_template('email/expiration_warning.html').render(ctx)
    try:
        msg = EmailMultiAlternatives(subject, text, to=to, from_email=from_email)
        msg.attach_alternative(html, "text/html")
        msg.send()
    except Exception as e:
        logger.error("Encountered an error when sending status email: {}".format(e))
Example #31
0
def send_user_token_email(
        user=None,
        request=None,
        subject_template_name=None,
        from_email=None,  # settings.EMAIL_HOST_USER,
        email_template_name=None,
        html_email_template_name=None,
        token_generator=default_token_generator,
        site_name=None,
        site_url=None,
        extra_email_context=None):
    '''Sends an email to a user with a uid/token link to reset password.

    user - existing user in db
    request - request from view where function is called
    subject_template_name - text file containing the email subject
    from_email - email address of sender
    email_template_name - template containing email body
    html_email_template - html-formatted template to display email_template
    token_generator - generate token based on user
    site name - name of project
    site_url - main project url
    extra_email_context - dict containing extra email context variables
    '''
    if not user or not request or not subject_template_name or not email_template_name:
        pass
    uid = urlsafe_base64_encode(force_bytes(user.pk))
    token = token_generator.make_token(user)
    token_url = request.build_absolute_uri(
        reverse('users:user_forgot_password_reset',
                kwargs={
                    'uidb64': uid,
                    'token': token
                }))
    if site_name is None:
        if hasattr(settings, 'PROJECT_NAME'):
            site_name = settings.PROJECT_NAME
    if site_url is None:
        if hasattr(settings, 'PROJECT_HOME_URL'):
            site_url = request.build_absolute_uri(
                reverse(settings.PROJECT_HOME_URL))
        else:
            site_url = request.build_absolute_uri('/')
    else:
        site_url = request.build_absolute_uri(reverse(site_url))
    context = {
        'request': request,
        'username': user,
        'site_url': site_url,
        'site_name': site_name,
        'token_url': token_url
    }
    if extra_email_context is not None:
        context.update(extra_email_context)
    '''
    Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
     '''
    subject = loader.render_to_string(subject_template_name, context)
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    body = loader.render_to_string(email_template_name, context)
    email_message = EmailMultiAlternatives(subject, body, from_email,
                                           [user.email])
    if html_email_template_name is not None:
        html_email = loader.render_to_string(html_email_template_name, context)
        email_message.attach_alternative(html_email, 'text/html')

    email_message.send()
Example #32
0
def send_mail(recipients, template, subject):
    from_email = settings.SERVER_EMAIL
    msg = EmailMultiAlternatives(subject, template, from_email, recipients)
    msg.attach_alternative(template, "text/html")
    msg.send()
def newsletter_signup(request):
    NewsletterUser2 = NewsletterUser.objects.all()
    count_users = NewsletterUser.objects.all().count()

    form = NewsletterUserSignUpForm(request.POST or None)

    if form.is_valid():
        instance = form.save(commit=False)

        if NewsletterUser.objects.filter(email=instance.email).exists():
            messages.warning(request,
                             'Your Email already exists in our database',
                             "alert alert-warning alert-dismissable")
        else:
            instance.save()
            messages.success(
                request, 'Your Email  submitted to our database succesfully ',
                "alert alert-success alert-dismissable")
            subject = "Thank you for subscribing our newsletter"
            from_email = settings.EMAIL_HOST_USER
            to_email = [instance.email]
            #rec_emails =NewsletterUser.objects.all()
            #    print(rec_emails)
            #    print(len(rec_emails))
            #    query_list = []

            #signup_message = """Welcome to visit+ newsletter.To UnSubscribe,Go To http://127.0.0.1:8000/newsletter/unsubscribe/"""
            #send_mail(subject=subject,from_email=from_email,recipient_list=to_email,message=signup_message,fail_silently=False)
            """"for ob in rec_emails:
                email = str(ob.email)
                query_list.append(email)

            if len(rec_emails) >=3:
                with open(settings.BASE_DIR + "/newsletters/templates/newsletters/sign_up_email.txt") as f:
                    signup_message = f.read()
                message = EmailMultiAlternatives(subject=subject,body=signup_message,from_email=from_email,to=query_list)
                html_template = get_template("newsletters/sign_up_email.html").render()
                message.attach_alternative(html_template,"text/html")
                message.send()
                """

            with open(settings.BASE_DIR +
                      "/newsletters/templates/newsletters/sign_up_email.txt"
                      ) as f:
                signup_message = f.read()
            message = EmailMultiAlternatives(subject=subject,
                                             body=signup_message,
                                             from_email=from_email,
                                             to=to_email)
            html_template = get_template(
                "newsletters/sign_up_email.html").render()
            message.attach_alternative(html_template, "text/html")
            message.send()
            print("Thank u mail sent")

            if count_industries == 17:
                print(
                    "count_industries == 17 ,so sending emails to everyone indiviually"
                )
                subject_News = "New Industry added to the database"
                rec_emails = NewsletterUser.objects.all()
                print(rec_emails)
                print(len(rec_emails))
                query_list = []

                for ob in rec_emails:
                    email = str(ob.email)
                    query_list.append(email)
                    with open(
                            settings.BASE_DIR +
                            "/newsletters/templates/newsletters/New_Industry_Added.txt"
                    ) as f:
                        signup_message = f.read()
                    print("Newsletters Sending to", query_list)
                    message = EmailMultiAlternatives(subject=subject_News,
                                                     body=signup_message,
                                                     from_email=from_email,
                                                     to=query_list)
                    html_template = get_template(
                        "newsletters/New_Industry_Added.html").render()
                    message.attach_alternative(html_template, "text/html")
                    message.send()
                    print("Newsletters Sent to", query_list)
                    query_list.pop()
                print("Newsletters Sent to all!!")

    context = {
        'form': form,
        'NewsletterUser2': NewsletterUser2,
        'count': count_users,
    }

    return render(request, 'newsletters/sign_up.html', context)
Example #34
0
def contact_us(request):
    owner = User.objects.get(id=request.GET.get('owner')) if (
        request.GET.get('owner')
        and User.objects.filter(id=request.GET.get('owner')).first()) else None

    video = Video.objects.get(id=request.GET.get('video')) if (
        request.GET.get('video') and Video.objects.filter(
            id=request.GET.get('video')).first()) else None

    description = "%s: %s\n%s: %s%s\n\n" % (
        _('Title'), video.title, _('Link'), 'https:' if request.is_secure()
        else 'http:', video.get_full_url(request)) if video else None

    send_subject = request.GET.get('subject') if (
        request.GET.get('subject') and request.GET.get('subject')
        in [key for key, value in SUBJECT_CHOICES]) else None

    prefix = 'https://' if request.is_secure() else 'http://'
    home_page = ''.join([prefix, get_current_site(request).domain])
    url_referrer = request.META["HTTP_REFERER"] if request.META.get(
        "HTTP_REFERER") else home_page

    form = ContactUsForm(request,
                         initial={
                             'url_referrer': url_referrer,
                             'subject': send_subject,
                             'description': description
                         })

    if request.method == "POST":
        form = ContactUsForm(request, request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            form_subject = form.cleaned_data['subject'] if (
                form.cleaned_data.get('subject')) else send_subject
            subject = "[ %s ] %s" % (TITLE_SITE,
                                     dict(SUBJECT_CHOICES)[form_subject])
            email = form.cleaned_data['email']
            message = form.cleaned_data['description']

            text_content = loader.get_template('mail/mail.txt').render({
                'name':
                name,
                'email':
                email,
                'TITLE_SITE':
                TITLE_SITE,
                'message':
                message,
                'url_referrer':
                form.cleaned_data['url_referrer']
            })
            html_content = loader.get_template('mail/mail.html').render({
                'name':
                name,
                'email':
                email,
                'TITLE_SITE':
                TITLE_SITE,
                'message':
                message.replace("\n", "<br/>"),
                'url_referrer':
                form.cleaned_data['url_referrer']
            })

            dest_email = []
            dest_email = get_dest_email(owner, video, form_subject, request)

            msg = EmailMultiAlternatives(subject, text_content, email,
                                         dest_email)
            msg.attach_alternative(html_content, "text/html")
            msg.send(fail_silently=False)

            # EMAIL TO SENDER
            subject = "[ %s ] %s %s" % (TITLE_SITE, _('your message untitled'),
                                        dict(SUBJECT_CHOICES)[form_subject])

            text_content = loader.get_template('mail/mail_sender.txt').render({
                'TITLE_SITE':
                TITLE_SITE,
                'message':
                message
            })
            html_content = loader.get_template('mail/mail_sender.html').render(
                {
                    'TITLE_SITE': TITLE_SITE,
                    'message': message.replace("\n", "<br/>")
                })
            msg = EmailMultiAlternatives(subject, text_content,
                                         DEFAULT_FROM_EMAIL, [email])
            msg.attach_alternative(html_content, "text/html")
            msg.send(fail_silently=False)

            messages.add_message(request, messages.INFO,
                                 _('Your message have been sent.'))

            return redirect(form.cleaned_data['url_referrer'])

        else:
            messages.add_message(
                request, messages.ERROR,
                _(u'One or more errors have been found in the form.'))

    return render(request, 'contact_us.html', {'form': form, 'owner': owner})
Example #35
0
def payment_form_view(request):
    record = get_record(request)

    if not record.offer_agreement:  # Redirect to offer-agreement if user haven't agreed
        return redirect("purchase:offer-agreement")
    elif not record.is_ready():  # Redirect to form if it is not valid
        return redirect("purchase:entity-form"
                        ) if record.get_entity_payer_or_none() else redirect(
                            "purchase:individual-form")
    elif not record.is_confirmed():
        return redirect("purchase:confirmation-form")
    elif record.finished:
        return redirect("purchase:finished")

    if request.method == "POST":
        form = PaymentForm(request.POST)

        if form.is_valid():  # Finish purchase
            payment_type = form.cleaned_data.get("payment_type")

            record.payment_type = payment_type
            record.date_finished = timezone.now()
            record.save()

            # Send mail with full information to workers and payer
            if payment_type == "payme":
                payment_link = get_payment_link(
                    record.id, record.get_9_digit_phone(),
                    record.get_amount() * 100, request.LANGUAGE_CODE,
                    request.build_absolute_uri(reverse("purchase:finished")))
            else:
                payment_link = None
            build_invoice(record, request)
            html_context = {
                "payer": record.payer,
                "students_list": get_students_list(record),
                "mail": True,
                "payment_link": payment_link
            }
            plain_context = {
                "payer": record.payer,
                "students_list": record.students.all(),
                "mail": True
            }
            html_content = render_to_string("purchase/mail/html_mail.html",
                                            html_context,
                                            request=request)
            text_content = strip_tags(
                render_to_string("purchase/mail/text_mail.html",
                                 plain_context))
            mail = EmailMultiAlternatives(
                subject="Новая покупка",
                body=text_content,
                from_email=EMAIL_PAYMENT_NOTIFICATION_USER,
                to=STAFF_MAILS + [record.payer.email()])
            with open(BASE_DIR / "static" / "css" / "mail.css", 'r') as css:
                css = css.read().replace('\n', '')
                mail.attach_alternative(transform(html_content, css_text=css),
                                        'text/html')  # Attach html version

            # Attach files
            for student in record.students.all():
                archive_name = student.folder_path / f"{student.name}.zip"
                with ZipFile(archive_name, "w") as archive:
                    archive.write(
                        student.passport_path,
                        STUDENT_PASSPORT + student.passport_path.suffix)
                    archive.write(
                        student.study_document_path,
                        STUDY_DOCUMENT + student.study_document_path.suffix)
                with open(archive_name, "rb") as archive:
                    mail.attach(archive_name.name, archive.read())
                archive_name.unlink()

            mail.attach(INVOICE + record.invoice_path.suffix,
                        record.invoice_path.read_bytes())
            if record.get_individual_payer_or_none() is not None:
                mail.attach(PAYER_PASSPORT + record.payer.passport_path.suffix,
                            record.payer.passport_path.read_bytes())

            result = mail.send()

            request.session["allow_media"] = record.id
            delete_session_purchase_record(request)
            if not record.finished:
                record.finish()

            if result:
                if payment_type == "payme":
                    return redirect("purchase:payme-payment")
                else:
                    return redirect("purchase:finished")
            else:
                return HttpResponseServerError(
                    _("Что-то пошло не так при оформлении заказа. Разработчик был уведомлён об ошибке. Приносим свои извинения"
                      ))

    form = PaymentForm(instance=record)

    context = {
        "record": record,
        "form": form,
    }

    return render(request, "purchase/payment-form.html", context)
Example #36
0
    def submit(self):
        subscriptions = self.subscriptions.filter(subscribed=True)

        logger.info(ugettext(u"Submitting %(submission)s to %(count)d people"),
                    {
                        'submission': self,
                        'count': subscriptions.count()
                    })

        assert self.publish_date < now(), \
            'Something smells fishy; submission time in future.'

        self.sending = True
        self.save()

        try:
            (subject_template, text_template, html_template) = \
                self.message.newsletter.get_templates('message')

            for subscription in subscriptions:
                variable_dict = {
                    'subscription': subscription,
                    'site': Site.objects.get_current(),
                    'submission': self,
                    'message': self.message,
                    'newsletter': self.newsletter,
                    'date': self.publish_date,
                    'STATIC_URL': settings.STATIC_URL,
                    'MEDIA_URL': settings.MEDIA_URL
                }

                unescaped_context = Context(variable_dict, autoescape=False)

                message = EmailMultiAlternatives(
                    subject_template.render(unescaped_context),
                    text_template.render(unescaped_context),
                    from_email=self.newsletter.get_sender(),
                    to=[subscription.get_recipient()])

                if html_template:
                    escaped_context = Context(variable_dict)

                    message.attach_alternative(
                        html_template.render(escaped_context), "text/html")

                try:
                    logger.debug(ugettext(u'Submitting message to: %s.'),
                                 subscription)

                    message.send()

                except Exception, e:
                    # TODO: Test coverage for this branch.
                    logger.error(
                        ugettext(u'Message %(subscription)s failed '
                                 u'with error: %(error)s'), {
                                     'subscription': subscription,
                                     'error': e
                                 })

            self.sent = True
Example #37
0
import os
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
if __name__ == '__main__':
    subject, from_email, to = '来自www.liujiangblog.com的测试邮件', '*****@*****.**', '*****@*****.**'
    text_content = '欢迎访问www.liujiangblog.com,这里是刘江的博客和教程站点,专注于Python和Django技术的分享!'
    html_content = '<p>欢迎访问<a href="http://www.liujiangblog.com" target=blank>www.liujiangblog.com</a>,这里是刘江的博客和教程站点,本站专注于Python、Django和机器学习技术的分享!</p>'
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
Example #38
0
def confirm(request):
    subs = [['Login', 'cadastramento de usuário'], ['OK', 'tudo certo!'],
            ['ERRO', 'ha algo de arrado']]
    erro = None
    url = "https://fsfwefdefeeddfcef.herokuapp.com/register"

    if request.method == "POST":
        #pegou o email do user
        email = request.POST.get('email')
        senha = request.POST.get('senha')

        if email != None and senha == None:
            data = {'email': email}
            try:
                tk = requests.post(url=url, data=data)
            except:
                erro = 'problemas de conexão ao servidor, recarregue a pagina e tente novamente'
                return render(
                    request, 'index.html',
                    dict(view='login.html',
                         title=title,
                         subtitle=subs[0],
                         mode="1",
                         email=email,
                         erro=erro))

            turl = siteurl + "confirm?" + tk.text
            htmlEmail = """<h3>Termine seu cadastro na NinosApp </h3>
            <p>Para terminar seu cadrastro, <a href="{turl}">click aqui</a><p><br/>
            <p><font color="#f00">obs: </font> você tem apenas 10 minutos para realizar seu cadastro, caso nao seja confirmado, acesse {url} e faça esta etapa novamente
            </p><br/>
            <small>Esta é uma menssagem enviada altomaticamente. Por favor não responsa.</small>""".format(
                url=siteurl, turl=turl)
            sub = "termine seu cadastro na NinosApp"
            text_content = ''
            f = '*****@*****.**'

            try:
                msg = EmailMultiAlternatives(sub, text_content, f, [email])
                msg.attach_alternative(htmlEmail, 'text/html')
                msg.send()
            except:
                erro = 'email invalido!'
                return render(
                    request, 'index.html',
                    dict(view='login.html',
                         title=title,
                         subtitle=subs[0],
                         mode="1",
                         erro=erro))

            return render(
                request, 'index.html',
                dict(view='next.html',
                     title=title,
                     subtitle=subs[1],
                     form={"token": tk.text}))

        else:
            return redirect('home')
    elif request.method == "GET":
        token = request.GET.get('t')
        if token == None:
            return render(
                request, 'index.html',
                dict(title=title, view='error.html', e=0, erro='ERRO 404'))
        else:
            try:
                url = "https://fsfwefdefeeddfcef.herokuapp.com/register"
                tk = requests.post(url=url)
            except:
                return render(
                    request, 'index.html',
                    dict(title=title,
                         view='error.html',
                         subtitle=subs[2],
                         e=1,
                         erro='codigo de confirmação inválido'))
    else:
        return redirect('home')
Example #39
0
def send_now(users, label, extra_context=None, on_site=True, preference=None):
    """
    Creates a new notice.

    This is intended to be how other apps create new notices.

    notification.send(user, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )
    
    You can pass in on_site=False to prevent the notice emitted from being
    displayed on the site.
    """
    if extra_context is None:
        extra_context = {}

    notice_type = NoticeType.objects.get(label=label)

    current_site = Site.objects.get_current()
    notices_url = u"http://%s%s" % (
        unicode(current_site),
        reverse("notification_notices"),
    )

    current_language = get_language()

    formats = (
        'short.txt',
        'full.txt',
        'notice.html',
        'full.html',
    )  # TODO make formats configurable

    for user in users:
        if preference:
            if user.get_profile().get_preference(preference) == "off":
                continue

        recipients = []
        # get user language for user from language store defined in
        # NOTIFICATION_LANGUAGE_MODULE setting
        try:
            language = get_notification_language(user)
        except LanguageStoreNotAvailable:
            language = None

        if language is not None:
            # activate the user's language
            activate(language)

        # update context with user specific translations
        context = Context({
            "user": user,
            "notice": ugettext(notice_type.display),
            "notices_url": notices_url,
            "current_site": current_site,
        })
        context.update(extra_context)

        # get prerendered format messages
        messages = get_formatted_messages(formats, label, context)

        # Strip newlines from subject
        subject = ''.join(
            render_to_string('notification/email_subject.txt', {
                'message': messages['short.txt'],
            }, context).splitlines())

        body_html = render_to_string('notification/email_body.html', {
            'message': messages['full.txt'],
        }, context)

        body_txt = render_to_string('notification/email_body.txt', {
            'message': messages['full.txt'],
        }, context)

        notice = Notice.objects.create(user=user,
                                       message=body_html,
                                       notice_type=notice_type,
                                       on_site=on_site)
        if should_send(user, notice_type, "1") and user.email:  # Email
            recipients.append(user.email)
        # send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, recipients)
        # tutaj wysylany jest mail!!!

        msg = EmailMultiAlternatives(subject, body_txt,
                                     settings.DEFAULT_FROM_EMAIL, [
                                         user.email,
                                     ])
        msg.attach_alternative(body_html, "text/html")
        msg.send(fail_silently=True)

    # reset environment to original language
    activate(current_language)
def receive_sms(request):
    # TODO - secure this callback
    sender = request.POST.get('From')
    message = request.POST.get('Body')

    STOP_LIST = ['STOP', 'STOPALL', 'UNSUBSCRIBE', 'CANCEL', 'END', 'QUIT']
    command = message.strip(string.punctuation + string.whitespace).upper()
    opt_out = command in STOP_LIST
    if opt_out:
        application_mobile_opt_out(sender)
        return http.HttpResponse(status=200)

    START_LIST = ['START', 'YES', 'UNSTOP']
    opt_in = command in START_LIST
    if opt_in:
        application_mobile_opt_out_revert(sender)
        return http.HttpResponse(status=200)

    to = []
    bcc = None
    subject = 'New SMS reply from {0}'.format(sender)
    context = {
        'message': message,
        'sender': sender,
    }

    # Only forward message to facilitator if there is a meeting in the future-ish
    today = datetime.datetime.now().date()
    yesterday = today - datetime.timedelta(days=1)
    meetings = Meeting.objects.active().filter(meeting_date__gte=yesterday)
    signups = Application.objects.active().filter(
        Q(mobile=sender) & Q(mobile_opt_out_at__isnull=True)
        & Q(study_group__in=meetings.values('study_group')))

    # TODO handle user signed up to 2 learning circles
    if signups.count() == 1:
        signup = signups.first()
        context['signup'] = signup
        # TODO i18n
        subject = 'New SMS reply from {0} <{1}>'.format(signup.name, sender)
        to += [signup.study_group.facilitator.email]
        next_meeting = signups.first().study_group.next_meeting()
        # TODO - replace this check with a check to see if the meeting reminder has been sent
        if next_meeting and next_meeting.meeting_datetime() - timezone.now(
        ) < datetime.timedelta(days=2):
            context['next_meeting'] = next_meeting
            context['rsvp_yes'] = next_meeting.rsvp_yes_link(sender)
            context['rsvp_no'] = next_meeting.rsvp_no_link(sender)

    text_body = render_to_string_ctx('studygroups/email/incoming_sms.txt',
                                     context)
    html_body = render_to_string_ctx('studygroups/email/incoming_sms.html',
                                     context)
    if len(to) == 0:
        to = [a[1] for a in settings.ADMINS]
    else:
        bcc = [a[1] for a in settings.ADMINS]

    notification = EmailMultiAlternatives(subject, text_body,
                                          settings.DEFAULT_FROM_EMAIL, to, bcc)
    notification.attach_alternative(html_body, 'text/html')
    notification.send()
    return http.HttpResponse(status=200)
Example #41
0
def send_new_answer_payload(sender, instance, created, **kwargs):
    answer = instance
    writeitinstance = answer.message.writeitinstance

    if created:
        connection = writeitinstance.config.get_mail_connection()
        new_answer_template = writeitinstance.new_answer_notification_template

        with override(None, deactivate=True):
            message_url = reverse('thread_read',
                                  subdomain=writeitinstance.slug,
                                  kwargs={'slug': answer.message.slug})

        context = {
            'author_name': answer.message.author_name,
            'person': answer.person.name,
            'subject': answer.message.subject,
            'content': answer.content,
            'message_url': message_url,
            'site_name': answer.message.writeitinstance.name,
        }

        subject = new_answer_template.get_subject_template().format(**context)
        text_content = new_answer_template.get_content_template().format(
            **context)
        html_content = new_answer_template.template_html.format(
            **escape_dictionary_values(context))

        if settings.SEND_ALL_EMAILS_FROM_DEFAULT_FROM_EMAIL:
            from_email = settings.DEFAULT_FROM_EMAIL
        else:
            from_domain = writeitinstance.config.custom_from_domain or settings.DEFAULT_FROM_DOMAIN
            from_email = "%s@%s" % (
                writeitinstance.slug,
                from_domain,
            )

        subscribers = answer.message.subscribers.all()

        if writeitinstance.config.notify_owner_when_new_answer:
            subscribers = chain(subscribers, (writeitinstance.owner, ))

        for subscriber in subscribers:
            msg = EmailMultiAlternatives(
                subject.strip(),
                text_content,
                from_email,
                [subscriber.email],
                connection=connection,
            )
            if html_content:
                msg.attach_alternative(html_content, "text/html")
            msg.send()

        # Webhooks
        payload = {
            'message_id': '/api/v1/message/{0}/'.format(answer.message.id),
            'content': answer.content,
            'person': answer.person.name,
            'person_id': answer.person.popit_url,
        }

        for webhook in writeitinstance.answer_webhooks.all():
            requests.post(webhook.url, data=payload)
Example #42
0
    def send_activation_email(self, site, request=None):
        """
        Send an activation email to the user associated with this
        ``RegistrationProfile``.

        The activation email will make use of two templates:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. Because it is used as the subject line of an email,
            this template's output **must** be only a single line of
            text; output longer than one line will be forcibly joined
            into only a single line.

        ``registration/activation_email.txt``
            This template will be used for the text body of the email.

        ``registration/activation_email.html``
            This template will be used for the html body of the email.

        These templates will each receive the following context
        variables:

        ``user``
            The new user account

        ``activation_key``
            The activation key for the new account.

        ``expiration_days``
            The number of days remaining during which the account may
            be activated.

        ``site``
            An object representing the site on which the user
            registered; depending on whether ``django.contrib.sites``
            is installed, this may be an instance of either
            ``django.contrib.sites.models.Site`` (if the sites
            application is installed) or
            ``django.contrib.sites.models.RequestSite`` (if
            not). Consult the documentation for the Django sites
            framework for details regarding these objects' interfaces.

        ``request``
            Optional Django's ``HttpRequest`` object from view.
            If supplied will be passed to the template for better
            flexibility via ``RequestContext``.
        """
        ctx_dict = {}
        if request is not None:
            ctx_dict = RequestContext(request, ctx_dict)
        # update ctx_dict after RequestContext is created
        # because template context processors
        # can overwrite some of the values like user
        # if django.contrib.auth.context_processors.auth is used
        ctx_dict.update({
            'user': self.user,
            'activation_key': self.activation_key,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
            'site': site,
        })
        subject = getattr(settings, 'REGISTRATION_EMAIL_SUBJECT_PREFIX', '') + \
                  render_to_string('registration/activation_email_subject.txt', ctx_dict)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())

        message_txt = render_to_string('registration/activation_email.txt',
                                       ctx_dict)
        email_message = EmailMultiAlternatives(subject, message_txt,
                                               settings.DEFAULT_FROM_EMAIL,
                                               [self.user.email])

        try:
            message_html = render_to_string(
                'registration/activation_email.html', ctx_dict)
        except TemplateDoesNotExist:
            message_html = None

        if message_html:
            email_message.attach_alternative(message_html, 'text/html')

        email_message.send()
Example #43
0
    def post(self, request, *args, **kwargs):
        order_form = OrderForm(request.POST)

        if order_form.is_valid():
            name = order_form.cleaned_data['name']
            email = order_form.cleaned_data['email']
            phone = order_form.cleaned_data['phone_hidden']

            product = order_form.cleaned_data['product']
            product_language = order_form.cleaned_data['language']
            product_occasion = order_form.cleaned_data['occasion']
            product_date = order_form.cleaned_data['date']
            product_recipient = order_form.cleaned_data['recipient']
            product_relationship = order_form.cleaned_data['relationship']
            product_style = order_form.cleaned_data['style']
            message = order_form.cleaned_data['message']
            message = message.replace('\r\n', '\n                ')

            sayit_email = os.environ['EMAIL_HOST_USER']

            # Construct email subject
            today = str(datetime.today())
            today_date = today[2:10].replace('-', '')
            today_sec = today[-9:-7]
            invoice_number = '{0}-{1}-{2}'.format(today_date, name[:2].upper(),
                                                  today_sec)
            subject = 'Say It With a Song Order #{0}'.format(invoice_number)

            # Assemble plain text email body
            text_welcome = '''\
                Thanks for contacting Say It With a Song. \
                We're excited to work with you!
                We will be in touch within 48 hours. \
                For your records, please see a copy of your order below.'''
            text_contact = '''\
                Contact Information\n
                Name: {0}
                Email: {1}
                Phone: {2}'''.format(name, email, phone)
            text_product = '''\
                Order Information\n
                Product: {0}
                Language: {1}
                Occasion: {2}
                Date: {3}
                Recipient: {4}
                Relationship to Recipient: {5}
                Style: {6}
                Message:
                {7}'''.format(product, product_language, product_occasion,
                              product_date, product_recipient,
                              product_relationship, product_style, message)
            text_closing = '''\
                Sincerely yours,
                Rachel Sparrow
            '''
            text_content_business = '{0}{1}'.format(dedent(text_contact),
                                                    dedent(text_product))
            text_content_customer = '{0}{1}{2}'.format(dedent(text_welcome),
                                                       text_content_business,
                                                       dedent(text_closing))

            # Assemble HTML email body
            html_welcome = '''
                <p>Thanks for contacting Say It With a Song.
                We're excited to work with you!
                We will be in touch within 48 hours.<br>
                For your records, please see a copy of your order below.</p>'''
            html_contact = '''
                <p>Contact Information</p>
                <ul>
                    <li>Name: {0}</li>
                    <li>Email: {1}</li>
                    <li>Phone: {2}</li>
                </ul>'''.format(name, email, phone)
            html_product = '''
                <p>Order Information</p>
                <ul>
                    <li>Product: {0}</li>
                    <li>Language: {1}</li>
                    <li>Occasion: {2}</li>
                    <li>Date: {3}</li>
                    <li>Recipient: {4}</li>
                    <li>Relationship to Recipient: {5}</li>
                    <li>Style: {6}</li>
                    <li>Message: {7}</li>
                </ul>'''.format(product, product_language, product_occasion,
                                product_date, product_recipient,
                                product_relationship, product_style, message)
            html_closing = '''
            <p>Sincerely yours,<br>
            Rachel Sparrow</p>
            '''
            html_content_business = '{0}{1}'.format(dedent(html_contact),
                                                    dedent(html_product))
            html_content_customer = '{0}{1}{2}'.format(dedent(html_welcome),
                                                       html_content_business,
                                                       dedent(html_closing))

            # Create email for business
            msg_business = EmailMultiAlternatives(
                subject=subject,
                body=text_content_business,
                from_email='{0} <{1}>'.format(name, email),
                to=[sayit_email],
                headers={'Reply-To': '{0} <{1}>'.format(name, email)})
            msg_business.attach_alternative(html_content_business, 'text/html')

            # Create messsage for customer
            msg_customer = EmailMultiAlternatives(
                subject=subject,
                body=text_content_customer,
                from_email='Say It With a Song <{0}>'.format(sayit_email),
                to=[email],
                headers={
                    'Reply-To':
                    '{0} <{1}>'.format('Say It With a Song', sayit_email)
                })
            msg_customer.attach_alternative(html_content_customer, 'text/html')

            try:
                msg_business.send()
                msg_customer.send()
                self.add_message('Your order was sent!',
                                 level=messages.SUCCESS)
                return self.form_valid(order_form)

            except:
                self.add_message('Something went wrong. Please try again.',
                                 level=messages.ERROR)
                return self.form_invalid(order_form)

        else:
            self.add_message('Error found. Please try again.',
                             level=messages.ERROR)
            return self.form_invalid(order_form)
Example #44
0
def send_mail(subject,
              email_template_name,
              context,
              from_email,
              to_email,
              verified,
              cc_list=None,
              bcc_list=None):
    """
    :param subject: string
    :param email_template_name: string
    :param context: string
    :param from_email: mail id
    :param to_email: mail id or list of mail ids
    :param verified: string
    :param cc_list: mail id or list of mail ids
    :param bcc_list: mail id or list of mail ids
    :return:
    """
    mfrom = settings.DEFAULT_FROM_EMAIL
    if verified:
        mail_sender = settings.MAIL_SENDER
    else:
        mail_sender = settings.INACTIVE_MAIL_SENDER
    htmly = loader.get_template(email_template_name)

    html_content = htmly.render(context)
    recipients = [to_email]
    if isinstance(to_email, list):
        recipients = to_email
    ccs = list()
    if cc_list:
        ccs = [cc_list]
        if isinstance(cc_list, list):
            ccs = cc_list
    bccs = list()
    if bcc_list:
        bccs = [bcc_list]
        if isinstance(bcc_list, list):
            bccs = bcc_list
    for email in recipients + ccs + bccs:
        is_valid = validate_email(email, check_mx=True)
        if not is_valid:
            raise ValueError("{} is not a valid email".format(email))
    if mail_sender == 'AMAZON':
        client = boto3.client(
            'ses',
            aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
            aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
        recipients = [to_email]
        if isinstance(to_email, list):
            recipients = to_email
        try:
            response = client.send_email(
                Destination={
                    'ToAddresses': recipients,
                    'CcAddresses': ccs,
                    'BccAddresses': bccs
                },
                Message={
                    'Body': {
                        'Html': {
                            'Charset': "UTF-8",
                            'Data': htmly,
                        }
                    },
                    'Subject': {
                        'Charset': "UTF-8",
                        'Data': subject,
                    },
                },
                Source=from_email,
            )
            return {
                'message': 'Mail sent',
                'data': response['ResponseMetadata']['RequestId']
            }
        except ClientError as e:
            raise e.response['Error']['Message']
    elif mail_sender == 'MAILGUN':
        try:
            response = requests.post(settings.MGUN_API_URL,
                                     auth=('api', settings.MGUN_API_KEY),
                                     data={
                                         'from': mfrom,
                                         'to': recipients,
                                         'subject': subject,
                                         "cc": ccs,
                                         "bcc": bccs,
                                         'html': html_content,
                                     })
            return {'message': 'Mail sent', 'data': response.json()}
        except Exception:
            raise Exception

    elif mail_sender == 'SENDGRID':
        import sendgrid
        sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD)
        sending_msg = sendgrid.Mail()
        if bcc_list:
            if isinstance(bcc_list, list):
                for bcc_mail in bcc_list:
                    sending_msg.add_bcc(bcc_email=bcc_mail)
            else:
                sending_msg.add_bcc(bcc_email=bcc_list)
        if cc_list:
            if isinstance(cc_list, list):
                for cc_mail in cc_list:
                    sending_msg.add_cc(cc_email=cc_mail)
            else:
                sending_msg.add_cc(cc_email=cc_list)
        sending_msg.set_subject(subject)
        sending_msg.set_html(html_content)
        sending_msg.set_text(subject)
        sending_msg.set_from(from_email)
        sending_msg.add_to(to_email)
        try:
            response = sg.send(sending_msg)
            return {'message': 'Mail sent', 'data': response}
        except Exception:
            raise Exception
    elif mail_sender == 'MAILJET':
        from mailjet_rest import Client
        API_KEY = settings.MJ_APIKEY_PUBLIC
        API_SECRET = settings.MJ_APIKEY_PRIVATE
        mailjet = Client(auth=(API_KEY, API_SECRET), version='v3.1')
        to_list = list()
        for recipient in recipients:
            to_list.append({
                "Email": recipient,
                "Name": ''.join(recipient.split('@')[0].split('.'))
            })
        ccs_list = list()
        for recipient in ccs:
            ccs_list.append({
                "Email": recipient,
                "Name": ''.join(recipient.split('@')[0].split('.'))
            })
        bccs_list = list()
        for recipient in bccs:
            bccs_list.append({
                "Email":
                recipient,
                "Name":
                ''.join(recipient.split('@')[0].split('.'))
            })
        data = {
            'Messages': [{
                "From": {
                    "Email": from_email,
                    "Name": "Me"
                },
                "To": to_list,
                "Cc": ccs_list,
                'Bcc': bccs_list,
                "Subject": subject,
                "HTMLPart": html_content
            }]
        }
        try:
            result = mailjet.send.create(data=data)
            return {'message': 'Mail sent', 'data': result.json()}
        except Exception:
            raise Exception
    else:
        msg = EmailMultiAlternatives(subject,
                                     html_content,
                                     from_email,
                                     recipients,
                                     cc=ccs,
                                     bcc=bccs)
        msg.attach_alternative(html_content, "text/html")
        try:
            response = msg.send()
            return {'message': 'Mail sent', 'data': response}
        except Exception:
            raise Exception
Example #45
0
def send_confirmation_email(sender, instance, created, **kwargs):
    confirmation = instance
    if created:
        confirmation_url = reverse(
            'confirm',
            subdomain=confirmation.message.writeitinstance.slug,
            kwargs={'slug': confirmation.key},
        )
        message_full_url = confirmation.message.get_absolute_url()
        plaintext = confirmation.message.writeitinstance.confirmationtemplate.get_content_template(
        )
        htmly = confirmation.message.writeitinstance.confirmationtemplate.content_html
        subject = confirmation.message.writeitinstance.confirmationtemplate.get_subject_template(
        )
        subject = subject.rstrip()

        context = {
            'author_name': confirmation.message.author_name_for_display,
            'site_name': confirmation.message.writeitinstance.name,
            'subject': confirmation.message.subject,
            'content': confirmation.message.content,
            'recipients':
            u', '.join([x.name for x in confirmation.message.people]),
            'confirmation_url': confirmation_url,
            'message_url': message_full_url,
        }

        text_content = template_with_wrap(plaintext, context)
        subject = subject.format(**context)
        html_content = htmly.format(**escape_dictionary_values(context))

        if settings.SEND_ALL_EMAILS_FROM_DEFAULT_FROM_EMAIL:
            from_email = settings.DEFAULT_FROM_EMAIL
        else:
            from_domain = confirmation.message.writeitinstance.config.custom_from_domain\
                or settings.DEFAULT_FROM_DOMAIN
            from_email = "%s@%s" % (
                confirmation.message.writeitinstance.slug,
                from_domain,
            )
        real_name = \
            confirmation.message.writeitinstance.config.real_name_for_site_emails
        if real_name:
            from_email = u'{real_name} <{email}>'.format(real_name=real_name,
                                                         email=from_email)

        connection = confirmation.message.writeitinstance.config.get_mail_connection(
        )

        msg = EmailMultiAlternatives(
            subject,
            text_content,
            from_email,
            [confirmation.message.author_email],
            connection=connection,
        )

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

        msg.send()
import django
import sys
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'carebackend.settings'
sys.path.append(os.path.dirname(__file__) + '/..')
django.setup()
from django.core.mail import EmailMultiAlternatives
from django.core import mail

if len(sys.argv) < 4:
    print("Missing args: Format is ADDRESS SUBJECT FILE")
    exit()
to_address = sys.argv[1]
subject = sys.argv[2]
file = sys.argv[3]

with open(file, 'r') as f:
    body = f.read()

with mail.get_connection() as connection:
    message = EmailMultiAlternatives(
        subject=subject,
        body=body,
        from_email="SavingChinatown Team <*****@*****.**>",
        to=[to_address],
        bcc=['*****@*****.**'],
        connection=connection,
    )
    message.send()
    print("Sent email to", to_address)
def Register(request):

    # if user logged in redirect to the home page
    if request.session.get('email'):
        messages.add_message(request, messages.INFO,
                             f'You are already logged in.')
        return redirect('home_page')

    # if user not logged in & submit the register form
    if request.method == 'POST':

        # get the form data from all input fields
        name = request.POST.get('name')
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')

        # check username is unique or not
        checkUsername = Users.objects.filter(username=username)

        # if username already exists - user stay on register page & display info to user
        if checkUsername:
            messages.add_message(request, messages.WARNING,
                                 f'This Username is already taken!')
            return redirect('register_page')

        # if username is unique, check email is unique or not
        else:
            checkemail = Users.objects.filter(email=email)

            # if email is already exists - user stay on register page & display info to user
            if checkemail:
                messages.add_message(request, messages.WARNING,
                                     'This Email is already Exists!')
                return redirect('register_page')

            # if both username and email is unique
            # user account created
            else:

                # send mail to the user email address
                subject, from_email, to = 'Verify your Email Address', '*****@*****.**', email
                text_content = 'This is an important message.'
                html_content = f'''
                    <h1 style="font-family: 'Lexend Deca', sans-serif; font-weight: bold; font-size: 30px; color: #8B78E6; text-align: center;"> Discus Question </h1>
                    <p style="font-family: 'Roboto', sans-serif; font-size: 18px; padding: 0 200px; margin: 13px 0; margin-bottom: 20px;">
                        We need to verify your email address. We have sent an email to {email} to verify your address. Please click the link below to verify your email address.
                    </p>
                    <div style="text-align: center; font-family: 'Roboto', sans-serif;">
                        <a href="{DOMAIN}/verify/{username}/{verifyStr}" style="text-decoration: none; background: #8B78E6; color: #fff; border: none; padding: 10px 20px; padding-bottom: 20px; font-size: 17px;">Verify your Email</a>
                    </div>
                '''
                msg = EmailMultiAlternatives(
                    subject, text_content, from_email, [to])
                msg.attach_alternative(html_content, "text/html")
                msg.send()


                # random verify string
                lst = [random.choice(string.ascii_letters + string.digits)
                       for n in range(50)]
                verifyStr = "".join(lst)


                # random change password string
                s = [random.choice(string.ascii_letters + string.digits)
                     for n in range(80)]
                change_pass_str = "".join(s)


                # encrypt password
                enc_password = pbkdf2_sha256.encrypt(
                    password, rounds=12000, salt_size=32)

                # find user location
                r = requests.get('https://api.ipdata.co?api-key=test').json()
                location = r['country_name']

                # sava data to the database and the user account created
                newUser = Users(name=name, username=username,
                                email=email, password=enc_password, verify=verifyStr, location=location, change_pass_str=change_pass_str)
                newUser.save()

                # After creating user account, redirect to the home page
                messages.add_message(request, messages.SUCCESS,
                                     'Your Accound has been created successfully. Now you can login to your account after verifying email.')
                return redirect('home_page')

    # if user not logged in simply render register.html page
    else:
        return render(request, 'MainApp/register.html', ({
            "title": "Register",
            "page": "register"
        }))
Example #48
0
    def run(self):
        msg = EmailMultiAlternatives(self.subject, self.text, to=(self.to, ),
                                     headers=self.headers)

        msg.attach_alternative(self.html, "text/html")
        msg.send()
Example #49
0
def send_templated_mail(template_name,
                        email_context,
                        recipients,
                        sender=None,
                        bcc=None,
                        fail_silently=False,
                        files=None):
    """
    send_templated_mail() is a warpper around Django's e-mail routines that
    allows us to easily send multipart (text/plain & text/html) e-mails using
    templates that are stored in the database. This lets the admin provide
    both a text and a HTML template for each message.

    template_name is the slug of the template to use for this message (see
        models.EmailTemplate)

    email_context is a dictionary to be used when rendering the template

    recipients can be either a string, eg '*****@*****.**', or a list of strings.

    sender should contain a string, eg 'My Site <*****@*****.**>'. If you leave it
        blank, it'll use settings.DEFAULT_FROM_EMAIL as a fallback.

    bcc is an optional list of addresses that will receive this message as a
        blind carbon copy.

    fail_silently is passed to Django's mail routine. Set to 'True' to ignore
        any errors at send time.

    files can be a list of tuple. Each tuple should be a filename to attach, 
        along with the File objects to be read. files can be blank.

    """
    from django import VERSION
    from django.conf import settings
    from django.core.mail import EmailMultiAlternatives
    from django.template import loader, Context

    from helpdesk.models import EmailTemplate
    from helpdesk.settings import HELPDESK_EMAIL_SUBJECT_TEMPLATE
    import os

    # RemovedInDjango110Warning: render() must be called with a dict, not a Context.
    if VERSION >= (1, 8):
        context = email_context
    else:
        context = Context(email_context)

    if hasattr(context['queue'], 'locale'):
        locale = getattr(context['queue'], 'locale', '')
    else:
        locale = context['queue'].get('locale', 'en')
    if not locale:
        locale = 'en'

    t = None
    try:
        t = EmailTemplate.objects.get(template_name__iexact=template_name,
                                      locale=locale)
    except EmailTemplate.DoesNotExist:
        pass

    if not t:
        try:
            t = EmailTemplate.objects.get(template_name__iexact=template_name,
                                          locale__isnull=True)
        except EmailTemplate.DoesNotExist:
            logger.warning('template "%s" does not exist, no mail sent' %
                           template_name)
            return  # just ignore if template doesn't exist

    if not sender:
        sender = settings.DEFAULT_FROM_EMAIL

    footer_file = os.path.join('helpdesk', locale, 'email_text_footer.txt')

    # get_template_from_string was removed in Django 1.8 http://django.readthedocs.org/en/1.8.x/ref/templates/upgrading.html
    try:
        from django.template import engines
        template_func = engines['django'].from_string
    except ImportError:  # occurs in django < 1.8
        template_func = loader.get_template_from_string

    text_part = template_func("%s{%% include '%s' %%}" %
                              (t.plain_text, footer_file)).render(context)

    email_html_base_file = os.path.join('helpdesk', locale,
                                        'email_html_base.html')
    ''' keep new lines in html emails '''
    from django.utils.safestring import mark_safe

    if 'comment' in context:
        html_txt = context['comment']
        html_txt = html_txt.replace('\r\n', '<br>')
        context['comment'] = mark_safe(html_txt)

    # get_template_from_string was removed in Django 1.8 http://django.readthedocs.org/en/1.8.x/ref/templates/upgrading.html
    html_part = template_func(
        "{%% extends '%s' %%}{%% block title %%}%s{%% endblock %%}{%% block content %%}%s{%% endblock %%}"
        % (email_html_base_file, t.heading, t.html)).render(context)

    # get_template_from_string was removed in Django 1.8 http://django.readthedocs.org/en/1.8.x/ref/templates/upgrading.html
    subject_part = template_func(HELPDESK_EMAIL_SUBJECT_TEMPLATE % {
        "subject": t.subject,
    }).render(context)

    if isinstance(recipients, str):
        if recipients.find(','):
            recipients = recipients.split(',')
    elif type(recipients) != list:
        recipients = [
            recipients,
        ]

    msg = EmailMultiAlternatives(subject_part.replace('\n',
                                                      '').replace('\r', ''),
                                 text_part,
                                 sender,
                                 recipients,
                                 bcc=bcc)
    msg.attach_alternative(html_part, "text/html")

    if files:
        for attachment in files:
            file_to_attach = attachment[1]
            file_to_attach.open()
            msg.attach(filename=attachment[0], content=file_to_attach.read())
            file_to_attach.close()

    return msg.send(fail_silently)
Example #50
0
    def send_activation_email(self, site, request=None):
        """
        Send an activation email to the user associated with this
        ``RegistrationProfile``.

        The activation email will use the following templates,
        which can be overriden by setting ACTIVATION_EMAIL_SUBJECT,
        ACTIVATION_EMAIL_BODY, and ACTIVATION_EMAIL_HTML appropriately:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. Because it is used as the subject line of an email,
            this template's output **must** be only a single line of
            text; output longer than one line will be forcibly joined
            into only a single line.

        ``registration/activation_email.txt``
            This template will be used for the text body of the email.

        ``registration/activation_email.html``
            This template will be used for the html body of the email.

        These templates will each receive the following context
        variables:

        ``user``
            The new user account

        ``activation_key``
            The activation key for the new account.

        ``expiration_days``
            The number of days remaining during which the account may
            be activated.

        ``site``
            An object representing the site on which the user
            registered; depending on whether ``django.contrib.sites``
            is installed, this may be an instance of either
            ``django.contrib.sites.models.Site`` (if the sites
            application is installed) or
            ``django.contrib.sites.requests.RequestSite`` (if
            not). Consult the documentation for the Django sites
            framework for details regarding these objects' interfaces.

        ``request``
            Optional Django's ``HttpRequest`` object from view.
            If supplied will be passed to the template for better
            flexibility via ``RequestContext``.
        """
        activation_email_subject = getattr(
            settings, 'ACTIVATION_EMAIL_SUBJECT',
            'registration/activation_email_subject.txt')
        activation_email_body = getattr(settings, 'ACTIVATION_EMAIL_BODY',
                                        'registration/activation_email.txt')
        activation_email_html = getattr(settings, 'ACTIVATION_EMAIL_HTML',
                                        'registration/activation_email.html')

        ctx_dict = {
            'user': self.user,
            'activation_key': self.activation_key,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
            'site': site,
        }
        prefix = getattr(settings, 'REGISTRATION_EMAIL_SUBJECT_PREFIX', '')
        subject = prefix + render_to_string(
            activation_email_subject, ctx_dict, request=request)

        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        from_email = get_from_email(site)
        message_txt = render_to_string(activation_email_body,
                                       ctx_dict,
                                       request=request)

        email_message = EmailMultiAlternatives(subject, message_txt,
                                               from_email, [self.user.email])

        if getattr(settings, 'REGISTRATION_EMAIL_HTML', True):
            try:
                message_html = render_to_string(activation_email_html,
                                                ctx_dict,
                                                request=request)
            except TemplateDoesNotExist:
                pass
            else:
                email_message.attach_alternative(message_html, 'text/html')

        email_message.send()
Example #51
0
def send_stage_email(task, email_conf, token=None):
    if not email_conf:
        return

    text_template = loader.get_template(email_conf["template"],
                                        using="include_etc_templates")
    html_template = email_conf["html_template"]
    if html_template:
        html_template = loader.get_template(html_template,
                                            using="include_etc_templates")

    emails = set()
    actions = {}
    # find our set of emails and actions that require email
    for action in task.actions:
        act = action.get_action()
        email = act.get_email()
        if email:
            emails.add(email)
            actions[str(act)] = act

    if not emails:
        return

    if len(emails) > 1:
        notes = {
            "errors":
            ("Error: Unable to send update, more than one email for task: %s" %
             task.uuid)
        }
        create_notification(task, notes, error=True)
        return

    context = {"task": task, "actions": actions}
    if token:
        tokenurl = CONF.workflow.horizon_url
        if not tokenurl.endswith("/"):
            tokenurl += "/"
        tokenurl += "token/"
        context.update({"tokenurl": tokenurl, "token": token.token})

    try:
        message = text_template.render(context)

        # from_email is the return-path and is distinct from the
        # message headers
        from_email = email_conf["from"]
        if not from_email:
            from_email = email_conf["reply"]
        elif "%(task_uuid)s" in from_email:
            from_email = from_email % {"task_uuid": task.uuid}

        # these are the message headers which will be visible to
        # the email client.
        headers = {
            "X-Adjutant-Task-UUID": task.uuid,
            # From needs to be set to be disctinct from return-path
            "From": email_conf["reply"],
            "Reply-To": email_conf["reply"],
        }

        email = EmailMultiAlternatives(
            email_conf["subject"],
            message,
            from_email,
            [emails.pop()],
            headers=headers,
        )

        if html_template:
            email.attach_alternative(html_template.render(context),
                                     "text/html")

        email.send(fail_silently=False)

    except Exception as e:
        notes = {
            "errors":
            ("Error: '%s' while emailing update for task: %s" % (e, task.uuid))
        }

        notif_conf = task.config.notifications

        if e.__class__.__name__ in notif_conf.safe_errors:
            notification = create_notification(task,
                                               notes,
                                               error=True,
                                               handlers=False)
            notification.acknowledged = True
            notification.save()
        else:
            create_notification(task, notes, error=True)
def Forget_password(request):

    # if user submit the forget_password form
    if request.method == "POST":

        # get the data from input field
        email = request.POST.get('email')

        # if input field email is blank
        # display a info to user and redirect to same page

        if email == "":
            messages.add_message(request, messages.WARNING,
                                 'Please Enter your Email Address.')
            return redirect('forget_pass_page')

        # if email field is not blank
        # query the user email is exists or not

        checkemail = Users.objects.filter(email=email).count()

        # if user email is exists
        if checkemail == 1:

            # get the user object from the user email
            data = Users.objects.get(email=email)

            # send mail to the user email address
            subject, from_email, to = 'Choose a new password', '*****@*****.**', email
            text_content = ''
            html_content = f'''
                    <h1 style="font-family: 'Lexend Deca', sans-serif; font-weight: bold; font-size: 30px; color: #8B78E6; text-align: center;"> Discus Question </h1>
                    <p style="font-family: 'Roboto', sans-serif; font-size: 16px; padding: 0 200px; margin: 13px 0; margin-bottom: 20px;">
                        There was a request to change your password. <br>
                        If you did not make this request, just ignore this email. Otherwise, please click the button below to change your password.
                    </p>
                    <div style="text-align: center; font-family: 'Roboto', sans-serif;">
                        <a href="{DOMAIN}/changepassword/{data.username}/{data.change_pass_str}" style="text-decoration: none; background: #8B78E6; color: #fff; border: none; padding: 10px 20px; padding-bottom: 20px; font-size: 17px;">Change password</a>
                    </div>
                '''
            msg = EmailMultiAlternatives(
                subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

            # display info to user and redirect user to home Page
            messages.add_message(request, messages.INFO,
                                 'Mail successfully sent to your email address.Open your mailbox, There is Instructions to chnage password.')
            return redirect('home_page')

        # if user email does not exists
        else:
            messages.add_message(request, messages.WARNING,
                                 'Wrong Email Address! Please check it perfectly.')
            return redirect('forget_pass_page')

    # if user does not submit the forget_password form
    else:
        return render(request, 'MainApp/forget_password.html', ({
            "title": "Forget Password",
            "page": "forget"
        }))
Example #53
0
def send_broadcast_email(request):
    content = get_media_file_contents('generic_email.html')
    if not content:
        return HttpResponseBadRequest(
            'Generic email template not defined. Visit the customization page to upload a template.'
        )
    form = EmailBroadcastForm(request.POST)
    if not form.is_valid():
        return render(request, 'email/compose_email.html', {'form': form})
    dictionary = {
        'title': form.cleaned_data['title'],
        'greeting': form.cleaned_data['greeting'],
        'contents': form.cleaned_data['contents'],
        'template_color': form.cleaned_data['color'],
    }
    content = Template(content).render(Context(dictionary))
    users = None
    audience = form.cleaned_data['audience']
    selection = form.cleaned_data['selection']
    active_choice = form.cleaned_data['only_active_users']
    try:
        if audience == 'tool':
            users = User.objects.filter(qualifications__id=selection)
        elif audience == 'project':
            users = User.objects.filter(projects__id=selection)
        elif audience == 'account':
            users = User.objects.filter(projects__account__id=selection)
        if active_choice:
            users = users.filter(is_active=True)
    except Exception as error:
        warning_message = 'Your email was not sent. There was a problem finding the users to send the email to.'
        dictionary = {'error': warning_message}
        logger.warning(
            warning_message +
            ' audience: {}, only_active: {}. The error message that was received is: {}'
            .format(audience, active_choice, str(error)))
        return render(request, 'email/compose_email.html', dictionary)
    if not users:
        dictionary = {
            'error':
            'The audience you specified is empty. You must send the email to at least one person.'
        }
        return render(request, 'email/compose_email.html', dictionary)
    subject = form.cleaned_data['subject']
    users = [x.email for x in users]
    if form.cleaned_data['copy_me']:
        users += [request.user.email]
    try:
        email = EmailMultiAlternatives(subject,
                                       from_email=request.user.email,
                                       bcc=set(users))
        email.attach_alternative(content, 'text/html')
        email.send()
    except SMTPException as error:
        site_title = get_customization('site_title')
        error_message = f"{site_title} was unable to send the email through the email server. The error message that was received is: " + str(
            error)
        logger.exception(error_message)
        dictionary = {
            'title': 'Email not sent',
            'heading': 'There was a problem sending your email',
            'content': error_message,
        }
        return render(request, 'acknowledgement.html', dictionary)
    dictionary = {
        'title': 'Email sent',
        'heading': 'Your email was sent',
    }
    return render(request, 'acknowledgement.html', dictionary)
Example #54
0
def _send(recipient_pks,
          recipient_emails,
          template_path,
          context,
          from_email,
          fail_silently,
          extra_headers=None):
    recipients = list(get_user_model().objects.filter(pk__in=recipient_pks))
    recipients += recipient_emails

    current_language = get_language()
    current_site = Site.objects.get(id=settings.SITE_ID)

    default_context = context or {}
    default_context["current_site"] = current_site
    default_context["STATIC_URL"] = settings.STATIC_URL

    subject_path = "%s/short.txt" % template_path
    text_path = "%s/email.txt" % template_path
    html_path = "%s/email.html" % template_path

    for recipient in recipients:
        if use_threading:
            SendThread(recipient, current_language, current_site,
                       default_context, subject_path, text_path, html_path,
                       from_email, fail_silently, extra_headers).start()
            return
        # if it is user, get the email and switch the language
        if isinstance(recipient, get_user_model()):
            email = recipient.email
            try:
                language = get_users_language(recipient)
            except LanguageStoreNotAvailable:
                language = None

            if language is not None:
                # activate the user's language
                activate(language)
        else:
            email = recipient

        # populate per-recipient context
        context = default_context
        context['recipient'] = recipient
        context['email'] = email

        # load email subject, strip and remove line breaks
        subject = render_to_string(subject_path, context).strip()
        subject = "".join(subject.splitlines())  # this must be a single line
        text = render_to_string(text_path, context)

        msg = EmailMultiAlternatives(subject,
                                     text,
                                     from_email, [email],
                                     headers=extra_headers)

        # try to attach the html variant
        try:
            body = render_to_string(html_path, context)
            if pynliner:
                body = pynliner.fromString(body)
            msg.attach_alternative(body, "text/html")
        except TemplateDoesNotExist:
            logging.info("Email sent without HTML, since %s not found" %
                         html_path)

        msg.send(fail_silently=fail_silently)

        # reset environment to original language
        if isinstance(recipient, get_user_model()):
            activate(current_language)

        return msg
Example #55
0
def stripe_webhook(request):
    stripe.api_key = settings.STRIPE_SECRET_KEY
    endpoint_secret = settings.STRIPE_ENDPOINT_SECRET
    payload = request.body
    sig_header = request.META['HTTP_STRIPE_SIGNATURE']

    def fulfull_payment(session):
        product = session['metadata']['product']
        user_pk = int(session['client_reference_id'])

        log.info("stripe_webhook: user %d product %s" % (user_pk, product))

        try:
            user = User.objects.get(pk=user_pk)
        except User.DoesNotExist:
            log.exception("stripe_webhook: user %d invalid user" % user_pk)
            return HttpResponseBadRequest()

        if product == 'lite':
            subscription = Subscription.objects.get(name="AstroBin Lite 2020+")
        elif product == 'premium':
            subscription = Subscription.objects.get(
                name="AstroBin Premium 2020+")
        elif product == 'ultimate':
            subscription = Subscription.objects.get(
                name="AstroBin Ultimate 2020+")
        else:
            log.exception("stripe_webhook: user %d invalid product" % user_pk)
            return HttpResponseBadRequest()

        payment = PayPalIPN.objects.create(custom=user_pk,
                                           item_number=subscription.pk,
                                           mc_gross=subscription.price,
                                           mc_currency=subscription.currency)

        handle_payment_was_successful(payment)

    try:
        event = stripe.Webhook.construct_event(payload, sig_header,
                                               endpoint_secret)
    except Exception as e:
        log.exception("stripe_webhook: %s" % str(e))
        return HttpResponseBadRequest()

    log.info("stripe_webhook: %s" % event['type'])

    try:
        type = event['type']
        session = event['data']['object']

        if type == 'checkout.session.completed':
            fulfull_payment(session)
        elif event['type'] == 'checkout.session.async_payment_succeeded':
            log.info("stripe_webhook: payment succeeded for event %s" %
                     event['id'])
        elif event['type'] == 'checkout.session.async_payment_failed':
            log.info("stripe_webhook: payment failed for event %s" %
                     event['id'])
            msg = EmailMultiAlternatives(
                '[AstroBin] User payment failed',
                'Payment from user failed: <br/>%s' %
                json.dumps(session, indent=4, sort_keys=True),
                settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'])
            msg.send()
    except KeyError as e:
        log.exception("stripe_webhook: %s" % str(e))
        return HttpResponseBadRequest()

    return HttpResponse(status=200)
Example #56
0
def send_email_to_users(user, domain_override, email_template_name,use_https, token_generator):
    """
    input description: 
    parameter one - created user info
    parameter two - the domain name form where the email has to be sent
    parameter three - the path of the email template that needs to be rendered to send mail
    parameter four - protocol used to send mail (http or https) 
    parameter five - built in method to generate a unique token for the user
    input type: 
    parameter one - unicode
    parameter two - string
    parameter three - html
    parameter four - built in methods
    parameter five - built in methods
    action preformed: sends email on user creation
    template used: NA
    """
    try:
        a = AESCipher()
        email_obj = EmailConfiguration.objects.last()
        EMAIL_HOST = a.decrypt(email_obj.email_host)
        EMAIL_PORT = a.decrypt(email_obj.email_port)
        EMAIL_HOST_USER = a.decrypt(email_obj.email_host_user)
        EMAIL_HOST_PASSWORD = a.decrypt(email_obj.email_host_password)
        from_email = a.decrypt(email_obj.email_from_email)
        display_email = a.decrypt(email_obj.email_display_name)
        email_certs = a.decrypt(email_obj.email_certs)
        if email_certs == 'SSL':
            USE_TLS = None
            USE_SSL = True
        else:
            USE_TLS = True
            USE_SSL = None
        connection = get_connection(host=EMAIL_HOST,port=EMAIL_PORT,username=EMAIL_HOST_USER,password=EMAIL_HOST_PASSWORD,
            use_tls=USE_TLS, fail_silently=False, use_ssl=USE_SSL, timeout=None)
        connection.open()
        from_full_email = '{0} <{1}>'.format(display_email,from_email)
        if not user.email:
            raise ValueError('Email address is required to send an email')
        if not domain_override:
            domain = 'http://{0}'.format(get_ip())
            site_name = 'http://{0}'.format(get_ip())
        else:
            site_name = domain = domain_override
        t = loader.get_template(email_template_name)
        c = {
            'email': user.email,
            'name':user.username,
            'domain': domain,
            'site_name': site_name,
            'uid': urlsafe_base64_encode(str(user.id)),
            'user': user,
            'token': token_generator.make_token(user),
            'protocol': use_https and 'https' or 'http',
            'auth_token':user.auth_token
        }
        email = EmailMultiAlternatives("Welcome to Orchestron", '', from_full_email, [user.email],connection=connection)
        email.attach_alternative(t.render(c), "text/html")
        email.send()
        info_debug_log(user=user,event='Send email to users',status='success')
        connection.close()
    except:
        from_email = 'Orchestron'
        
        if not user.email:
            error_debug_log(user=user,event='Email address is not provided',status='failure')
            raise ValueError('Email address is required to send an email')
        if not domain_override:                        
            domain = 'http://{0}'.format(get_ip())
            site_name = 'http://{0}'.format(get_ip())
        else:
            site_name = domain = domain_override
        t = loader.get_template(email_template_name)
        c = {
            'email': user.email,
            'name':user.username,
            'domain': domain,
            'site_name': site_name,
            'uid': urlsafe_base64_encode(str(user.id)),
            'user': user,
            'token': token_generator.make_token(user),
            'protocol': use_https and 'https' or 'http',
            'auth_token':user.auth_token
        }
        email = EmailMultiAlternatives("Welcome to Orchestron", '', from_email, [user.email])
        email.attach_alternative(t.render(c), "text/html")
        email.send()
        info_debug_log(user=user,event='Send email to users',status='success')
Example #57
0
def send_poll_emails(request: CleanRequest) -> Response:
    '''
    Description: Envia emails para o conjunto de usuarios/emails cadastrados em uma dada eleicao com id == poll_id.
    '''
    data = request.clean_data
    admin = request.user
    #Get the desired poll.
    try:
        poll = Poll.objects.get(pk=data['poll_id'], admin=admin)
    except Poll.DoesNotExist:
        return Response({'message': 'Eleicao não encontrada'},
                        status=HTTP_404_NOT_FOUND)

    #Check if poll is valid:
    if poll.deadline < datetime.date.today():
        return Response(
            {'message': 'Eleição finalizada em {}'.format(poll.deadline)},
            status=HTTP_400_BAD_REQUEST)

    connection = mail.get_connection()
    # Manually open the connection
    connection.open()

    failed_emails = {
        'failed_to_send': [],
        'have_already_voted': [],
        'is_not_active': []
    }
    failed_emails['have_already_voted'] = list(
        map(lambda user: user.ref, poll.emails_voted.all()))

    try:
        token_list = Token.objects.filter(poll__id=poll.id)
    except Token.DoesNotExist:
        return Response({
            'message': 'Usuarios nao encontrados',
        },
                        status=HTTP_404_NOT_FOUND)

    emails_voted_list = poll.emails_voted.all()

    for token in token_list:
        user = token.user
        if not user.is_active:
            failed_emails['is_not_active'].append(user.id)
            continue
        user_email = user.ref

        user_token = token.token
        # Construct an email message that uses the connection
        #email = EmailMultiAlternatives(
        #    'Link para a eleicao {}'.format(poll.title),
        #    'Link: www.safe-polls.com/{}'.format(user_token),
        #    '*****@*****.**',
        #    [user_email],
        #    connection=connection
        #    )

        subject = f'Convite para participar da eleição: {poll.title}'
        html_message = (
            f'<p>Olá!</p> <p>Você foi convidado para participar da eleição <strong>{poll.title}</strong>'
            +
            f', criada por {poll.admin.get_full_name()}. </p> <p> Por favor, clique'
            +
            f'<a href="{BASE_URL}/polls/{poll.id}/vote?token={user_token}"> aqui </a>'
            + ' para votar.</p> <p>Obrigado!</p> <p>Equipe SafePoll</p>')

        msg = EmailMultiAlternatives(subject, '', '*****@*****.**',
                                     [user_email])
        msg.attach_alternative(html_message, "text/html")

        try:
            msg.send()  # Send the email
        except:
            failed_emails['failed_to_send'].append(user.id)

    connection.close()

    if any(map(len, failed_emails.values())
           ) is False:  #If both failed_emails.values are 0.
        return Response(
            {'message': 'Convites para votacao enviados com sucesso.!'},
            status=HTTP_200_OK)
    else:
        return Response(data={
            'message': 'Falha no envio de emails',
            'failed_emails': failed_emails,
            'faltam_votar': len(token_list)
        },
                        status=HTTP_202_ACCEPTED)
def event_comment(request):
    if request.method == 'POST':
        name = request.POST['name']
        surname = request.POST['surname']
        email = request.POST['email']
        comment = request.POST['comment']
        webcast_id = request.POST['webcast_id']
        webcast_title = request.POST['webcast_title']
        date = request.POST['date']

        if request.POST['form'] == "commentForm":

            try:
                Feedback.objects.create(
                    name=name,
                    surname=surname,
                    email=email,
                    comment=comment,
                    webcast_id=webcast_id,
                    date=date,
                    event_title=webcast_title
                )

                subject, from_email, to = 'Thank you for contacting Marver', '*****@*****.**', email
                text_content = 'This is an important message.'
                context = {
                    'name': name.upper(),
                    'comment': comment,
                    'webcast_title': webcast_title.upper()
                }
                message = get_template('eventsdisplay/comment_email_template.html')
                msg = EmailMultiAlternatives(subject ,text_content, from_email, [to])
                msg.attach_alternative(message.render(context), 'text/html')
                msg.send()
                return HttpResponse('You have successfully submitted your feedback, thank you!!')
            except BadHeaderError:
                return HttpResponse('There have been an error please try again')
        else:
            issue_type = request.POST['issue_type']
            platform = request.POST['platform']
            device = request.POST['device']
            Support.objects.create(
                name=name,
                surname=surname,
                email=email,
                support_request=comment,
                webcast_id=webcast_id,
                issue_type=issue_type,
                date=date,
                platform=platform,
                device=device,
                event_title=webcast_title
            )

            subject, from_email, to = 'Thank you for your support request', '*****@*****.**', email
            text_content = 'This is an important message.'
            context = {
                'name': name.upper(),
                'comment': comment,
                'webcast_title': webcast_title.upper()
            }
            message = get_template('eventsdisplay/support_email_template.html')
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(message.render(context), 'text/html')
            msg.send()
            return HttpResponse('You have successfully submitted a support request, we will be in touch shortly')
Example #59
0
def send_list_emails(request: CleanRequest) -> Response:
    '''
    Description: Envia emails para uma lista especifica de usuarios. Sao enviados emails somente para os usuarios cadastrados na eleicao.
    '''
    data = request.clean_data
    admin = request.user
    #Get the desired poll.
    try:
        poll = Poll.objects.get(pk=data['poll_id'], admin=admin)
    except Poll.DoesNotExist:
        return Response({'message': 'Eleicao nao existe.'},
                        status=HTTP_404_NOT_FOUND)

    #Check if poll is valid:
    if poll.deadline < datetime.date.today():
        return Response(
            {
                'message':
                'Eleição não é válida, acabou em {}'.format(
                    poll.deadline.strftime("%d/%m/%Y"))
            },
            status=HTTP_400_BAD_REQUEST)

    connection = mail.get_connection()
    # Manually open the connection
    connection.open()

    failed_emails = {
        'no_token': [],
        'failed_to_send': [],
        'have_already_voted': [],
        'is_not_active': []
    }
    users_emails_list = data['users_emails_list']

    users_id_list = []
    for email in users_emails_list:
        users_id_list.append(UserAccount.objects.get(ref=email).pk)

    token_list = []
    for user_id in users_id_list:
        try:
            token = Token.objects.get(poll__id=poll.id, user__id=user_id)
            token_list.append(token)
        except Token.DoesNotExist:
            failed_emails['no_token'].append(user_id)

    emails_voted_list = poll.emails_voted.all()
    for token in token_list:
        user = token.user
        if not user.is_active:
            failed_emails['is_not_active'].append(user.id)
            continue
        user_email = user.ref

        #Check if the user has already voted.
        if user in emails_voted_list:
            failed_emails['have_already_voted'].append(user.id)
            continue
        user_token = token.token
        # Construct an email message that uses the connection

        subject = f'Convite para participar da eleição: {poll.title}'
        html_message = (
            f'<p>Olá!</p> <p>Você foi convidado para participar da eleição <strong>{poll.title}</strong>'
            +
            f', criada por {poll.admin.get_full_name()}. </p> <p> Por favor, clique'
            +
            f'<a href="{BASE_URL}/polls/{poll.id}/vote?token={user_token}"> aqui </a>'
            + ' para votar.</p> <p>Obrigado!</p> <p>Equipe SafePoll</p>')

        msg = EmailMultiAlternatives(subject, '', '*****@*****.**',
                                     [user_email])
        msg.attach_alternative(html_message, "text/html")

        try:
            msg.send()  # Send the email
        except:
            failed_emails['failed_to_send'].append(user.id)

    connection.close()

    if any(map(len, failed_emails.values())
           ) is False:  #If both failed_emails.values are 0.
        return Response(
            {'message': 'Convites para votação enviado com sucesso!'},
            status=HTTP_200_OK)
    else:
        return Response(data={
            'message': 'Falha no envio de emails',
            'failed_emails': failed_emails
        },
                        status=HTTP_400_BAD_REQUEST)
Example #60
0
def send_email(request,
               call_on,
               user_position=None,
               workshop_date=None,
               workshop_title=None,
               user_name=None,
               other_email=None,
               phone_number=None,
               institute=None,
               key=None):
    '''
	Email sending function while registration and 
	booking confirmation.
	'''

    if call_on == "Registration":
        if user_position == "instructor":
            message = dedent("""\
					Your request as an Instructor at FOSSEE, IIT Bombay 
					has been received. Please click on the below link to 
					activate your account
					{0}/activate_user/{1}

					You will be notified via email on
					approval of your instructor account
					within 3 working days.

					In case of queries regarding the same revert to this 
					email.""".format(PRODUCTION_URL, key))

            try:
                send_mail("Instructor Registration - FOSSEE, IIT Bombay",
                          message,
                          SENDER_EMAIL, [request.user.email],
                          fail_silently=False)
            except Exception:
                send_smtp_email(
                    request=request,
                    subject="Instructor Registration - FOSSEE, IIT Bombay",
                    message=message,
                    other_email=request.user.email,
                )

            #Send a mail to admin as well.
            message = dedent("""\
					A new instructor request has been received.

					Instructor name: {0}
					Instructor email: {1}

					Please verify the profile and mail the user within 2
					working days.""".format(request.user, request.user.email))

            try:
                send_mail("New Instructor Registration - FOSSEE, IIT Bombay",
                          message,
                          SENDER_EMAIL, ['*****@*****.**'],
                          fail_silently=False)
            except Exception:
                send_smtp_email(
                    request=request,
                    subject="Instructor Registration - FOSSEE, IIT Bombay",
                    message=message,
                    other_email='*****@*****.**',
                )

        else:
            message = dedent("""\
						Thank you for registering as a coordinator with us. 

						Your request as a coordinator has been accepted.
						Please click on the below link to 
						activate your account
						{0}/activate_user/{1}
						
						After activation you can proceed to book your dates for 
						the workshop(s).

						In case of queries regarding workshop booking(s), 
						revert to this email.""".format(PRODUCTION_URL, key))

            try:
                send_mail("Coordinator Registration at FOSSEE, IIT Bombay",
                          message,
                          SENDER_EMAIL, [request.user.email],
                          fail_silently=False)
            except Exception:
                send_smtp_email(
                    request=request,
                    subject="Coordinator Registration - FOSSEE, IIT Bombay",
                    message=message,
                    other_email=request.user.email,
                )

    elif call_on == "Booking":
        if user_position == "instructor":
            message = dedent("""\
					Coordinator name:{0}
					Coordinator email: {1}
					Contact number:{2}
					Institute:{3}
					Workshop date:{4}
					Workshop title:{5}

					You may accept or reject this booking 
					{6}/my_workshops/ .""".format(user_name, request.user.email,
                                   request.user.profile.phone_number,
                                   request.user.profile.institute,
                                   workshop_date, workshop_title,
                                   PRODUCTION_URL))

            try:
                send_mail(
                    "New FOSSEE Workshop booking on {0}".format(workshop_date),
                    message,
                    SENDER_EMAIL, [other_email],
                    fail_silently=False)
            except Exception:
                send_smtp_email(
                    request=request,
                    subject="New FOSSEE Workshop booking on {0}".format(
                        workshop_date),
                    message=message,
                    other_email=other_email,
                )
        else:
            message = dedent("""\
					Thank You for New FOSSEE Workshop booking. 

					Workshop date:{0}
					Workshop title:{1}

					Your request has been received and is awaiting instructor 
					approval/disapproval. You will be notified about the status
					via email and on {2}/my_workshops/

					In case of queries regarding workshop booking(s), revert
					to this email.""".format(workshop_date, workshop_title, PRODUCTION_URL))

            try:
                send_mail(
                    "Pending Request for New FOSSEE Workshop booking on {0}".
                    format(workshop_date),
                    message,
                    SENDER_EMAIL, [request.user.email],
                    fail_silently=False)
            except Exception:
                send_smtp_email(
                    request=request,
                    subject="Pending Request for New FOSSEE Workshop booking \
					on {0}".format(workshop_date),
                    message=message,
                    other_email=request.user.email,
                )

    elif call_on == "Booking Confirmed":
        if user_position == "instructor":
            message = dedent("""\
			Coordinator name:{0}
			Coordinator email: {1}
			Contact number:{2}
			Institute:{3}
			Workshop date:{4}
			Workshop title:{5}

			You have accepted this booking.  Detailed instructions have
			been sent to the coordinator. """.format(user_name, other_email,
                                            phone_number, institute,
                                            workshop_date, workshop_title))


            subject = "FOSSEE Workshop booking confirmation  on {0}".\
             format(workshop_date)
            msg = EmailMultiAlternatives(subject, message, SENDER_EMAIL,
                                         [request.user.email])

            files = listdir(settings.MEDIA_ROOT)
            for f in files:
                attachment = open(path.join(settings.MEDIA_ROOT, f), 'rb')
                part = MIMEBase('application', 'octet-stream')
                part.set_payload((attachment).read())
                encoders.encode_base64(part)
                part.add_header('Content-Disposition',
                                "attachment; filename= %s " % f)
                msg.attach(part)
            msg.send()

        else:
            message = dedent("""\
				Instructor name:{0}
				Instructor email: {1}
				Contact number:{2}
				Workshop date:{3}
				Workshop title:{4}

				Your workshop booking has been accepted. Detailed 
				instructions are attached below.  

				In case of queries regarding the workshop 
				instructions/schedule revert to this email.""".format(
                request.user.username, request.user.email, phone_number,
                workshop_date, workshop_title))

            subject = "FOSSEE Workshop booking confirmation  on {0}".\
             format(workshop_date)
            msg = EmailMultiAlternatives(subject, message, SENDER_EMAIL,
                                         [other_email])

            files = listdir(settings.MEDIA_ROOT)
            for f in files:
                attachment = open(path.join(settings.MEDIA_ROOT, f), 'rb')
                part = MIMEBase('application', 'octet-stream')
                part.set_payload((attachment).read())
                encoders.encode_base64(part)
                part.add_header('Content-Disposition',
                                "attachment; filename= %s " % f)
                msg.attach(part)
            msg.send()

    elif call_on == "Booking Request Rejected":
        if user_position == "instructor":
            message = dedent("""\
					Coordinator name:{0}
					Coordinator email: {1}
					Contact number:{2}
					Institute:{3}
					Workshop date:{4}
					Workshop title:{4}

					You have rejected this booking.  The coordinator has
					been notified.""".format(user_name, other_email, phone_number, institute,
                              workshop_date, workshop_title))

            try:
                send_mail("FOSSEE Workshop booking rejected for {0}".format(
                    workshop_date),
                          message,
                          SENDER_EMAIL, [request.user.email],
                          fail_silently=False)
            except Exception:
                send_smtp_email(
                    request=request,
                    subject="FOSSEE Workshop booking rejected for {0}".format(
                        workshop_date),
                    message=message,
                    other_email=request.user.email)
        else:
            message = dedent("""\
					Workshop date:{0}
					Workshop title:{1}

					We regret to inform you that your workshop booking
					has been rejected due to unavailability of the
					instructor. You may try booking other available 
					slots {2}/book/ """.format(workshop_date, workshop_title, PRODUCTION_URL))

            try:
                send_mail("FOSSEE Workshop booking rejected for {0}".format(
                    workshop_date),
                          message,
                          SENDER_EMAIL, [other_email],
                          fail_silently=False)
            except Exception:
                send_smtp_email(
                    request=request,
                    subject="FOSSEE Workshop booking rejected for {0}".format(
                        workshop_date),
                    message=message,
                    other_email=other_email)

    elif call_on == 'Workshop Deleted':
        message = dedent("""\
				You have deleted a Workshop.

				Workshop date:{0}
				Workshop title:{1}""".format(workshop_date, workshop_title))
        try:
            send_mail("FOSSEE workshop deleted for {0}".format(workshop_date),
                      message,
                      SENDER_EMAIL, [request.user.email],
                      fail_silently=False)
        except Exception:
            send_smtp_email(request=request,
                            subject="FOSSEE Workshop deleted for {0}".format(
                                workshop_date),
                            message=message,
                            other_email=request.user.email)