Пример #1
0
    def bug_report(self, couch_user, error_id):
        error = PillowError.objects.get(id=error_id)

        context = {
            'error': error,
            'url': "{}{}?error={}".format(get_url_base(), reverse(EditPillowError.urlname), error_id)
        }
        message = render_to_string('hqpillow_retry/fb.txt', context)
        subject = 'PillowTop error: {} - {}'.format(error.pillow, error.error_type)

        reply_to = u'"{}" <{}>'.format(couch_user.full_name, couch_user.get_email())
        email = EmailMessage(
            subject=subject,
            body=message,
            to=settings.BUG_REPORT_RECIPIENTS,
            headers={'Reply-To': reply_to}
        )

        # only fake the from email if it's an @dimagi.com account
        if re.search('@dimagi\.com$', couch_user.username):
            email.from_email = couch_user.username
        else:
            email.from_email = settings.CCHQ_BUG_REPORT_EMAIL

        email.send(fail_silently=False)
Пример #2
0
    def emit(self, record):
        import traceback

        if not settings.ADMINS:
            return
        try:
            # Hack to try to get request from context
            request = record.exc_info[2].tb_frame.f_locals['context']['request']
            request_repr = repr(request)
            request_path = request.path
        except Exception:
            request_repr = "Request unavailable"
            request_path = 'Unknown URL'
        if record.exc_info:
            stack_trace = '\n'.join(traceback.format_exception(*record.exc_info))
        else:
            stack_trace = 'No stack trace available'
        message = "%s\n\n%s" % (stack_trace, request_repr)
        msg = EmailMessage(
            '[sorl-thumbnail] %s: %s' % (record.levelname, request_path),
            message,
            settings.SERVER_EMAIL,
            [a[1] for a in settings.ADMINS],
            connection=None
        )
        msg.send(fail_silently=True)
Пример #3
0
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST,
                           initial={
                               'captcha': request.META['REMOTE_ADDR']})
        if form.is_valid():
            if form.cleaned_data['sender']:
                headers = {
                    'Reply-To': form.cleaned_data['sender']}
            else:
                headers = {}

            email = EmailMessage(
                subject=form.cleaned_data['subject'],
                body="%s\n\nfrom: %s" % (form.cleaned_data['message'],
                                         form.cleaned_data['sender']),
                from_email='*****@*****.**',
                to=('*****@*****.**', '*****@*****.**'),
                headers=headers,
            )

            email.send()

            # Redirect after POST
            return HttpResponseRedirect(reverse('contact_sent'))

    else:
        form = ContactForm()  # An unbound form

    # request context required for CSRF
    return render_to_response('dnd/contacts/contact.html',
                              {
                                  'request': request,
                                  'form': form, }, context_instance=RequestContext(request), )
Пример #4
0
 def notify(self):
     base_url = "http://%s" % Site.objects.get_current().domain
     text = render_to_string("harvester/notification.html",
                             dict(base_url=base_url, job=self))
     message = EmailMessage(u"Harvesting job is complete", text, settings.DEFAULT_FROM_EMAIL, [self.email])
     message.content_subtype = "html"
     message.send()
Пример #5
0
def home(request):
    if request.method == 'POST':
        form = ContactForm(request.POST, request.FILES)
        if form.is_valid():
            contact = form.save()

            message = render_to_string("email.html", {'contact': contact})

            msg = EmailMessage('Info verzoek van anverhuizen.be',
                               message,
                               contact.email,
                               ['*****@*****.**'])
            msg.content_subtype = "html"

            if 'attachment' in request.FILES:
                request.FILES['attachment'].seek(0)
                msg.attach(request.FILES['attachment'].name,
                           request.FILES['attachment'].read(),
                           request.FILES['attachment'].content_type)

            msg.send(fail_silently=False)

            messages.success(request, _("Ik heb jouw bericht ontvangen en zal zo snel mogelijk contact opnemen."))

            return HttpResponseRedirect(reverse('home'))
    else:
        form = ContactForm()

    return render_to_response('home.html',
                              {'form': form},
                              RequestContext(request))
Пример #6
0
def send_simple_order_notification(sender, order, request, **kwargs):
    """
    :param order: Order
    :type order: shuup.core.models.Order
    """

    if order.log_entries.filter(identifier=NOTIFICATION_SUCCESS_LOG_IDENTIFIER).exists():
        return

    try:
        engine = engines["jinja2"]
    except InvalidTemplateEngineError:
        return  # Dont send notifications because we cannot parse files :(

    with translation.override(order.language):
        # Local import to make sure the environment is initialized
        env = {"order": order}
        subject = engine.from_string(MESSAGE_SUBJECT_TEMPLATE).render(env)
        body = engine.from_string(MESSAGE_BODY_TEMPLATE).render(env)

    message = EmailMessage(subject, body, to=[order.email])
    try:
        message.send()
    except Exception as exc:
        LOG.exception("Failed to send order notification to %s" % message.to)
        order.add_log_entry(
            "Order Notification Email failed: %s" % exc,
            identifier=NOTIFICATION_ERROR_LOG_IDENTIFIER,
            kind=LogEntryKind.ERROR)
    else:
        LOG.info("Order notification sent to %s" % message.to)
        order.add_log_entry(
            "Order Notification Email sent",
            identifier=NOTIFICATION_SUCCESS_LOG_IDENTIFIER,
            kind=LogEntryKind.ERROR)
Пример #7
0
def newsite(req):
    import base.models as M, random, string 
    form                = None
    auth_user           = UR.getUserInfo(req)
    ensemble_form       = None
    user_form           = None
    if auth_user is not None: 
        return HttpResponseRedirect("/admin")
    if req.method == 'POST':
        user            = M.User(confkey="".join([choice(string.ascii_letters+string.digits) for i in xrange(0,32)]))
        ensemble        = M.Ensemble()
        user_form       = forms.UserForm(req.POST, instance=user)
        ensemble_form   = forms.EnsembleForm(req.POST, instance=ensemble)
        if user_form.is_valid() and ensemble_form.is_valid():             
            user_form.save()
            ensemble.invitekey =  "".join([ random.choice(string.ascii_letters+string.digits) for i in xrange(0,50)])      
            ensemble_form.save()
            m = M.Membership(user=user, ensemble=ensemble, admin=True)
            m.save()
            p = {"tutorial_url": settings.GUEST_TUTORIAL_URL, "conf_url": "http://%s?ckey=%s" %(settings.NB_SERVERNAME, user.confkey), "firstname": user.firstname, "email": user.email, "password": user.password }
            email = EmailMessage(
                "Welcome to NB, %s" % (user.firstname),
                render_to_string("email/confirm_newsite", p), 
                settings.EMAIL_FROM, 
                (user.email, ), 
                (settings.EMAIL_BCC, ))
            email.send()
            return HttpResponseRedirect('/newsite_thanks')       
    else: 
        user_form       = forms.UserForm()
        ensemble_form   = forms.EnsembleForm()
    return render_to_response("web/newsite.html", {"user_form": user_form, "ensemble_form": ensemble_form})
Пример #8
0
def payment_notification(sender, **kwargs):
    ipn_obj = sender
    if ipn_obj.payment_status == ST_PP_COMPLETED:
        # payment was successful
        order = get_object_or_404(Order, id=ipn_obj.invoice)
        # mark the order as paid
        order.paid = True
        order.save()

        # create invoice e-mail
        subject = 'My Shop - Invoice no. {}'.format(order.id)
        message = 'Please, find attached the invoice for your recent purchase.'
        email = EmailMessage(subject, message, '*****@*****.**', [order.email])

        # generate PDF
        html = render_to_string('orders/order/pdf.html', {'order': order})
        out = BytesIO()
        css_path = os.path.join(settings.STATICFILES_DIRS[0], 'css/pdf.css')
        weasyprint.HTML(string=html).write_pdf(out, stylesheets=[weasyprint.CSS(css_path)])

        # attach PDF file
        email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf')

        # send e-mail
        email.send()
Пример #9
0
def send_mail(subject, template_name, to, **kwargs):
    kwargs['settings'] = settings
    body = render_to_string(template_name, kwargs)
    if to:
        msg = EmailMessage(subject, body, None, to=to)
        msg.content_subtype = "html"
        msg.send()
Пример #10
0
 def send_confirmation(self):
     url = reverse("users:reset_password", kwargs=dict(key=self.key))
     url = "http://%s%s" % (Site.objects.get_current().domain, url)
     body = render_to_string("users/emails/reset-password-confirmation.html", dict(url=url, user=self.user))
     message = EmailMessage(u"Reset your OER Commons password", body, to=[self.user.email])
     message.content_subtype = "html"
     message.send()
Пример #11
0
    def send_csv(self, emails=[]):
        filename, csv_file = self.create_csv()

        message = EmailMessage(subject='{} LEVEL ASSORTMENT REPORT'.format(self.level.upper()),
                               from_email=EMAIL_HOST_USER, to=emails)
        message.attach(filename, csv_file.getvalue(), 'text/csv')
        print message.send()
Пример #12
0
def remind_account_about_events_with_email(account, single_events):
    featured_events = Event.featured_events_for_region(account.native_region)

    similar_events = find_similar_events(
        Event.future_events.filter(id__in=single_events.values_list("event_id", flat=True))
    )

    subject = "Upcoming events from cityfusion"

    message = render_to_string(
        "accounts/emails/reminder_email.html",
        {
            "featured_events": featured_events,
            "events": single_events,
            "similar_events": similar_events,
            "STATIC_URL": "/static/",
            "advertising_region": account.advertising_region,
            "site": "http://%s" % Site.objects.get_current().domain,
        },
    )

    msg = EmailMessage(subject, message, "*****@*****.**", [account.reminder_email])
    msg.content_subtype = "html"
    msg.send()

    return message
Пример #13
0
def register_company_view(request):
    """Registro de compañias"""
    if request.method == 'POST':
        form = RegistrerCompaniesForm(request.POST)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            username = cleaned_data.get('email')
            company = cleaned_data.get('company')
            password = cleaned_data.get('password')
            email = cleaned_data.get('email')
            # instanciamos un objeto User, con el username y password
            user_model = User.objects.create_user(username=username,
                                                  password=password,
                                                  first_name=company)
            user_model.email = email
            user_model.save()
            company_user = CompanyUser()
            company_user.company = user_model
            company_user.save()
            asunto = 'Servifeng'
            mens = 'Se a realizado su registro correctamente su usuario es: ' + username
            mens = mens + r' ingrese a http://127.0.0.1:8000/admin/'
            mail = EmailMessage(asunto, mens, to=[email, '*****@*****.**'])
            mail.send()
            return redirect(reverse('accounts.gracias', kwargs={'username': username}))
    else:
        form = RegistrerCompaniesForm()

    context ={
        'form': form
    }
    return render(request, 'companies/registro.html', context)
Пример #14
0
def local_red_alert(message):
    '''
    Sends out an SMS message, email, and initiates a conference call.
    '''
    message = message.replace('/', ' slash ').replace('.py', ' dot pie.') #To assist the text-to-speech
    sms_recipients = []
    phone_recipients = []
    email_recipients = []
    
    for contact in PRODUCTION_EMERGENCY:
        if contact[1]:
            phone_recipients.append(contact[1])
        if contact[2]:            
            email_recipients.append(contact[2])
        if contact[3]:
            sms_recipients.append(contact[3])
    
    place_red_alert_phone_call(phone_recipients, message)
    subject = "" 
    body = message
    sender = '*****@*****.**'
    
    sms_msg = EmailMessage(subject, body, sender, sms_recipients)
    sms_msg.send()
    
    email_msg = EmailMessage(subject, body, sender, email_recipients)
    email_msg.send()

    return True
Пример #15
0
def activate(request, token):

    
    aux1=YoungInvestigator.objects.filter(token=token)
    aux2=PrincipalInvestigator.objects.filter(token=token)
    aux=[]
    if len(aux1)==1:
        aux=aux1
    if len(aux2)==1:
        aux=aux2
    if len(aux)==1:
        reg1=aux[0]
        user1=User.objects.filter(id=reg1.user.id)[0]
        user1.is_active=1
        user1.save()
        reg1.activation_key="ALREADY_ACTIVATED"
        reg1.save()
        
        ##correo para informar de la activacion
        contenido="Thanks for trust in ScienceWeb.\n You can access with your account.\n\nUsername: "******"\n http://www.peerland.org/"
        correo = EmailMessage("ScienceWeb: Your Account is already activated", contenido, to=[user1.email])
        correo.send()
        
        return render_to_response('users/activation_complete.html',context_instance = RequestContext(request))
    
    else:
        return render_to_response('users/activate.html')
Пример #16
0
def inform_account_about_events_with_tag_with_email(account, events, tags_in_venues):
    featured_events = Event.featured_events_for_region(account.native_region)[:4]

    similar_events = find_similar_events(events)

    subject = "New Events in cityfusion"

    message = render_to_string(
        "accounts/emails/in_the_loop_email.html",
        {
            "featured_events": featured_events,
            "events": events,
            "similar_events": similar_events,
            "STATIC_URL": "/static/",
            "site": "http://%s" % Site.objects.get_current().domain,
            "tags_in_venues": tags_in_venues,
            "advertising_region": account.advertising_region,
        },
    )

    msg = EmailMessage(subject, message, "*****@*****.**", [account.in_the_loop_email])

    msg.content_subtype = "html"

    msg.send()

    return message
Пример #17
0
def wyslij_email(request, pk):
    if request.is_ajax():
        response_message = "success"

        wiadomosc = Wiadomosc.objects.get(id=pk)
        subject = 'Hotel Messiah'
        try:
            message = request.GET['message']
            message_html = '<h3>' + _('Twoje pytanie') + ': </h3><p>' + wiadomosc.tresc + \
                '</p><h3>' + _('Nasza odpowiedz') + ': </h3><p>' + request.GET['message'] + "</p>"
            from_email = '*****@*****.**'
            to_email = request.GET['email_address']
            if subject and message and from_email:
                try:
                    # send_mail(subject, message, from_email, [to_email])
                    msg = EmailMessage(subject, message_html, from_email, [to_email])
                    msg.content_subtype = "html"
                    msg.send()
                except KeyError:
                    response_message = "site_error"
            else:
                response_message = "empty_field"

            if response_message == "success":
                wiadomosc.wyslano_odpowiedz = True
                wiadomosc.odpowiedz = message
                wiadomosc.save()
        except KeyError:
            raise Http404

        return HttpResponse(response_message)
    else:
        raise Http404
Пример #18
0
 def send(self, fail_silently=False):
     recipient_list = []
     recipient_bcc_list = []
     headers = {}
     if self.recipient:
         recipient_list = self.recipient.split(',')
         recipient_list = [recipient.strip() for recipient in recipient_list \
                           if recipient.strip() <> '']
     if self.recipient_cc:
         recipient_cc_list = self.recipient_cc.split(',')
         recipient_cc_list = [recipient_cc.strip() for recipient_cc in recipient_cc_list if \
                               recipient_cc.strip() <> '']
         recipient_list += recipient_cc_list
     if self.recipient_bcc:
         recipient_bcc_list = self.recipient_bcc.split(',')
         recipient_bcc_list = [recipient_bcc.strip() for recipient_bcc in recipient_bcc_list if \
                                recipient_bcc.strip() <> '']
         
     if self.reply_to:
         headers['Reply-To'] = self.reply_to
     if self.sender_display:
         headers['From'] = '%s<%s>' % (self.sender_display, self.sender)
         
     if recipient_list or recipient_bcc_list:
         msg = EmailMessage(self.subject,
                            self.body,
                            self.sender,
                            recipient_list,
                            recipient_bcc_list,
                            headers=headers )
         if self.content_type == 'html' or self.content_type == 'text/html':
             msg.content_subtype = 'html'
         msg.send(fail_silently=fail_silently)
Пример #19
0
    def send_mail(self, request, newsletter_id):
        object = Newsletter.objects.get(id=newsletter_id)

        subscribers = Subscription.objects.filter(subscribed=True)

        site = Site.objects.get_current()
        template = render_to_string(object.template, locals(), RequestContext(request))

        if request.method == 'POST':
            object.sent_date = datetime.now()
            object.save()
            email = EmailMessage(subject = '%s - %s' % (object.title, site),
                                 body = template,
                                 from_email = settings.NEWSLETTER_FROM_EMAIL,
                                 bcc = [e.email for e in subscribers],
                                 headers = {'Reply-To': settings.NEWSLETTER_REPLYTO_EMAIL}
            )
            email.content_subtype = "html"  # Main content is now text/html
            email.send()
            self.message_user(request, _(u"Newsletter sent successfully"))

            return HttpResponseRedirect(reverse('admin:newsletters_newsletter_changelist'))
        opts = Newsletter._meta
        app_label = opts.app_label



        return render_to_response('admin/newsletters/send_mail.html',
                                  locals(),
                                  RequestContext(request))
Пример #20
0
 def send_pdf_to_user(self, user):
     report = self.report.get_path_to_pdf(user, self.view_args)
     title = self.report.email_subject(user, self.view_args)
     email = EmailMessage(title, 'See attachment',
                          settings.EMAIL_LOGIN, [user.email])
     email.attach_file(report)
     email.send(fail_silently=False)
Пример #21
0
def wyslij_biuletyn(request):
    if request.is_ajax():
        subscribers = Newsletter.objects.all()
        response_message = "success"
        from_email = '*****@*****.**'
        connection = mail.get_connection()
        connection.open()
        subject = 'Hotel Messiah Newsletter!'


        for subscriber in subscribers:
            try:
                message_html = request.GET['message']+"<a href='"+request.build_absolute_uri(reverse('hotel:newsletter_anuluj', args=[subscriber.news_kod]))+"'>"+"Anuluj newsletter"+"</a>"
                to_email = subscriber.news_email
                #to_email_bcc = Newsletter.objects.values_list('news_email', flat=True)
                if subject and message_html and from_email:
                    try:
                        msg = EmailMessage(subject, message_html, from_email, [to_email])
                        msg.content_subtype = "html"
                        msg.send()
                    except KeyError:
                        response_message = "site_error"
                else:
                    response_message = "empty_field"

            except KeyError:
                raise Http404

        connection.close()
        return HttpResponse(response_message)
    else:
        raise Http404
Пример #22
0
def save_user(form, client):

    list_mail = dict()

    name = form.cleaned_data['name']
    email = form.cleaned_data['email']
    user = form.cleaned_data['user'].upper()
    groups = form.cleaned_data['groups']
    user_ldap = form.cleaned_data[
        'ldap_user'] if form.cleaned_data['is_ldap'] else None

    list_mail['nome'] = name
    list_mail['user'] = user

    password = make_random_password()
    list_mail['pass'] = password

    new_user = client.create_usuario().inserir(
        user, password, name, email, user_ldap)

    for group in groups:
        client.create_usuario_grupo().inserir(
            new_user.get('usuario')['id'], group)

    if user_ldap is None:
        connection = EmailBackend(
            username=EMAIL_HOST_USER, password=EMAIL_HOST_PASSWORD)
        send_email = EmailMessage('Novo Usuário CadVlan-Globo.com',  loader.render_to_string(
            MAIL_NEW_USER, list_mail), EMAIL_FROM, [email], connection=connection)
        send_email.content_subtype = "html"
        send_email.send()
Пример #23
0
def send_html_message(subject, html_content, from_email, to_list):
#    with open( "output.html" , "w") as debug_file:
#        debug_file.write(html_content)
    
    msg = EmailMessage(string_to_email_subject(subject), html_content, from_email, to_list)
    msg.content_subtype = "html"  # Main content is now text/html
    msg.send()
Пример #24
0
def remind_account_about_events_with_email(account, single_events):
    if account.reminder_email:
        featured_events = Event.featured_events_for_region(account.native_region)[0:4]

        similar_events = find_similar_events(
            Event.future_events.filter(id__in=single_events.values_list("event_id", flat=True))
        )

        subject = "Upcoming events from cityfusion"

        message = render_to_string('accounts/emails/reminder_email.html', {
                "featured_events": featured_events,
                "events": single_events,
                "similar_events": similar_events,
                "STATIC_URL": "/static/",
                "advertising_region": account.advertising_region,
                "site": "http://%s" % Site.objects.get_current().domain
            })

        try:
            msg = EmailMessage(subject,
                       message,
                       "*****@*****.**",
                       [account.reminder_email])
            msg.content_subtype = 'html'
            msg.send()
        except:
            logger.error("Invalid email %s" % account.reminder_email)

        return message

    else:
        return ""
Пример #25
0
def send_email_feedback(self, feedback_pk, sender, recipents):
    try:
        feedback = Feedback.objects.get(pk=feedback_pk)
    except Feedback.DoesNotExist as exc:
        logger.error('Failed processing_crash_dump',
                     exc_info=True,
                     extra=dict(crash_pk=feedback_pk))
        raise self.retry(exc=exc, countdown=2 ** send_email_feedback.request.retries)
    recipients = [x.strip() for x in recipents.split(',')]
    body = email_body_tmpl % (
        feedback.description, feedback.page_url, feedback.email,
        feedback.ip, feedback.feedback_data,
    )
    email = EmailMessage("Feedback # %s" % feedback_pk, body, sender, recipients)

    attachments = [
        feedback.screenshot,
        feedback.blackbox,
        feedback.system_logs,
        feedback.attached_file
    ]
    for attach in attachments:
        if attach:
            email.attach(os.path.basename(attach.name), attach.read())

    email.send()
Пример #26
0
 def _log_to_email(email_to, email_from, output, req_string):
     em = EmailMessage('Slow Request Watchdog: %s' %
                       req_string.encode('utf-8'),
                       output,
                       email_from,
                       (email_to,))
     em.send(fail_silently=True)
Пример #27
0
def remind_account_about_deleted_events_with_email(account, single_events):
    if account.reminder_email:
        featured_events = Event.featured_events_for_region(account.native_region)[:4]
        subject = 'Deleted events from cityfusion'

        message = render_to_string('accounts/emails/reminder_deleted_event_email.html', {
                "featured_events": featured_events,
                "events": single_events,
                "STATIC_URL": "/static/",
                "advertising_region": account.advertising_region,
                "site": "http://%s" % Site.objects.get_current().domain
            })

        try:
            msg = EmailMessage(subject,
                       message,
                       "*****@*****.**",
                       [account.reminder_email])
            msg.content_subtype = 'html'
            msg.send()
        except:
            logger.error("Invalid email %s" % account.reminder_email)

        return message

    else:
        return ""
Пример #28
0
def send_activation_mail(user):
    key = SecretKey.objects.get_or_create(user=user).secretkey
    context = {'username': user.username, 'security_key': key}
    html_content = render_to_string('massage.html', context)
    msg = EmailMessage('submit registration', html_content, '*****@*****.**', [user.email])
    msg.content_subtype = "html"
    msg.send()
Пример #29
0
def sender(request):
	
    if request.method == 'POST':
	doc_id = request.POST.get('doc_id')
        comment = request.POST.get('comment')
        name_email = request.POST.get('name_email')

	document = Document.objects.get(id=doc_id)
	personals = document.personal.all()
	send_to = []
	for per in personals:
		send_to.append(per.email)

   	# Build message
    	email = EmailMessage(subject=name_email, body=comment, from_email='*****@*****.**',to=send_to, headers = {'Reply-To': '*****@*****.**'})

    	# Open file
    	attachment = open(u''+document.docfile.name, 'rb')

    	# Attach file
    	email.attach("attach_file.pdf", attachment.read(),'application/pdf')

    	# Send message with built-in send() method
    	email.send()
	msg_ok = "Send message success"
    	print('Send message success')    
    
    return render_to_response('group1/send.html', {'document': document, 'msg_ok': msg_ok} ,
                              context_instance=RequestContext(request))
Пример #30
0
def email(request, template_name="email.html"):
    ctx = dict()
    if request.method == "POST":
        email_address = request.POST.get("email", "your mom")

        trips = Trip.objects.filter(user=request.user)

        csv_data = "\n".join(["%s, %s, %s %s, %s" % (trip.date,
                                                     trip.odometer_start,
                                                     trip.odometer_end,
                                                     trip.distance(),
                                                     trip.reason)
                              for trip in trips])
        email = EmailMessage('MileTracker Data',
                             'Your data is attached',
                             '*****@*****.**',
                             ['*****@*****.**', email_address])
        email.attach('miletracker_report.csv', csv_data, 'text/csv')
        email.send()
        messages.info(request, "We've sent an email report to: %s" % email_address)

        return HttpResponseRedirect(reverse("log"))

    return render_to_response(
        template_name, RequestContext(request, ctx))
Пример #31
0
def user_details_force_sync(auth_entry, strategy, details, user=None, *args, **kwargs):
    """
    Update normally protected user details using data from provider.

    This step in the pipeline is akin to `social_core.pipeline.user.user_details`, which updates
    the user details but has an unconfigurable protection over updating the username & email, and
    is unable to update information such as the user's full name which isn't on the user model, but
    rather on the user profile model.

    Additionally, because the email field is normally used to log in, if the email is changed by this
    forced synchronization, we send an email to both the old and new emails, letting the user know.

    This step is controlled by the `sync_learner_profile_data` flag on the provider's configuration.
    """
    current_provider = provider.Registry.get_from_pipeline({'backend': strategy.request.backend.name, 'kwargs': kwargs})
    if user and current_provider.sync_learner_profile_data:
        # Keep track of which incoming values get applied.
        changed = {}

        # Map each incoming field from the provider to the name on the user model (by default, they always match).
        field_mapping = {field: (user, field) for field in details.keys() if hasattr(user, field)}

        # This is a special case where the field mapping should go to the user profile object and not the user object,
        # in some cases with differing field names (i.e. 'fullname' vs. 'name').
        field_mapping.update({
            'fullname': (user.profile, 'name'),
            'country': (user.profile, 'country'),
        })

        # Remove username from list of fields for update
        field_mapping.pop('username', None)

        # Track any fields that would raise an integrity error if there was a conflict.
        integrity_conflict_fields = {'email': user.email, 'username': user.username}

        for provider_field, (model, field) in field_mapping.items():
            provider_value = details.get(provider_field)
            current_value = getattr(model, field)
            if provider_value is not None and current_value != provider_value:
                if field in integrity_conflict_fields and User.objects.filter(**{field: provider_value}).exists():
                    logger.warning(u'[THIRD_PARTY_AUTH] Profile data synchronization conflict. '
                                   u'UserId: {user_id}, Provider: {provider}, ConflictField: {conflict_field}, '
                                   u'ConflictValue: {conflict_value}'.format(
                                       user_id=user.id,
                                       provider=current_provider.name,
                                       conflict_field=field,
                                       conflict_value=provider_value))
                    continue
                changed[provider_field] = current_value
                setattr(model, field, provider_value)

        if changed:
            logger.info(
                u'[THIRD_PARTY_AUTH] User performed SSO and data was synchronized. '
                u'Username: {username}, Provider: {provider}, UpdatedKeys: {updated_keys}'.format(
                    username=user.username,
                    provider=current_provider.name,
                    updated_keys=list(changed.keys())
                )
            )

            # Save changes to user and user.profile models.
            strategy.storage.user.changed(user)
            user.profile.save()

            # Send an email to the old and new email to alert the user that their login email changed.
            if changed.get('email'):
                old_email = changed['email']
                new_email = user.email
                email_context = {'old_email': old_email, 'new_email': new_email}
                # Subjects shouldn't have new lines.
                subject = ''.join(render_to_string(
                    'emails/sync_learner_profile_data_email_change_subject.txt',
                    email_context
                ).splitlines())
                body = render_to_string('emails/sync_learner_profile_data_email_change_body.txt', email_context)
                from_email = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)

                email = EmailMessage(subject=subject, body=body, from_email=from_email, to=[old_email, new_email])
                email.content_subtype = "html"
                try:
                    email.send()
                except SMTPException:
                    logger.exception('[THIRD_PARTY_AUTH] Error sending IdP learner data sync-initiated email change '
                                     u'notification email. Username: {username}'.format(username=user.username))
Пример #32
0
def send_mail_async(self, subject, message, from_email, recipient_list, messaging_event_id=None):
    """ Call with send_mail_async.delay(*args, **kwargs)
    - sends emails in the main celery queue
    - if sending fails, retry in 15 min
    - retry a maximum of 10 times
    """
    from corehq.util.soft_assert import soft_assert
    soft_assert('{}@dimagi.com'.format('skelly'))(
        all(recipient for recipient in recipient_list),
        'Blank email addresses',
        {
            'subject': subject,
            'message': message,
            'recipients': recipient_list
        }
    )

    recipient_list = [_f for _f in recipient_list if _f]

    # todo deal with recipients marked as bounced
    from dimagi.utils.django.email import get_valid_recipients, mark_subevent_bounced
    filtered_recipient_list = get_valid_recipients(recipient_list)
    bounced_recipients = list(set(recipient_list) - set(filtered_recipient_list))
    if bounced_recipients and messaging_event_id:
        mark_subevent_bounced(bounced_recipients, messaging_event_id)

    if not filtered_recipient_list:
        return

    headers = {}
    if messaging_event_id is not None:
        headers[COMMCARE_MESSAGE_ID_HEADER] = messaging_event_id
    if settings.SES_CONFIGURATION_SET is not None:
        headers[SES_CONFIGURATION_SET_HEADER] = settings.SES_CONFIGURATION_SET

    try:
        message = EmailMessage(
            subject=subject,
            body=message,
            from_email=from_email,
            to=filtered_recipient_list,
            headers=headers,
        )
        return message.send()
    except SMTPDataError as e:
        # If the SES configuration has not been properly set up, resend the message
        if (
            "Configuration Set does not exist" in e.smtp_error
            and SES_CONFIGURATION_SET_HEADER in message.extra_headers
        ):
            del message.extra_headers[SES_CONFIGURATION_SET_HEADER]
            message.send()
            notify_exception(None, message="SES Configuration Set missing", details={'error': e})
        else:
            raise
    except Exception as e:
        notify_exception(
            None,
            message="Encountered error while sending email",
            details={
                'subject': subject,
                'recipients': ', '.join(filtered_recipient_list),
                'error': e,
                'messaging_event_id': messaging_event_id,
            }
        )
        if messaging_event_id is not None:
            mark_subevent_gateway_error(messaging_event_id, e, retrying=True)
        try:
            self.retry(exc=e)
        except MaxRetriesExceededError:
            if messaging_event_id is not None:
                mark_subevent_gateway_error(messaging_event_id, e, retrying=False)
Пример #33
0
    def handle(self, *args, **options):
        from tendenci.apps.site_settings.utils import get_setting

        pass_update_tendenci = False
        pass_update_tendenci_site = False
        pass_restart_server = False
        is_uwsgi = False
        gunicorn_error_msg = None
        uwsgi_error_msg = None
        errors_list = []

        pypi = xmlrpclib.ServerProxy('http://pypi.python.org/pypi')
        latest_version = pypi.package_releases('tendenci')[0]
        error_message = ""
        email_context = {'site_url':get_setting('site', 'global', 'siteurl'),
                         'version':latest_version, 'error_message':error_message}

        email_sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        email_recipient = ""
        user_id = options['user']
        if User.objects.filter(pk=user_id).exists():
            user = User.objects.get(pk=user_id)
            if user.email:
                email_recipient = user.email

        try:
            print("Updating tendenci")
            subprocess.check_output("%s -m pip install tendenci --upgrade" % python_executable(), stderr=subprocess.STDOUT, shell=True)
            pass_update_tendenci = True

        except subprocess.CalledProcessError as e:
            errors_list.append(e.output)

        # run python deploy.py iff update_tendenci is successful
        if pass_update_tendenci:
            try:
                print("Updating tendenci site")
                subprocess.check_output("%s deploy.py" % python_executable(), stderr=subprocess.STDOUT, shell=True)
                pass_update_tendenci_site = True

            except subprocess.CalledProcessError as e:
                errors_list.append(e.output)

        # run reload if update is done
        if pass_update_tendenci_site:
            try:
                print("Restarting Server")
                subprocess.check_output("sudo reload %s" % os.path.basename(settings.PROJECT_ROOT),
                                    stderr=subprocess.STDOUT, shell=True)

            except subprocess.CalledProcessError as e:
                gunicorn_error_msg = e.output
                if "reload: Unknown job:" in e.output:
                    is_uwsgi = True

        # run usgi command iff it was proven that the site is using uwsgi instead
        if is_uwsgi:
            try:
                print("Restarting Server")
                subprocess.check_output("sudo touch /etc/uwsgi/vassals/%s.ini" % os.path.basename(settings.PROJECT_ROOT),
                                    stderr=subprocess.STDOUT, shell=True)

            except subprocess.CalledProcessError as e:
                uwsgi_error_msg = e.output

        if gunicorn_error_msg and uwsgi_error_msg:
            errors_list.append(uwsgi_error_msg)
            errors_list.append(gunicorn_error_msg)

        try:
            print("Clearing cache")
            call_command('clear_cache')
        except CommandError as e:
            errors_list.append(e.output)

        email_context['errors_list'] = errors_list

        if email_recipient:
            subject = render_to_string('notification/update_tendenci_notice/short.txt', email_context)
            subject = subject.strip('\n').strip('\r')
            body = render_to_string('notification/update_tendenci_notice/full.html', email_context)
            email = EmailMessage()
            email.subject = subject
            email.body = body
            email.from_email = email_sender
            email.to = [email_recipient]
            email.content_subtype = 'html'
            email.send()
Пример #34
0
    def post(self, req, *args, **kwargs):
        report = dict([(key, req.POST.get(key, '')) for key in (
            'subject',
            'username',
            'domain',
            'url',
            'message',
            'app_id',
            'cc',
            'email',
            '500traceback',
            'sentry_id',
        )])

        try:
            couch_user = req.couch_user
            full_name = couch_user.full_name
            if couch_user.is_commcare_user():
                email = report['email']
            else:
                email = couch_user.get_email()
        except Exception:
            full_name = None
            email = report['email']
        report['full_name'] = full_name
        report['email'] = email or report['username']

        if report['domain']:
            domain = report['domain']
        elif len(couch_user.domains) == 1:
            # This isn't a domain page, but the user has only one domain, so let's use that
            domain = couch_user.domains[0]
        else:
            domain = "<no domain>"

        message = (
            "username: {username}\n"
            "full name: {full_name}\n"
            "domain: {domain}\n"
            "url: {url}\n"
        ).format(**report)

        domain_object = Domain.get_by_name(domain) if report['domain'] else None
        debug_context = {
            'datetime': datetime.utcnow(),
            'self_started': '<unknown>',
            'scale_backend': '<unknown>',
            'has_handoff_info': '<unknown>',
            'project_description': '<unknown>',
            'sentry_error': '{}{}'.format(getattr(settings, 'SENTRY_QUERY_URL'), report['sentry_id'])
        }
        if domain_object:
            current_project_description = domain_object.project_description if domain_object else None
            new_project_description = req.POST.get('project_description')
            if (domain_object and
                    req.couch_user.is_domain_admin(domain=domain) and
                    new_project_description and current_project_description != new_project_description):
                domain_object.project_description = new_project_description
                domain_object.save()

            message += ((
                "software plan: {software_plan}\n"
            ).format(
                software_plan=Subscription.get_subscribed_plan_by_domain(domain),
            ))

            debug_context.update({
                'self_started': domain_object.internal.self_started,
                'scale_backend': should_use_sql_backend(domain),
                'has_handoff_info': bool(domain_object.internal.partner_contact),
                'project_description': domain_object.project_description,
            })

        subject = '{subject} ({domain})'.format(subject=report['subject'], domain=domain)
        cc = [el for el in report['cc'].strip().split(",") if el]

        if full_name and not any([c in full_name for c in '<>"']):
            reply_to = '"{full_name}" <{email}>'.format(**report)
        else:
            reply_to = report['email']

        # if the person looks like a commcare user, fogbugz can't reply
        # to their email, so just use the default
        if settings.HQ_ACCOUNT_ROOT in reply_to:
            reply_to = settings.SERVER_EMAIL

        message += "Message:\n\n{message}\n".format(message=report['message'])
        if req.POST.get('five-hundred-report'):
            extra_message = ("This message was reported from a 500 error page! "
                             "Please fix this ASAP (as if you wouldn't anyway)...")
            extra_debug_info = (
                "datetime: {datetime}\n"
                "Is self start: {self_started}\n"
                "Is scale backend: {scale_backend}\n"
                "Has Support Hand-off Info: {has_handoff_info}\n"
                "Project description: {project_description}\n"
                "Sentry Error: {sentry_error}\n"
            ).format(**debug_context)
            traceback_info = cache.cache.get(report['500traceback']) or 'No traceback info available'
            cache.cache.delete(report['500traceback'])
            message = "\n\n".join([message, extra_debug_info, extra_message, traceback_info])

        email = EmailMessage(
            subject=subject,
            body=message,
            to=self.recipients,
            headers={'Reply-To': reply_to},
            cc=cc
        )

        uploaded_file = req.FILES.get('report_issue')
        if uploaded_file:
            filename = uploaded_file.name
            content = uploaded_file.read()
            email.attach(filename=filename, content=content)

        # only fake the from email if it's an @dimagi.com account
        is_icds_env = settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS
        if re.search(r'@dimagi\.com$', report['username']) and not is_icds_env:
            email.from_email = report['username']
        else:
            email.from_email = settings.CCHQ_BUG_REPORT_EMAIL

        email.send(fail_silently=False)

        if req.POST.get('five-hundred-report'):
            messages.success(
                req,
                "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem."
            )
            return HttpResponseRedirect(reverse('homepage'))

        return HttpResponse()
Пример #35
0
def bug_report(req):
    report = dict([(key, req.POST.get(key, ''))
                   for key in ('subject', 'username', 'domain', 'url',
                               'message', 'app_id', 'cc')])

    report['user_agent'] = req.META['HTTP_USER_AGENT']
    report['datetime'] = datetime.utcnow()

    if report['app_id']:
        app = import_app(report['app_id'], BUG_REPORTS_DOMAIN)
        report['copy_url'] = "%s%s" % (
            get_url_base(),
            reverse('view_app', args=[BUG_REPORTS_DOMAIN, app.id]))
    else:
        report['copy_url'] = None

    try:
        couch_user = CouchUser.get_by_username(report['username'])
        full_name = couch_user.full_name
        email = couch_user.get_email()
    except Exception:
        full_name = None
        email = None
    report['full_name'] = full_name
    report['email'] = email or report['username']

    matching_subscriptions = Subscription.objects.filter(
        is_active=True,
        subscriber__domain=report['domain'],
    )

    if len(matching_subscriptions) >= 1:
        report['software_plan'] = matching_subscriptions[0].plan_version
    else:
        report['software_plan'] = u'domain has no active subscription'

    subject = u'{subject} ({domain})'.format(**report)
    message = (u"username: {username}\n"
               u"full name: {full_name}\n"
               u"domain: {domain}\n"
               u"software plan: {software_plan}\n"
               u"url: {url}\n"
               u"copy url: {copy_url}\n"
               u"datetime: {datetime}\n"
               u"User Agent: {user_agent}\n"
               u"Message:\n\n"
               u"{message}\n").format(**report)
    cc = report['cc'].strip().split(",")
    cc = filter(None, cc)

    if full_name and not any([c in full_name for c in '<>"']):
        reply_to = u'"{full_name}" <{email}>'.format(**report)
    else:
        reply_to = report['email']

    # if the person looks like a commcare user, fogbugz can't reply
    # to their email, so just use the default
    if settings.HQ_ACCOUNT_ROOT in reply_to:
        reply_to = settings.SERVER_EMAIL

    if req.POST.get('five-hundred-report'):
        message = "%s \n\n This messge was reported from a 500 error page! Please fix this ASAP (as if you wouldn't anyway)..." % message
    email = EmailMessage(subject=subject,
                         body=message,
                         to=settings.BUG_REPORT_RECIPIENTS,
                         headers={'Reply-To': reply_to},
                         cc=cc)

    uploaded_file = req.FILES.get('report_issue')
    if uploaded_file:
        filename = uploaded_file.name
        content = uploaded_file.read()
        email.attach(filename=filename, content=content)

    # only fake the from email if it's an @dimagi.com account
    if re.search('@dimagi\.com$', report['username']):
        email.from_email = report['username']
    else:
        email.from_email = settings.CCHQ_BUG_REPORT_EMAIL

    email.send(fail_silently=False)

    if req.POST.get('five-hundred-report'):
        messages.success(
            req,
            "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem."
        )
        return HttpResponseRedirect(reverse('homepage'))

    return HttpResponse()
Пример #36
0
def send_message(subject_user, user_context_html, from_email, to_email):
    message_user = EmailMessage(subject_user, user_context_html, from_email,
                                [to_email])
    message_user.content_subtype = "html"
    message_user.send(fail_silently=True)
Пример #37
0
def bug_report(req):
    report = dict([(key, req.POST.get(key, '')) for key in (
        'subject',
        'username',
        'domain',
        'url',
        'message',
        'app_id',
        'cc',
        'email',
        '500traceback',
    )])

    domain_object = Domain.get_by_name(report['domain'])
    current_project_description = domain_object.project_description if domain_object else None
    new_project_description = req.POST.get('project_description')
    if (domain_object
            and req.couch_user.is_domain_admin(domain=report['domain'])
            and new_project_description
            and current_project_description != new_project_description):

        domain_object.project_description = new_project_description
        domain_object.save()

    report['user_agent'] = req.META['HTTP_USER_AGENT']
    report['datetime'] = datetime.utcnow()
    report['feature_flags'] = toggles.toggles_dict(
        username=report['username'], domain=report['domain']).keys()
    report['feature_previews'] = feature_previews.previews_dict(
        report['domain']).keys()
    report['scale_backend'] = should_use_sql_backend(
        report['domain']) if report['domain'] else False
    report[
        'project_description'] = domain_object.project_description if domain_object else '(Not applicable)'

    try:
        couch_user = req.couch_user
        full_name = couch_user.full_name
        if couch_user.is_commcare_user():
            email = report['email']
        else:
            email = couch_user.get_email()
    except Exception:
        full_name = None
        email = report['email']
    report['full_name'] = full_name
    report['email'] = email or report['username']

    matching_subscriptions = Subscription.objects.filter(
        is_active=True,
        subscriber__domain=report['domain'],
    )

    if len(matching_subscriptions) >= 1:
        report['software_plan'] = matching_subscriptions[0].plan_version
    else:
        report['software_plan'] = u'domain has no active subscription'

    subject = u'{subject} ({domain})'.format(**report)
    message = (u"username: {username}\n"
               u"full name: {full_name}\n"
               u"domain: {domain}\n"
               u"software plan: {software_plan}\n"
               u"url: {url}\n"
               u"datetime: {datetime}\n"
               u"User Agent: {user_agent}\n"
               u"Feature Flags: {feature_flags}\n"
               u"Feature Previews: {feature_previews}\n"
               u"Is scale backend: {scale_backend}\n"
               u"Project description: {project_description}\n"
               u"Message:\n\n"
               u"{message}\n").format(**report)
    cc = report['cc'].strip().split(",")
    cc = filter(None, cc)

    if full_name and not any([c in full_name for c in '<>"']):
        reply_to = u'"{full_name}" <{email}>'.format(**report)
    else:
        reply_to = report['email']

    # if the person looks like a commcare user, fogbugz can't reply
    # to their email, so just use the default
    if settings.HQ_ACCOUNT_ROOT in reply_to:
        reply_to = settings.SERVER_EMAIL

    if req.POST.get('five-hundred-report'):
        extra_message = ("This messge was reported from a 500 error page! "
                         "Please fix this ASAP (as if you wouldn't anyway)...")
        traceback_info = cache.cache.get(report['500traceback'])
        cache.cache.delete(report['500traceback'])
        traceback_info = "Traceback of this 500: \n%s" % traceback_info
        message = "%s \n\n %s \n\n %s" % (message, extra_message,
                                          traceback_info)

    email = EmailMessage(subject=subject,
                         body=message,
                         to=settings.BUG_REPORT_RECIPIENTS,
                         headers={'Reply-To': reply_to},
                         cc=cc)

    uploaded_file = req.FILES.get('report_issue')
    if uploaded_file:
        filename = uploaded_file.name
        content = uploaded_file.read()
        email.attach(filename=filename, content=content)

    # only fake the from email if it's an @dimagi.com account
    if re.search('@dimagi\.com$', report['username']):
        email.from_email = report['username']
    else:
        email.from_email = settings.CCHQ_BUG_REPORT_EMAIL

    email.send(fail_silently=False)

    if req.POST.get('five-hundred-report'):
        messages.success(
            req,
            "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem."
        )
        return HttpResponseRedirect(reverse('homepage'))

    return HttpResponse()
Пример #38
0
def _generate_notification_for_seqr_match(submission, results):
    """
    Generate a notifcation to say that a match happened initiated from a seqr user.
    """
    matches = []
    hpo_terms_by_id, genes_by_id, _ = get_mme_genes_phenotypes_for_results(
        results)
    for result in results:
        patient = result['patient']

        gene_message = ''
        if patient.get('genomicFeatures'):
            gene_symbols = set()
            for gene in patient['genomicFeatures']:
                gene_symbol = gene['gene']['id']
                if gene_symbol.startswith('ENSG'):
                    gene_symbol = genes_by_id.get(gene_symbol, {}).get(
                        'geneSymbol', gene_symbol)
                gene_symbols.add(gene_symbol)

            gene_message = ' with genes {}'.format(' '.join(
                sorted(gene_symbols)))

        phenotypes_message = ''
        if patient.get('features'):
            phenotypes_message = ' with phenotypes {}'.format(' '.join([
                '{} ({})'.format(feature['id'],
                                 hpo_terms_by_id.get(feature['id']))
                for feature in patient['features']
            ]))

        matches.append(
            ' - From {contact} at institution {institution}{gene_message}{phenotypes_message}.'
            .format(
                contact=patient['contact'].get('name', '(none given)'),
                institution=patient['contact'].get('institution',
                                                   '(none given)'),
                gene_message=gene_message,
                phenotypes_message=phenotypes_message,
            ))

    individual = submission.individual
    project = individual.family.project
    message = u"""
    A search from a seqr user from project {project} individual {individual_id} had the following new match(es):
    
    {matches}
    
    {host}project/{project_guid}/family_page/{family_guid}/matchmaker_exchange
    """.format(
        project=project.name,
        individual_id=individual.individual_id,
        matches='\n\n'.join(matches),
        host=BASE_URL,
        project_guid=project.guid,
        family_guid=submission.individual.family.guid,
    )

    post_to_slack(MME_SLACK_SEQR_MATCH_NOTIFICATION_CHANNEL, message)
    emails = map(lambda s: s.strip().split('mailto:')[-1],
                 submission.contact_href.split(','))
    email_message = EmailMessage(
        subject=u'New matches found for MME submission {} (project: {})'.
        format(individual.individual_id, project.name),
        body=message,
        to=[email for email in emails if email != MME_DEFAULT_CONTACT_EMAIL],
        from_email=MME_DEFAULT_CONTACT_EMAIL,
    )
    email_message.send()
Пример #39
0
 def run(self):
     msg = EmailMessage(self.subject, self.html_content, EMAIL_HOST_USER,
                        self.recipient_list)
     msg.content_subtype = "html"
     msg.send()
Пример #40
0
    def post(self, req, *args, **kwargs):
        report = dict([(key, req.POST.get(key, '')) for key in (
            'subject',
            'username',
            'domain',
            'url',
            'message',
            'app_id',
            'cc',
            'email',
            '500traceback',
            'sentry_id',
        )])

        report['user_agent'] = req.META['HTTP_USER_AGENT']
        report['datetime'] = datetime.utcnow()

        try:
            couch_user = req.couch_user
            full_name = couch_user.full_name
            if couch_user.is_commcare_user():
                email = report['email']
            else:
                email = couch_user.get_email()
        except Exception:
            full_name = None
            email = report['email']
        report['full_name'] = full_name
        report['email'] = email or report['username']

        if report['domain']:
            domain = report['domain']
        elif len(couch_user.domains) == 1:
            # This isn't a domain page, but the user has only one domain, so let's use that
            domain = couch_user.domains[0]
        else:
            domain = "<no domain>"

        message = (
            u"username: {username}\n"
            u"full name: {full_name}\n"
            u"domain: {domain}\n"
            u"url: {url}\n"
            u"datetime: {datetime}\n"
            u"User Agent: {user_agent}\n"
        ).format(**report)

        domain_object = Domain.get_by_name(domain) if report['domain'] else None
        if domain_object:
            current_project_description = domain_object.project_description if domain_object else None
            new_project_description = req.POST.get('project_description')
            if (domain_object and
                    req.couch_user.is_domain_admin(domain=domain) and
                    new_project_description and current_project_description != new_project_description):
                domain_object.project_description = new_project_description
                domain_object.save()

            matching_subscriptions = Subscription.visible_objects.filter(
                is_active=True,
                subscriber__domain=domain,
            )
            if len(matching_subscriptions) >= 1:
                software_plan = matching_subscriptions[0].plan_version
            else:
                software_plan = u'domain has no active subscription'

            message += ((
                u"software plan: {software_plan}\n"
                u"Is self start: {self_started}\n"
                u"Feature Flags: {feature_flags}\n"
                u"Feature Previews: {feature_previews}\n"
                u"Is scale backend: {scale_backend}\n"
                u"Has Support Hand-off Info: {has_handoff_info}\n"
                u"Internal Project Information: {internal_info_link}\n"
                u"Project description: {project_description}\n"
                u"Sentry Error: {sentry_error}\n"
            ).format(
                software_plan=software_plan,
                self_started=domain_object.internal.self_started,
                feature_flags=list(toggles.toggles_dict(username=report['username'], domain=domain)),
                feature_previews=list(feature_previews.previews_dict(domain)),
                scale_backend=should_use_sql_backend(domain),
                has_handoff_info=bool(domain_object.internal.partner_contact),
                internal_info_link=reverse('domain_internal_settings', args=[domain], absolute=True),
                project_description=domain_object.project_description,
                sentry_error='{}{}'.format(getattr(settings, 'SENTRY_QUERY_URL'), report['sentry_id'])
            ))

        subject = u'{subject} ({domain})'.format(subject=report['subject'], domain=domain)
        cc = [el for el in report['cc'].strip().split(",") if el]

        if full_name and not any([c in full_name for c in '<>"']):
            reply_to = u'"{full_name}" <{email}>'.format(**report)
        else:
            reply_to = report['email']

        # if the person looks like a commcare user, fogbugz can't reply
        # to their email, so just use the default
        if settings.HQ_ACCOUNT_ROOT in reply_to:
            reply_to = settings.SERVER_EMAIL

        message += u"Message:\n\n{message}\n".format(message=report['message'])
        if req.POST.get('five-hundred-report'):
            extra_message = ("This messge was reported from a 500 error page! "
                             "Please fix this ASAP (as if you wouldn't anyway)...")
            traceback_info = cache.cache.get(report['500traceback'])
            cache.cache.delete(report['500traceback'])
            message = "%s \n\n %s \n\n %s" % (message, extra_message, traceback_info)

        email = EmailMessage(
            subject=subject,
            body=message,
            to=self.recipients,
            headers={'Reply-To': reply_to},
            cc=cc
        )

        uploaded_file = req.FILES.get('report_issue')
        if uploaded_file:
            filename = uploaded_file.name
            content = uploaded_file.read()
            email.attach(filename=filename, content=content)

        # only fake the from email if it's an @dimagi.com account
        if re.search('@dimagi\.com$', report['username']):
            email.from_email = report['username']
        else:
            email.from_email = settings.CCHQ_BUG_REPORT_EMAIL

        email.send(fail_silently=False)

        if req.POST.get('five-hundred-report'):
            messages.success(
                req,
                "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem."
            )
            return HttpResponseRedirect(reverse('homepage'))

        return HttpResponse()
Пример #41
0
def subscribe_with_key(req):
    key = req.GET.get("key", "")
    if not key:
        return HttpResponse(UR.prepare_response({}, 1, "NOT ALLOWED"))
    e = M.Ensemble.objects.get(invitekey=key)
    if not e.use_invitekey:
        return HttpResponse(UR.prepare_response({}, 1, "NOT ALLOWED"))
    auth_user = UR.getUserInfo(req)
    if req.method == 'GET':
        if auth_user is None:  # Guest retrieving the subscribe page
            remote_form = RemoteForm(forms.UserForm())
            return HttpResponse(
                UR.prepare_response({
                    "new_user": True,
                    "class_settings": UR.model2dict(e),
                    "form": remote_form.as_dict()
                }))
        else:  # Logged in user retrieving the subscribe page
            user = auth_user
            remote_form = RemoteForm(forms.UserForm(instance=user))
            m = M.Membership.objects.filter(user=user, ensemble=e)
            if m.count() == 0:
                m = M.Membership(user=user, ensemble=e)
                m.save()
            return HttpResponse(
                UR.prepare_response({
                    "new_user": False,
                    "user": UR.model2dict(user),
                    "class_settings": UR.model2dict(e),
                    "form": remote_form.as_dict()
                }))
    else:  # POST requests
        if auth_user is None:  # Guest subscribing to a class
            user = M.User(confkey="".join([
                choice(string.ascii_letters + string.digits)
                for i in xrange(0, 32)
            ]))
            req.POST = dict(req.POST.iteritems()
                            )  # Convert immutable object to mutable object
            user_form = forms.UserForm(req.POST, instance=user)
            if user_form.is_valid():
                user_form.save()
                m = M.Membership(user=user, ensemble=e)
                m.save(
                )  # membership exists but user is still invalid until has confirmed their email
                p = {
                    "tutorial_url":
                    settings.GUEST_TUTORIAL_URL,
                    "conf_url":
                    "%s://%s/?ckey=%s" %
                    (settings.PROTOCOL, settings.NB_SERVERNAME, user.confkey),
                    "firstname":
                    user.firstname,
                    "email":
                    user.email
                }
                email = EmailMessage(
                    "Welcome to NB, %s" % (user.firstname, ),
                    render_to_string("email/confirm_subscribe",
                                     p), settings.EMAIL_FROM, (user.email, ),
                    (settings.EMAIL_BCC, ))
                email.send()
                return HttpResponse(
                    UR.prepare_response({
                        "new_user": True,
                        "class_settings": UR.model2dict(e),
                        "next": "/subscribe_thanks"
                    }))
            else:  # Invalid form - return form with error messages
                __clean_form(
                    user_form
                )  # Ensure user-generated data gets cleaned before sending back the form
                remote_form = RemoteForm(user_form)
                return HttpResponse(
                    UR.prepare_response({
                        "new_user": True,
                        "user": UR.model2dict(user),
                        "class_settings": UR.model2dict(e),
                        "form": remote_form.as_dict()
                    }))
        else:  # Logged in user subscribing to a class
            user = auth_user
            m = M.Membership.objects.filter(user=user, ensemble=e)
            if m.count() == 0:
                m = M.Membership(user=user, ensemble=e)
                m.save()
            return HttpResponse(
                UR.prepare_response({
                    "new_user": False,
                    "class_settings": UR.model2dict(e),
                    "next": "/"
                }))
Пример #42
0
 def email_sender(self, body, to_email):
     title = "email verification!"
     email = EmailMessage(title, body, to=[to_email])
     email.send()
Пример #43
0
    def handle(self, *args, **options):
        from tendenci.apps.site_settings.utils import get_setting
        from tendenci import __version__ as version
        from tendenci.apps.base.utils import get_latest_version

        verbosity = int(options['verbosity'])
        user_id = options['user_id']
        if user_id:
            [request_user] = User.objects.filter(pk=user_id)[:1] or [None]
        else:
            request_user = None
        site_url = get_setting('site', 'global', 'siteurl')

        # check what tendenci version we're on
        major_bit = int(version.split('.')[0])
        if major_bit < 7:
            if verbosity >1:
                print("No update for this version {}.".format(version))
                print("Please consider to upgrade https://tendenci.readthedocs.org/en/latest/")
            return

        project_root = settings.PROJECT_ROOT
        err_list = []

        # check the latest version
        latest_version = get_latest_version()
        if int(latest_version.split('.')[0]) < 7 or  version == latest_version:
            # STOP - NO UPDATE
            return
        if verbosity >1:
            print("Latest version: {}".format(latest_version))
            print("Your version: {}".format(version))
            print("Start updating...")

        # update some files - deploy.py, requirements/tendenci.txt
        files_to_update = {'deploy.py': 'https://raw.githubusercontent.com/tendenci/tendenci-project-template/master/deploy.py',
                           'requirements/tendenci.txt': 'https://raw.githubusercontent.com/tendenci/tendenci-project-template/master/requirements/tendenci.txt'
                        }
        for key, value in files_to_update.items():
            try:
                subprocess.check_output('curl {0} > {1}/{2}'.format(value, project_root, key),
                                        stderr=subprocess.STDOUT, shell=True)
            except subprocess.CalledProcessError as e:
                err_list.append(e.output)

        # update tendenci
        if not err_list:
            try:
                if verbosity >1:
                    print("Updating tendenci...")
                update_cmd = '{0} -m pip install -r {1}/{2} --upgrade'.format(python_executable(), project_root, 'requirements/tendenci.txt')
                subprocess.check_output('cd {}; {}'.format(project_root, update_cmd),
                                        stderr=subprocess.STDOUT, shell=True)
            except subprocess.CalledProcessError as e:
                err_list.append(e.output)

        if not err_list:
            # run migrate, collectstatic, etc via deploy.py
            try:
                subprocess.check_output("cd {0}; {1} manage.py migrate".format(latest_version, python_executable()),

                                        stderr=subprocess.STDOUT, shell=True)
            except subprocess.CalledProcessError as e:
                known_error = "BadMigrationError: Migrated app 'djcelery' contains South migrations"
                known_error2 = 'relation "djcelery_crontabschedule" already exists'
                if known_error in e.output or known_error2 in e.output:
                    try:
                        subprocess.check_output("cd {0}; {1} manage.py migrate djcelery 0001 --fake".format(latest_version, python_executable()),
                                            stderr=subprocess.STDOUT, shell=True)
                        subprocess.check_output("cd {0}; {1} manage.py migrate".format(latest_version, python_executable()),
                                            stderr=subprocess.STDOUT, shell=True)
                    except subprocess.CalledProcessError as e:
                        err_list.append(e.output)
        if not err_list:
            # run deploy.py
            try:
                subprocess.check_output("cd {0}; {1} deploy.py".format(latest_version, python_executable()),
                                        stderr=subprocess.STDOUT, shell=True)
            except subprocess.CalledProcessError as e:
                err_list.append(e.output)

        if not err_list:
            if verbosity >1:
                print('Reloading the site...')
            # reload the site.
            # it's a guessing game here - because we don't know what wsgi server the site is behind
            # and how exactly the site was set up
            try:
                subprocess.check_output("sudo reload %s" % os.path.basename(settings.PROJECT_ROOT),
                                        stderr=subprocess.STDOUT, shell=True)
            except subprocess.CalledProcessError as e:
                try:
                    subprocess.check_output("sudo sv kill tendenci_site && sv start tendenci_site",
                                            stderr=subprocess.STDOUT, shell=True)
                except subprocess.CalledProcessError as e:
                    err_list.append(e.output)

        if verbosity >1:
            if err_list:
                print('Sorry, updating tendenci is not complete due to the following error(s):\n\n')
                print('\n\n'.join(err_list))
            else:
                print("Update is done.")

        if request_user and request_user.email:
            # notify update is done
            if err_list:
                subject = 'Error on updating tendenci %s' % site_url
                body = 'Error(s) encountered on updating tendenci:\n\n'
                body += '\n\n'.join(err_list)
            else:
                subject = 'Update ams365 is done %s' % site_url
                body = 'Successfully updated tendenci for %s.\n\n' % site_url
                body += 'AMS365 version: %s\n\n' % latest_version
            body += "Thanks!\n%s\n\n" % get_setting('site', 'global', 'sitedisplayname')

            msg = EmailMessage(subject, body, settings.DEFAULT_FROM_EMAIL, [request_user.email])
            msg.send()
Пример #44
0
def newsite_form(req):
    import base.models as M, random, string
    auth_user = UR.getUserInfo(req)
    if auth_user is not None:
        return HttpResponse(UR.prepare_response({"redirect": "/"}))
    if req.method == 'GET':
        remote_user_form = RemoteForm(forms.UserForm())
        remote_class_form = RemoteForm(forms.EnsembleForm())
        return HttpResponse(
            UR.prepare_response({
                "user_form": remote_user_form.as_dict(),
                "class_form": remote_class_form.as_dict()
            }))
    else:
        user = M.User(confkey="".join([
            choice(string.ascii_letters + string.digits)
            for i in xrange(0, 32)
        ]))
        ensemble = M.Ensemble()
        req.POST = dict(
            req.POST.iteritems())  # Convert immutable object to mutable object
        user_form = forms.UserForm(req.POST, instance=user)
        ensemble_form = forms.EnsembleForm(req.POST, instance=ensemble)
        if user_form.is_valid() and ensemble_form.is_valid():
            user_form.save()
            ensemble.invitekey = "".join([
                random.choice(string.ascii_letters + string.digits)
                for i in xrange(0, 50)
            ])
            ensemble_form.save()
            m = M.Membership(user=user, ensemble=ensemble, admin=True)
            m.save()
            p = {
                "tutorial_url":
                settings.GUEST_TUTORIAL_URL,
                "conf_url":
                "http://%s?ckey=%s" % (settings.NB_SERVERNAME, user.confkey),
                "firstname":
                user.firstname,
                "email":
                user.email
            }
            email = EmailMessage("Welcome to NB, %s" % (user.firstname),
                                 render_to_string("email/confirm_newsite",
                                                  p), settings.EMAIL_FROM,
                                 (user.email, ), (settings.EMAIL_BCC, ))
            email.send()
            return HttpResponse(
                UR.prepare_response({"redirect": "/newsite_thanks"}))
        else:  # Invalid form - return form with error messages
            __clean_form(
                user_form
            )  # Ensure user-generated data gets cleaned before sending back the form
            __clean_form(
                ensemble_form
            )  # Ensure user-generated data gets cleaned before sending back the form
            remote_user_form = RemoteForm(user_form)
            remote_class_form = RemoteForm(ensemble_form)
            return HttpResponse(
                UR.prepare_response({
                    "user_form": remote_user_form.as_dict(),
                    "class_form": remote_class_form.as_dict()
                }))
Пример #45
0
def send_email_to_staff_on_student_enrollment(sender,
                                              event=None,
                                              user=None,
                                              **kwargs):  # pylint: disable=unused-argument
    """
    Sends an e-mail to staff after a new enrollment.
    This feature can be enabled by setting the e-mail of the staff in ENROLLMENT_NOTIFICATION_EMAIL in lms.env.json,
    or by using a SiteConfiguration variable of the same name (which will override the env one).
    Disabled by default.
    """

    if event == EnrollStatusChange.enroll:
        to_email = configuration_helpers.get_value(
            'ENROLLMENT_NOTIFICATION_EMAIL',
            settings.ENROLLMENT_NOTIFICATION_EMAIL)

        if not to_email:
            # feature disabled
            return

        course_id = kwargs['course_id']

        site_protocol = 'https' if settings.HTTPS == 'on' else 'http'
        site_domain = configuration_helpers.get_value('site_domain',
                                                      settings.SITE_NAME)
        context = {
            'user':
            user,
            # This full_name is dependent on edx-platform's profile implementation
            'user_full_name':
            user.profile.name if hasattr(user, 'profile') else None,
            'course_url':
            urlunsplit((site_protocol, site_domain,
                        reverse('about_course',
                                args=[course_id.to_deprecated_string()]), None,
                        None)),
            'user_admin_url':
            urlunsplit((
                site_protocol,
                site_domain,
                reverse('admin:auth_user_change', args=[user.id]),
                None,
                None,
            )),
        }
        subject = ''.join(
            render_to_string('emails/new_enrollment_email_subject.txt',
                             context).splitlines())
        message = render_to_string('emails/new_enrollment_email_body.txt',
                                   context)

        email = EmailMessage(subject=subject,
                             body=message,
                             from_email=settings.DEFAULT_FROM_EMAIL,
                             to=[to_email])

        try:
            email.send()
        except SMTPException as exception:
            LOGGER.error("Failed sending e-mail about new enrollment to %s",
                         to_email)
            LOGGER.exception(exception)
Пример #46
0
    def send(self, fail_silently=False, **kwargs):
        recipient_list = []
        recipient_bcc_list = []
        headers = kwargs.get('headers', {})
        attachments = kwargs.get('attachments', [])

        if isinstance(self.recipient, basestring):
            recipient_list = self.recipient.split(',')
            recipient_list = [recipient.strip() for recipient in recipient_list \
                              if recipient.strip() <> '']
        else:
            recipient_list = list(self.recipient)
        if isinstance(self.recipient_cc, basestring):
            recipient_cc_list = self.recipient_cc.split(',')
            recipient_cc_list = [recipient_cc.strip() for recipient_cc in recipient_cc_list if \
                                  recipient_cc.strip() <> '']
            recipient_list += recipient_cc_list
        else:
            recipient_list += list(self.recipient_cc)
        if isinstance(self.recipient_bcc, basestring):
            recipient_bcc_list = self.recipient_bcc.split(',')
            recipient_bcc_list = [recipient_bcc.strip() for recipient_bcc in recipient_bcc_list if \
                                   recipient_bcc.strip() <> '']
        else:
            recipient_bcc_list = list(self.recipient_bcc)

        if self.reply_to:
            headers['Reply-To'] = self.reply_to
        if not self.sender:
            self.sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        if self.sender_display:
            # Add quotes around display name to prevent errors on sending
            # When display name contains comma or other control characters,
            headers['From'] = '"%s"<%s>' % (self.sender_display, self.sender)
        if self.priority and self.priority == 1:
            headers['X-Priority'] = '1'
            headers['X-MSMail-Priority'] = 'High'

        # remove blocked from recipient_list and recipient_bcc_list
        temp_recipient_list = copy.copy(recipient_list)
        for e in temp_recipient_list:
            if self.is_blocked(e):
                recipient_list.remove(e)
        temp_recipient_bcc_list = copy.copy(recipient_bcc_list)
        for e in temp_recipient_bcc_list:
            if self.is_blocked(e):
                recipient_bcc_list.remove(e)

        if recipient_list or recipient_bcc_list:
            msg = EmailMessage(self.subject,
                               self.body,
                               self.sender,
                               recipient_list,
                               recipient_bcc_list,
                               headers=headers,
                               connection=kwargs.get('connection', None))
            if self.content_type == 'html' or self.content_type == self.CONTENT_TYPE_HTML:
                msg.content_subtype = 'html'
            if attachments:
                msg.attachments = attachments
            msg.send(fail_silently=fail_silently)
Пример #47
0
def _generate_notification_for_incoming_match(results, incoming_query,
                                              incoming_request_node,
                                              incoming_patient):
    """
    Generate a SLACK notifcation to say that a VALID match request came in and the following
    results were sent back. If Slack is not supported, a message is not sent, but details persisted.

    Args:
        response_from_matchbox (python requests object): contains the response from matchbox
        incoming_request (Django request object): The request that came into the view
        incoming_patient (JSON): The query patient JSON structure from outside MME node that was matched with
    """
    incoming_patient_id = incoming_patient['patient']['id']

    logger.info('{} MME matches found for patient {} from {}'.format(
        len(results), incoming_patient_id, incoming_request_node))

    institution = incoming_patient['patient']['contact'].get(
        'institution', incoming_request_node)
    contact_href = incoming_patient['patient']['contact'].get(
        'href', '(sorry I was not able to read the information given for URL)')

    if not results:
        message_template = """A match request for {patient_id} came in from {institution} today.
        The contact information given was: {contact}.
        We didn't find any individuals in matchbox that matched that query well, *so no results were sent back*."""
        post_to_slack(
            MME_SLACK_MATCH_NOTIFICATION_CHANNEL,
            message_template.format(institution=institution,
                                    patient_id=incoming_patient_id,
                                    contact=contact_href))
        return

    new_matched_results = MatchmakerResult.objects.filter(
        originating_query=incoming_query).prefetch_related('submission')
    if not new_matched_results:
        message_template = """A match request for {patient_id} came in from {institution} today.
        The contact information given was: {contact}.
        We found {existing_results} existing matching individuals but no new ones, *so no results were sent back*."""
        post_to_slack(
            MME_SLACK_MATCH_NOTIFICATION_CHANNEL,
            message_template.format(institution=institution,
                                    patient_id=incoming_patient_id,
                                    contact=contact_href,
                                    existing_results=len(results)))
        return

    hpo_terms_by_id, genes_by_id, _ = get_mme_genes_phenotypes_for_results(
        [incoming_patient])

    match_results = []
    all_emails = set()
    for result in new_matched_results:
        submission = result.submission
        individual = submission.individual
        project = individual.family.project

        result_text = """seqr ID {individual_id} from project {project_name} in family {family_id} inserted into
matchbox on {insertion_date}, with seqr link
{host}project/{project_guid}/family_page/{family_guid}/matchmaker_exchange""".replace(
            '\n', ' ').format(
                individual_id=individual.individual_id,
                project_guid=project.guid,
                project_name=project.name,
                family_guid=individual.family.guid,
                family_id=individual.family.family_id,
                insertion_date=submission.created_date.strftime('%b %d, %Y'),
                host=BASE_URL)
        emails = [
            email.strip() for email in submission.contact_href.replace(
                'mailto:', '').split(',')
            if email.strip() != MME_DEFAULT_CONTACT_EMAIL
        ]
        all_emails.update(emails)
        match_results.append((result_text, emails))
    match_results = sorted(match_results,
                           key=lambda result_tuple: result_tuple[0])

    base_message = """Dear collaborators,

    matchbox found a match between a patient from {query_institution} and the following {number_of_results} case(s) 
    in matchbox. The following information was included with the query,

    genes: {incoming_query_genes}
    phenotypes: {incoming_query_phenotypes}
    contact: {incoming_query_contact_name}
    email: {incoming_query_contact_url}

    We sent back the following:

    """.format(
        query_institution=institution,
        number_of_results=len(results),
        incoming_query_genes=', '.join(
            sorted([gene['geneSymbol'] for gene in genes_by_id.values()])),
        incoming_query_phenotypes=', '.join([
            '{} ({})'.format(hpo_id, term)
            for hpo_id, term in hpo_terms_by_id.items()
        ]),
        incoming_query_contact_url=contact_href,
        incoming_query_contact_name=incoming_patient['patient']['contact'].get(
            'name',
            '(sorry I was not able to read the information given for name'),
    )

    message_template = """{base_message}{match_results}

    We sent this email alert to: {email_addresses_alert_sent_to}\n{footer}."""

    post_to_slack(
        MME_SLACK_MATCH_NOTIFICATION_CHANNEL,
        message_template.format(
            base_message=base_message,
            match_results='\n'.join([text for text, _ in match_results]),
            email_addresses_alert_sent_to=', '.join(sorted(all_emails)),
            footer=MME_EMAIL_FOOTER))

    for result_text, emails in match_results:
        email_message = EmailMessage(
            subject='Received new MME match',
            body=message_template.format(
                base_message=base_message,
                match_results=result_text,
                email_addresses_alert_sent_to=', '.join(emails),
                footer=MME_EMAIL_FOOTER),
            to=emails,
            from_email=MME_DEFAULT_CONTACT_EMAIL,
        )
        email_message.send()
Пример #48
0
def pmp_indicator_report():
    base_url = 'https://etools.unicef.org'
    countries = Country.objects.exclude(schema_name__in=['public', 'uat', 'frg'])
    fieldnames = [
        'Country',
        'Partner Name',
        'Partner Type',
        'PD / SSFA ref',
        'PD / SSFA status',
        'PD / SSFA start date',
        'PD / SSFA creation date',
        'PD / SSFA end date',
        'UNICEF US$ Cash contribution',
        'UNICEF US$ Supply contribution',
        'Total Budget',
        'UNICEF Budget',
        'Currency',
        'Partner Contribution',
        'Unicef Cash',
        'In kind Amount',
        'Total',
        'FR numbers against PD / SSFA',
        'FR currencies',
        'Sum of all FR planned amount',
        'Core value attached',
        'Partner Link',
        'Intervention Link',
    ]
    csvfile = StringIO()
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    for country in countries:
        connection.set_tenant(Country.objects.get(name=country.name))
        logger.info(u'Running on %s' % country.name)
        for partner in PartnerOrganization.objects.filter():
            for intervention in Intervention.objects.filter(
                    agreement__partner=partner).select_related('planned_budget'):
                planned_budget = getattr(intervention, 'planned_budget', None)
                fr_currencies = intervention.frs.all().values_list('currency', flat=True).distinct()
                writer.writerow({
                    'Country': country,
                    'Partner Name': str(partner),
                    'Partner Type': partner.cso_type,
                    'PD / SSFA ref': intervention.number.replace(',', '-'),
                    'PD / SSFA status': intervention.get_status_display(),
                    'PD / SSFA start date': intervention.start,
                    'PD / SSFA creation date': intervention.created,
                    'PD / SSFA end date': intervention.end,
                    'UNICEF US$ Cash contribution': intervention.total_unicef_cash,
                    'UNICEF US$ Supply contribution': intervention.total_in_kind_amount,
                    'Total Budget': intervention.total_budget,
                    'UNICEF Budget': intervention.total_unicef_budget,
                    'Currency': intervention.planned_budget.currency if planned_budget else '-',
                    'Partner Contribution': intervention.planned_budget.partner_contribution if planned_budget else '-',
                    'Unicef Cash': intervention.planned_budget.unicef_cash if planned_budget else '-',
                    'In kind Amount': intervention.planned_budget.in_kind_amount if planned_budget else '-',
                    'Total': intervention.planned_budget.total if planned_budget else '-',
                    'FR numbers against PD / SSFA': u' - '.join([fh.fr_number for fh in intervention.frs.all()]),
                    'FR currencies': ', '.join(fr for fr in fr_currencies),
                    'Sum of all FR planned amount': intervention.frs.aggregate(
                        total=Coalesce(Sum('intervention_amt'), 0))['total'] if fr_currencies.count() <= 1 else '-',
                    'Core value attached': True if partner.core_values_assessment else False,
                    'Partner Link': '{}/pmp/partners/{}/details'.format(base_url, partner.pk),
                    'Intervention Link': '{}/pmp/interventions/{}/details'.format(base_url, intervention.pk),
                })

    mail = EmailMessage('PMP Indicator Report', 'Report generated',
                        '*****@*****.**', settings.REPORT_EMAILS)
    mail.attach('pmp_indicators.csv', csvfile.getvalue().encode('utf-8'), 'text/csv')
    mail.send()
Пример #49
0
    def handle(self, *args, **options):
        outputfile = options.get('file')

        output_text = []

        output_text.append('@@@@@'.join([
            smart_str(u"ID"),
            smart_str(u"User"),
            smart_str(u"Date"),
            smart_str(u"Date Updated"),
            smart_str(u"Name (as stated on disclaimer)"),
            smart_str(u"DOB"),
            smart_str(u"Address"),
            smart_str(u"Postcode"),
            smart_str(u"Home Phone"),
            smart_str(u"Mobile Phone"),
            smart_str(u"Emergency Contact 1: Name"),
            smart_str(u"Emergency Contact 1: Relationship"),
            smart_str(u"Emergency Contact 1: Phone"),
            smart_str(u"Emergency Contact 2: Name"),
            smart_str(u"Emergency Contact 2: Relationship"),
            smart_str(u"Emergency Contact 2: Phone"),
            smart_str(u"Medical Conditions"),
            smart_str(u"Medical Conditions Details"),
            smart_str(u"Joint Problems"),
            smart_str(u"Joint Problems Details"),
            smart_str(u"Allergies"),
            smart_str(u"Allergies Details"),
            smart_str(u"Medical Treatment Terms"),
            smart_str(u"Medical Treatment Accepted"),
            smart_str(u"Disclaimer Terms"),
            smart_str(u"Disclaimer Terms Accepted"),
            smart_str(u"Over 18 Statement"),
            smart_str(u"Over 18 Confirmed")
        ]))

        for obj in OnlineDisclaimer.objects.all():
            output_text.append('@@@@@'.join([
                smart_str(obj.pk),
                smart_str(obj.user),
                smart_str(obj.date.strftime('%Y-%m-%d %H:%M:%S:%f %z')),
                smart_str(
                    obj.date_updated.strftime('%Y-%m-%d %H:%M:%S:%f %z'
                                              ) if obj.date_updated else ''),
                smart_str(obj.name),
                smart_str(obj.dob.strftime('%Y-%m-%d')),
                smart_str(obj.address),
                smart_str(obj.postcode),
                smart_str(obj.home_phone),
                smart_str(obj.mobile_phone),
                smart_str(obj.emergency_contact1_name),
                smart_str(obj.emergency_contact1_relationship),
                smart_str(obj.emergency_contact1_phone),
                smart_str(obj.emergency_contact2_name),
                smart_str(obj.emergency_contact2_relationship),
                smart_str(obj.emergency_contact2_phone),
                smart_str('Yes' if obj.medical_conditions else 'No'),
                smart_str(obj.medical_conditions_details),
                smart_str('Yes' if obj.joint_problems else 'No'),
                smart_str(obj.joint_problems_details),
                smart_str('Yes' if obj.allergies else 'No'),
                smart_str(obj.allergies_details),
                smart_str(obj.medical_treatment_terms),
                smart_str('Yes' if obj.medical_treatment_permission else 'No'),
                smart_str(obj.disclaimer_terms),
                smart_str('Yes' if obj.terms_accepted else 'No'),
                smart_str(obj.over_18_statement),
                smart_str('Yes' if obj.age_over_18_confirmed else 'No'),
            ]))

        output_str = '&&&&&'.join(output_text)

        with open(outputfile, 'wb') as out:
            out.write(encrypt(PASSWORD, output_str))

        with open(outputfile, 'rb') as file:
            filename = os.path.split(outputfile)[1]
            try:
                msg = EmailMessage(
                    '{} disclaimer backup'.format(
                        settings.ACCOUNT_EMAIL_SUBJECT_PREFIX),
                    'Encrypted disclaimer back up file attached. '
                    '{} records.'.format(OnlineDisclaimer.objects.count()),
                    settings.DEFAULT_FROM_EMAIL,
                    to=[settings.SUPPORT_EMAIL],
                    attachments=[(filename, file.read(), 'bytes/bytes')])
                msg.send(fail_silently=False)
            except:
                pass

        self.stdout.write(
            '{} disclaimer records encrypted and written to {}'.format(
                OnlineDisclaimer.objects.count(), outputfile))

        logger.info('{} disclaimer records encrypted and backed up'.format(
            OnlineDisclaimer.objects.count()))
        ActivityLog.objects.create(
            log='{} disclaimer records encrypted and backed up'.format(
                OnlineDisclaimer.objects.count()))
Пример #50
0
def upload(req):
    r = HttpResponse()
    f = req.FILES["file"]
    id_ensemble = req.GET["id_ensemble"]
    id_source = req.GET["id_source"]
    id_folder = req.GET.get("id_folder", None)
    uid = UR.getUserId(req)
    logging.info("upload uid=%s, id_source=%s, id_ensemble=%s, id_folder=%s" %
                 (uid, id_source, id_ensemble, id_folder))
    url = "http://%s:%s/%s?id_ensemble=%s" % ("localhost", "8080", f.name,
                                              id_ensemble)
    payload = {"url": url, "id_source": id_source, "id_folder": id_folder}
    if auth.canInsertFile(uid, id_ensemble, id_folder):
        #the followong data will be deleted in utils_pdf if an PDF error happens later...
        annotations.createSource(uid, payload)
        ownership = annotations.addOwnership(id_source, id_ensemble, id_folder)
        source = ownership.source
        REPOSITORY_DIR = "%s/%s" % (settings.HTTPD_MEDIA, "/pdf/repository")
        f2 = open("%s/%s" % (
            REPOSITORY_DIR,
            id_source,
        ), "wb")
        f2.write(f.read())
        f2.close()
        if insert_pdf_metadata(id_source, REPOSITORY_DIR):
            V = {
                "reply_to": settings.SMTP_REPLY_TO,
                "email": source.submittedby.email,
                "title": source.title,
                "submitted": ownership.published,
                "protocol": settings.PROTOCOL,
                "hostname": settings.HOSTNAME,
                "id_source": id_source,
                "firstname": source.submittedby.firstname
            }
            msg = render_to_string("email/msg_pdfdone", V)
            email = EmailMessage(
                "The PDF file that you've submitted is now ready on NB.", msg,
                settings.EMAIL_FROM, (V["email"], settings.SMTP_CC_USER),
                (settings.EMAIL_BCC, ))
            email.send()
        else:
            #send email that stg didn't work and remove that document.
            V = {
                "reply_to": settings.SMTP_REPLY_TO,
                "email": source.submittedby.email,
                "source_id": id_source,
                "title": source.title,
                "submitted": ownership.published,
                "support": settings.SUPPORT_LINK,
                "contact_email": settings.NBTEAM_EMAIL,
                "firstname": source.submittedby.firstname
            }
            ownership.delete()
            source.delete()
            msg = render_to_string("email/msg_pdferror", V)
            email = EmailMessage(
                "NB was unable to read a PDF file that you've submitted", msg,
                settings.EMAIL_FROM, (V["email"], settings.SMTP_CC_PDFERROR),
                (settings.EMAIL_BCC, ))
            email.send()
        r.content = UR.prepare_response({})
    else:
        r.content = UR.prepare_response(
            {}, 1, "NOT ALLOWED to insert a file to this group")
    return r
Пример #51
0
def send_mail_task(subject, message, from_email, recipient_list):
    message = EmailMessage("Discover Special Value - {0}".format(subject), message, from_email, recipient_list)
    message.send()
Пример #52
0
def playstay_request_booking_email(booked_id):
    email_path = EMAIL_TEMPLATE_PATH + "playstay_request.html"
    booked = BookedPackageTour.objects.get(pk=booked_id)
    booked_data = BookedPackageTourSerializer(booked).data
    package_tour = PackageTour.objects.filter(
        id=booked_data['package_tour']).first()
    with open(email_path, encoding="utf-8") as f:
        data = f.read()
        if CURRENT_ENV == 'prod':
            bcc_email = ['*****@*****.**']
        else:
            bcc_email = []
        total_cost = int(booked_data['total_cost'])
        data = data.replace('{customer_name}', booked_data['customer_name'])
        data = data.replace('{booked_id}', booked_data['reservation_code'])
        data = data.replace('{customer_phone}', booked_data['customer_phone'])
        data = data.replace('{customer_email}', booked_data['customer_email'])
        data = data.replace('{total_cost}', "{:,}".format(total_cost))
        data = data.replace('{checkin_date}',
                            booked_data['checkin_date'].strftime('%b %d, %Y'))
        data = data.replace('{checkout_date}',
                            booked_data['checkout_date'].strftime('%b %d, %Y'))
        data = data.replace('{note}', booked_data['note'])
        data = data.replace('{no_nights}', str(booked_data['quantity']))
        if len(booked_data['golfcourses']) > 1:
            no_rounds = len(booked_data['golfcourses'])
        else:
            no_rounds = booked_data['golfcourses'][0]['no_round']
        no_rooms = 0
        total_stay = 0

        template_hotel = """
		<tr align="center">
            <td align="left" valign="top" width="60%">
                <span style="margin: 0; font-size: 15px; line-height: 21px; font-family: 'Helvetica', Arial, sans-serif; color: #333333;">
                            <span id="ctl13_lblRoomName">{hotel_name} - {room_name}</span></span>
            </td>
            <td align="right" valign="top" width="40%">
                <span style="margin: 0; font-size: 15px; line-height: 21px; font-family: 'Helvetica', Arial, sans-serif; color: #333333;">
                            <span id="ctl13_lblRoomPrice">{hotel_no_rooms} Room{scale}</span>
                </span>
            </td>
        </tr>
		"""
        template_golfcourse = """
		<tr align="center">
            <td align="left" valign="top" width="60%">
                <span style="margin: 0; font-size: 15px; line-height: 21px; font-family: 'Helvetica', Arial, sans-serif; color: #333333;">
                            <span id="ctl13_lblRoomName">{golfcourse_name}</span></span>
            </td>
            <td align="right" valign="top" width="40%">
                <span style="margin: 0; font-size: 15px; line-height: 21px; font-family: 'Helvetica', Arial, sans-serif; color: #333333;">
                            <span id="ctl13_lblRoomPrice">{golfcourse_no_round} Round{scale}</span>
                </span>
            </td>
        </tr>

		"""
        package_hotel = ""
        for hotel in booked_data['hotels']:
            no_rooms += hotel['quantity']
            total_stay += int(hotel['price'])
            td = {
                'room_name': hotel['info']['room_info']['name'],
                'hotel_no_rooms': hotel['quantity'],
                'hotel_name': hotel['name'],
                'scale': 's' if hotel['quantity'] > 1 else ''
            }
            package_hotel += template_hotel.format(**td)

        total_play = 0
        package_golfcourse = ""
        golfcourse_no_round = 1 if len(booked_data['golfcourses']) > 1 else 0
        for golfcourse in booked_data['golfcourses']:
            total_play += int(golfcourse['price'])
            gc_round = golfcourse_no_round or golfcourse['no_round']
            td = {
                'golfcourse_name':
                golfcourse['info']['golfcourse_info']['name'],
                'golfcourse_no_round': gc_round,
                'scale': 's' if (gc_round > 1) else ''
            }
            package_golfcourse += template_golfcourse.format(**td)
        total_stay *= booked_data['quantity']
        #total_play *= 1 if len(booked_data['golfcourses']) > 1 else booked_data['quantity']
        no_golfer = booked_data['golfcourses'][0]['quantity']
        data = data.replace('{no_rooms}', str(no_rooms))
        data = data.replace('{no_golfer}', str(no_golfer))
        data = data.replace('{total_stay}', "{:,}".format(total_stay))
        data = data.replace('{total_play}', "{:,}".format(total_play))
        data = data.replace('{package_hotel}', package_hotel)
        data = data.replace('{package_golfcourse}', package_golfcourse)
        scale_nogolfer = 's' if no_golfer > 1 else ''
        data = data.replace('{scale_nogolfer}', scale_nogolfer)

        total_sum = total_play + total_stay
        data = data.replace('{total_sum}', "{:,}".format(total_sum))

        template_discount = """
		<tr align="center">
            <td align="left" style="border-top: 1px dotted #dedede;">
                <strong style="margin: 0; font-size: 15px; line-height: 21px; font-family: 'Helvetica', Arial, sans-serif; color: #333333;">
					<span id="ctl13_lblTxtTotalPrice">Discount (-{0}%)</span>
				</strong>
            </td>
            <td align="right" valign="top" width="40%" style="border-top: 1px dotted #dedede;">
                <strong style="margin: 0; font-size: 15px; line-height: 21px; font-family: 'Helvetica', Arial, sans-serif; color: #333333;">
					<span id="ctl13_lblTotalPrice">VND -{1:,}</span>
				</strong>
            </td>
        </tr>
		"""
        if booked_data['discount']:
            td = template_discount.format(package_tour.discount,
                                          total_play + total_stay - total_cost)
            data = data.replace('{discount_amount}', td)
        else:
            data = data.replace('{discount_amount}', '')
        hotel_id = int(booked_data['hotels'][0]['info']['room_info']['hotel'])
        hotel = Hotel.objects.get(pk=hotel_id)

        data = data.replace('{hotel_name}', hotel.name.upper())
        data = data.replace('{hotel_address}', (hotel.address or ''))
        data = data.replace(
            '{hotel_image}',
            hotel.hotel_images.all()[0].url
            if hotel.hotel_images.all().count() > 0 else '')

        package_tour = PackageTour.objects.get(pk=booked_data['package_tour'])
        package_name = "{0} | {1} round{2} {3} night{4}".format(
            package_tour.title, no_rounds, 's' if no_rounds > 1 else '',
            booked_data['quantity'],
            's' if booked_data['quantity'] > 1 else '')
        data = data.replace('{package_name}', package_name)

        template_currency = """
		<tr align="center">
            <td align="left" align="right" valign="top" width="40%">
                <strong style="margin: 0; font-size: 20px; line-height: 21px; font-family: 'Helvetica', Arial, sans-serif; color: #333333;">
				    <span id="ctl13_lblTxtTotalPrice"></span>
				</strong>
            </td>
            <td align="right" valign="top" width="40%">
                <strong style="margin: 0; font-size: 20px; line-height: 21px; font-family: 'Helvetica', Arial, sans-serif; color: #333333;">
					<span id="ctl13_lblTotalPrice">{currencyCode} {currencyValue}*</span>
				</strong>
            </td>
        </tr>
		"""
        #round(a,2)
        if booked_data['currencyCode'] and booked_data['currencyCode'] != 'VND':
            temp_currency = {
                'currencyCode': booked_data['currencyCode'],
                'currencyValue': round(booked_data['currencyValue'], 2)
            }
            currency = template_currency.format(**temp_currency)
            data = data.replace('{currency}', currency)
        else:
            data = data.replace('{currency}', '')
        email = [booked_data['customer_email']]
        ctx = {'email': booked_data['customer_email']}
        text = 'Thanks you for your booking with GolfConnect24'
        template_data = Template(data)
        message = template_data.render(Context(ctx))
        msg = EmailMessage(
            'GOLFCONNECT24 BOOKING REQUEST #{}'.format(
                booked_data['reservation_code']),
            message,
            from_email='GolfConnect24 <*****@*****.**>',
            to=email,
            bcc=bcc_email)
        msg.content_subtype = "html"
        msg.send()
    return
Пример #53
0
def send_test_report():
    from django.core.mail import EmailMessage
    email = EmailMessage('Subject',
                         'Body',
                         to=['*****@*****.**'])
    email.send()
Пример #54
0
def send_email(request):
    msg = EmailMessage('Request Callback',
                       'Here is the message.', to=['*****@*****.**'])
    msg.send()
    return HttpResponseRedirect('/')
Пример #55
0
def download_payment_file_post(request):
    download_file = request.POST.get('download_payment_file', None)
    send_file = request.POST.get('send_payment_file', None)
    send_sales_report = request.POST.get('send_sales_report', None)
    if download_file:
        dl_url = get_today_payments()
        if not dl_url:
            return HttpResponseBadRequest('no url found')
        return HttpResponseRedirect(redirect_to=dl_url)
    if send_file:
        dl_url = payment_summary_today()
        msg = "Email sent to " + ', '.join(
            ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**',
             '*****@*****.**', '*****@*****.**', '*****@*****.**'])
        messages.error(request, "Mail sent successfully")
        return HttpResponseRedirect(redirect_to=dl_url)
    if send_sales_report:
        mb = ManualBooking.objects.filter(
            created_on__date=datetime.now().date() - timedelta(days=1)
        ).exclude(
            booking_status='cancelled'
        ).order_by(
            '-shipment_date'
        )
        if mb:
            data = []
            for booking in mb:
                try:
                    data.append([
                        booking.booking_id,
                        '\n'.join(booking.lr_numbers.values_list('lr_number', flat=True)),
                        booking.from_city,
                        booking.to_city,
                        booking.party_rate,
                        booking.charged_weight,
                        booking.total_amount_to_company,
                        booking.supplier_rate,
                        booking.supplier_charged_weight,
                        booking.total_amount_to_owner,
                        booking.total_amount_to_company - booking.total_amount_to_owner,
                        "{0:.2f}".format(((
                                                  booking.total_amount_to_company - booking.total_amount_to_owner) / booking.total_amount_to_owner) * 100)
                    ])
                except ZeroDivisionError:
                    data.append([
                        booking.booking_id,
                        '\n'.join(booking.lr_numbers.values_list('lr_number', flat=True)),
                        booking.from_city,
                        booking.to_city,
                        booking.party_rate,
                        booking.charged_weight,
                        booking.total_amount_to_company,
                        booking.supplier_rate,
                        booking.supplier_charged_weight,
                        booking.total_amount_to_owner,
                        booking.total_amount_to_company - booking.total_amount_to_owner,
                        'Amount to owner is zero'
                    ])

            df = pd.DataFrame(data=data,
                              columns=['Booking ID', 'LR Number(s)', 'From City', 'To City', 'Party Rate',
                                       'Party Weight',
                                       'Party Amount', 'Supplier Rate', 'Supplier Weight', 'Supplier Amount', 'Profit',
                                       '% Profit'])
            bytes_io = BytesIO()
            df.to_csv(bytes_io, index=False)
            bytes_io.seek(0)
            content = bytes_io.getvalue() or '\n'
            filename = datetime.now().strftime('%d%b%Y%I%M') + '.csv'
            s3_upload = save_to_s3_daily_sales_report(filename, content)
            s3_url = s3_upload.public_url()
            subject = '[Aaho] Daily Sales Report for ' + (datetime.now().date() - timedelta(days=1)).strftime(
                '%d-%b-%Y')
            body = get_template('team/emails/last-day-bookings.html').render(context={'mb': mb, 's3_url': s3_url})
            email = EmailMessage(subject, body,
                                 to=['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'])
            email.content_subtype = 'html'
            email.send()
    return HttpResponseRedirect('/team/download-payment-file/')
Пример #56
0
    def send_confirmation_emails(self, pdf_file, site_name):
        """
        send confirmation e-mail
        """
        recipient_list = [(self.user.username, self.user.email, 'user')]  # pylint: disable=no-member

        subject = _("Order Payment Confirmation")

        dashboard_url = '{base_url}{dashboard}'.format(
            base_url=site_name, dashboard=reverse('dashboard'))
        try:
            from_address = configuration_helpers.get_value(
                'email_from_address', settings.PAYMENT_SUPPORT_EMAIL)
            # Send a unique email for each recipient. Don't put all email
            # addresses in a single email.
            for recipient in recipient_list:
                message = render_to_string(
                    'micro_masters/emails/order_confirmation_email.txt', {
                        'order':
                        self,
                        'recipient_name':
                        recipient[0],
                        'recipient_type':
                        recipient[2],
                        'site_name':
                        site_name,
                        'dashboard_url':
                        dashboard_url,
                        'currency_symbol':
                        settings.PAID_COURSE_REGISTRATION_CURRENCY[1],
                        'order_placed_by':
                        '{username} ({email})'.format(
                            username=self.user.username,
                            email=self.user.email),
                        'has_billing_info':
                        settings.FEATURES['STORE_BILLING_INFO'],
                        'platform_name':
                        configuration_helpers.get_value(
                            'platform_name', settings.PLATFORM_NAME),
                        'payment_support_email':
                        configuration_helpers.get_value(
                            'payment_support_email',
                            settings.PAYMENT_SUPPORT_EMAIL,
                        ),
                        'payment_email_signature':
                        configuration_helpers.get_value(
                            'payment_email_signature'),
                    })
                email = EmailMessage(subject=subject,
                                     body=message,
                                     from_email=from_address,
                                     to=[recipient[1]])

                if pdf_file is not None:
                    email.attach(u'Receipt.pdf', pdf_file.getvalue(),
                                 'application/pdf')
                else:
                    file_buffer = StringIO.StringIO(
                        _('pdf download unavailable right now, please contact support.'
                          ))
                    email.attach(u'pdf_not_available.txt',
                                 file_buffer.getvalue(), 'text/plain')
                email.send()
        # sadly need to handle diff. mail backends individually
        except (smtplib.SMTPException, BotoServerError):
            log.error('Failed sending confirmation e-mail for order %d',
                      self.id)
Пример #57
0
def registro_de_usuarios(request):
    captcha = generar_captchat()
    if request.POST:
        c = request.POST['captcha'].upper()
        c1 = request.POST['captcha1']
        print c, captcha
        if c1 == c and validar_cedula(request.POST['cedula']):
            try:
                user = User.objects.create_user(
                    username=request.POST['email'],
                    email=request.POST['email'],
                    password=request.POST['password'],
                    first_name=request.POST['nombres'],
                    last_name=request.POST['apellidos'])

                user.is_staff = False
                user.is_active = False
                user.save()
                try:
                    print request.POST['fecha_nacimiento']
                    Estudiantes(
                        usuario=user,
                        cedula=request.POST['cedula'],
                        fecha_nacimiento=request.POST['fecha_nacimiento'],
                        cert_votacion=request.POST['certificado_votacion'],
                        nombre_colegio=request.POST['nombre_colegio'],
                        lugar_nacimiento=request.POST['lugar_nacimiento'],
                        nacionalidad=request.POST['nacionalidad'],
                        telefono=request.POST['telefono'],
                        tipo_sangre=request.POST['tipo_sangre'],
                        anio_graduacion=request.POST['anio_graduacion'],
                        direccion=request.POST['direccion'],
                        sexo=request.POST['sexo']).save()
                    host = str(lectura_host())
                    email = EmailMessage(
                        "- SINDICATO CANTONAL DE CHOFERES PROFESIONALES DE PASAJE -",
                        "\n\n\nTe damos la Bienvenida, y te agradecemos por registrarte en nuestro sistema, aqui tienes un enlace para activar tú cuenta: http://"
                        + host + "/activar_usuario/" + str(user.id),
                        to=[request.POST['email']])
                    email.send()
                except Exception as error:
                    print error
                    pass
                return render_to_response(
                    "public/Registro.html", {
                        "mensaje":
                        "Su cuenta fué creada exitosamente, LOS DATOS DE LA ACTIVACIÓN LLEGARÁN A SU CORREO ELECTRÓNICO..!!",
                        "captcha": captcha
                    })
            except:
                return render_to_response(
                    "public/Registro.html", {
                        "mensaje":
                        "Se ha presentado un error desconocido, por favor intente más tarde..!!"
                    })
        else:
            return render_to_response(
                "public/Registro.html", {
                    "mensaje":
                    "No ha pasado la validación o su cédula no es correcta, Reintente..!!"
                })
    else:
        return render_to_response("public/Registro.html", {"captcha": captcha})
Пример #58
0
def email(name, subject, mailid, file_path):
    email = EmailMessage("Respected, {}!!".format(name), subject, to=[mailid])

    email.attach_file(file_path)
    email.send()
    print("Email Sent")
Пример #59
0
    def execute(self, context):
        """
        :param context: Script Context.
        :type context: shuup.notify.script.Context
        """
        recipient = get_email_list(self.get_value(context, "recipient"))
        if not recipient:
            context.log(logging.INFO,
                        "Info! %s: Not sending mail, no recipient.",
                        self.identifier)
            return

        send_identifier = self.get_value(context, "send_identifier")
        if send_identifier and context.log_entry_queryset.filter(
                identifier=send_identifier).exists():
            context.log(
                logging.INFO,
                "Info! %s: Not sending mail, it was already sent (%r).",
                self.identifier, send_identifier)
            return

        languages = [
            language for language in [
                self.get_value(context, "language"),
                self.get_value(context, "fallback_language"),
            ] if language and language in dict(settings.LANGUAGES).keys()
        ]

        if not languages:
            languages = [settings.PARLER_DEFAULT_LANGUAGE_CODE]

        strings = self.get_template_values(context, languages)

        subject = unescape(strings.get("subject"))
        body = unescape(strings.get("body"))
        email_template_id = strings.get("email_template")

        if email_template_id:
            email_template = EmailTemplate.objects.filter(
                pk=email_template_id).first()

            if email_template and "%html_body%" in email_template.template:
                body = email_template.template.replace("%html_body%", body)

        content_type = strings.get("content_type")
        if not (subject and body):
            context.log(
                logging.INFO,
                "Info! %s: Not sending mail to %s, either subject or body empty.",
                self.identifier,
                recipient,
            )
            return

        reply_to = get_email_list(self.get_value(context, "reply_to_address"))
        from_email = self.get_value(context, "from_email")
        bcc = get_email_list(self.get_value(context, "bcc"))
        cc = get_email_list(self.get_value(context, "cc"))

        subject = " ".join(
            subject.splitlines())  # Email headers may not contain newlines
        message = EmailMessage(subject=subject,
                               body=body,
                               to=recipient,
                               reply_to=reply_to,
                               from_email=from_email,
                               bcc=bcc,
                               cc=cc)
        message.content_subtype = content_type
        notification_email_before_send.send(sender=type(self),
                                            action=self,
                                            message=message,
                                            context=context)
        message.send()
        context.log(logging.INFO, "Info! %s: Mail sent to %s.",
                    self.identifier, recipient)

        notification_email_sent.send(sender=type(self),
                                     message=message,
                                     context=context)

        if send_identifier:
            context.add_log_entry_on_log_target(
                "Info! Email sent to %s: %s" % (recipient, subject),
                send_identifier)
Пример #60
0
def enviar_email(asunto, mensaje, mensaje_html, destinos):
    msg = EmailMessage(asunto, mensaje_html, settings.EMAIL_HOST_USER, destinos)
    msg.content_subtype = "html"
    msg.send()