示例#1
11
文件: mail.py 项目: erickgnavar/eolo
 def send_email_attach(*args, **kwargs):
     email = EmailMessage()
     email.subject = kwargs['subject']
     email.body = kwargs['body']
     email.from_email = settings.DEFAULT_FROM_EMAIL
     email.to = [kwargs['email']]
     email.attach_file(kwargs['path'])
     email.send()
示例#2
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)
示例#3
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)
示例#4
0
def custom_email(label, to, cc=None, attachments=None, context=None):
    if not isinstance(to, (list, tuple)):
        to = [to]

    if not isinstance(cc, (list, tuple)):
        cc = [cc]

    full_context = dict()
    full_context.update({} or context)
    mail_obj = EmailMessage()
    mail_obj.to = to
    mail_obj.cc = cc
    mail_obj.subject = render_to_string('email/{}/subject.txt'.format(label),
                                        context=full_context)
    mail_obj.from_email = settings.EMAIL_HOST_USER
    mail_obj.body = render_to_string('email/{}/message.html'.format(label),
                                     context=full_context)
    if attachments:
        for file_name in attachments:
            if os.path.exists(file_name):
                mail_obj.attach_file(file_name)
            else:
                logging.debug(
                    "file is not available in specified location: {}".format(
                        file_name))
    mail_obj.content_subtype = "html"

    try:
        return mail_obj.send()
    except Exception as e:
        msg = u"sending email failed\n"
        msg += unicode(e)
        print >> sys.stderr, e
def contact_email_producto(request, form, herramienta, id_producto):

    emailF = form
    emails = []

    #Informacion del usuario
    name = emailF.cleaned_data['nombre']
    telephone = emailF.cleaned_data['telefono']
    email = emailF.cleaned_data['correo']
    emails.append('*****@*****.**')

    #Mensaje a enviar
    message = 'Correo de contacto del usuario: '+ str(name.encode("utf8")) + '.<br/> Enviado mientras veia la herramienta: <a href="www.alquiherramientas.com/productos/'+str(id_producto)+' target="new">'+str(herramienta)+'"</a>'
    message += '.<br> Con correo: ' + str(emailF.cleaned_data['correo'].encode("utf8")) +'<br>'
    message += 'Mensaje: '+ str(emailF.cleaned_data['mensaje'].encode("utf8")) + '<br>'
    message += 'Telefono de contacto: '+ str(telephone.encode("utf8"))

    email = EmailMessage()
    email.subject = '[Alquiherramientas] Contacto de producto'
    email.body = message
    email.from_email = '*****@*****.**'
    email.to = emails
    email.content_subtype = "html"
    enviado=email.send()
    return True
示例#6
0
def send_email_reply(request):
    # Save this email in the database.
    emailLog = EmailLog()
    emailLog.subject = request.POST.get('reply_subject')
    emailLog.body = request.POST.get('reply_body')
    emailLog.from_email = request.POST.get('reply_from')
    emailLog.to = request.POST.get('reply_to')
    emailLog.cc = request.POST.get('reply_cc')
    reply_department_id = request.POST.get('department_id')
    reply_department = Department.objects.get(pk=reply_department_id)
    emailLog.department = reply_department     
    emailLog.timestamp = timezone.now()
    emailLog.sent_successfully = False
    emailLog.save()
    
    # Send the message.
    email_message = EmailMessage()
    email_message.subject = emailLog.subject
    email_message.body = emailLog.body
    email_message.from_email = emailLog.from_email

    if emailLog.to:
        email_message.to = emailLog.to.split(',')

    if emailLog.cc:
        email_message.cc = emailLog.cc.split(',')

    try:
        email_message.send()
        emailLog.sent_successfully = True
        emailLog.save()
        return HttpResponse()
    except:
        logger.exception("Error sending email. from_email=" + str(emailLog.from_email) + ", to_department=" + str(emailLog.department) + ", subject=" + str(emailLog.subject))
        return HttpResponseServerError()
示例#7
0
 def _send(self, email_message: EmailMessage):
     """A helper method that does the actual sending."""
     if not email_message.recipients():
         return False
     encoding = email_message.encoding or settings.DEFAULT_CHARSET
     # Specific
     email_message.extra_headers["Reply-To"] = sanitize_address(
         email_message.from_email, encoding)
     email_message.from_email = settings.EMAIL_SENDER
     for key, value in json.loads(settings.EMAIL_EXTRA_HEADERS).items():
         email_message.extra_headers[key] = value
     # /Specific
     from_email = sanitize_address(email_message.from_email, encoding)
     recipients = [
         sanitize_address(addr, encoding)
         for addr in email_message.recipients()
     ]
     message = email_message.message()
     try:
         self.connection.sendmail(from_email, recipients,
                                  message.as_bytes(linesep="\r\n"))
     except SMTPException:
         if not self.fail_silently:
             raise
         return False
     return True
示例#8
0
def send_chunked_txt_files(data):
    logger.info('Sending chunked txt file email')

    email = EmailMessage()
    email.subject = 'Multiple uploads required'
    email.body = ('Hi there 👋,\n\n'
                  'Unfortunately we can only process 450 urls per day.'
                  ' We have began processing the first 450 urls and have'
                  ' split the remaining urls into seperate txt files each'
                  ' containing 450 urls or less. Please come back in 24'
                  ' hours and upload the next file.\n\n'
                  'Best,\n'
                  'Scane')
    email.from_email = settings.DEFAULT_EMAIL_SENDER
    email.reply_to = settings.REPLY_TO_EMAIL
    email.to = [settings.DEFAULT_EMAIL_RECIEVER]

    file_names = []
    for file_name, urls in data:
        with open(file_name, 'w') as writer:
            for url in urls:
                writer.write(f'{url}\n')
            file_names.append(file_name)

    for f_n in file_names:
        filepath = os.path.join(settings.PROJECT_ROOT_DIR, f_n)
        email.attach_file(filepath)

    email.send()
示例#9
0
def verification_send_page(request):
    user = UserExt.objects.get(pk=request.user.pk)
    form_verification_send = VerificationSendForm()
    if user.userinfo.virifield == UserInfo.UNDF:
        if request.method == 'POST':
            form_verification_send = VerificationSendForm(request.POST)
            if form_verification_send.is_valid():
                # Создание, наполнение, отплавка сообщения
                email = EmailMessage()
                email.subject = "Verification request. User: " + user.username
                email.body = form_verification_send.data['message']
                email.from_email = user.email
                email.to = ['*****@*****.**']
                image1 = request.FILES['image1']
                image2 = request.FILES['image2']
                email.attach(image1.name, image1.read(), image1.content_type)
                email.attach(image2.name, image2.read(), image2.content_type)
                email.send()
                user.userinfo.virifield = UserInfo.WAIT
                user.userinfo.save()
                return HttpResponseRedirect('/user/verification/send')

    return render(request,
                  'UserProfile/verification/verification_send_page.html',
                  {'form_verification_send': form_verification_send}) \
        if user.userinfo.virifield == UserInfo.UNDF \
        else render(request,
                    'UserProfile/verification/verification_status_page.html',
                    {'UserStatus': UserInfo})
示例#10
0
def mail_ics_file(file_name, to):

    message = EmailMessage()
    message.from_email = settings.EMAIL_HOST_USER
    message.to = [to]
    message.subject = 'Add this event to you Calendar'
    message.attach_file(file_name)
    message.send()
示例#11
0
def send_an_email(subject, body, from_email, to_emails, attachment=None):
    email = EmailMessage()
    email.subject = subject
    email.body = body
    email.from_email = from_email
    email.to = to_emails
    if attachment:
        # email.attach_file(attachment)
        email.attach('payslip.pdf', attachment, 'application/pdf')
    email.send()
示例#12
0
def send_an_email(subject, body, from_email, to_emails, attachment=None):
    email = EmailMessage()
    email.subject = subject
    email.body = body
    email.from_email = from_email
    email.to = to_emails
    if attachment:
        # email.attach_file(attachment)
        email.attach('payslip.pdf', attachment, 'application/pdf')
    email.send()
示例#13
0
def send_e_mail(to_email, Subject, message, attachment):

    email = EmailMessage()
    email.subject = Subject
    email.body = message
    email.from_email = 'PaymentRequests'
    email.to = to_email
    if attachment:
        email.attach_file(attachment)

    email.send()
示例#14
0
 def send_file(self):
     mail = EmailMessage()
     mail.body = "Hallo " + self.mailer.first_name + " " + self.mailer.last_name + \
                 " Anbei die Liste zum Dienstplan der Freiwilligen. Dies ist ein Service von volunteer-planner.org"
     mail.subject = "Dienstplan fuer den " + self.needs[0].time_period_from.date_time.strftime("%d.%m.%Y") + \
                    " der Freiwilligen in der Unterkunft " + self.needs[0].location.name
     mail.from_email = "Volunteer-Planner.org <*****@*****.**>"
     mail.to = [str(self.mailer.email)]
     attachment = self.generate_excel()
     mail.attach_file(path=attachment, mimetype='application/octet-stream')
     mail.send()
示例#15
0
 def send_file(self):
     mail = EmailMessage()
     mail.body = "Hallo " + self.mailer.first_name + " " + self.mailer.last_name + \
                 " Anbei die Liste zum Dienstplan der Freiwilligen. Dies ist ein Service von volunteer-planner.org"
     mail.subject = "Dienstplan fuer den " + self.needs[0].time_period_from.date_time.strftime("%d.%m.%Y") + \
                    " der Freiwilligen in der Unterkunft " + self.needs[0].location.name
     mail.from_email = "Volunteer-Planner.org <*****@*****.**>"
     mail.to = [str(self.mailer.email)]
     attachment = self.generate_excel()
     mail.attach_file(path=attachment, mimetype='application/octet-stream')
     # import ipdb
     # ipdb.set_trace()
     mail.send()
def send_form_single_attachment():
    try:
        os.remove('forms_single.zip')
    except:
        pass
    survey = Survey.objects.filter(active=2)
    with zipfile.ZipFile('forms_single.zip','w') as forms_zip:
        for i in survey:
            forms_zip.write("forms_and_choices/"+str(i)+"_"+str(i.id)+".csv")
    email = EmailMessage()
    email.subject = "Forms and choices zip file"
    email.body = "PFA for forms and choices in single file inside zip file"
    email.from_email = "*****@*****.**"
    email.to = [ "*****@*****.**", ]
    email.attach_file('forms_single.zip')
    email.send()
示例#17
0
    def handle(self, *args, **options):
        from tendenci.core.site_settings.utils import get_setting

        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("pip install tendenci --upgrade", stderr=subprocess.STDOUT, shell=True)

            print "Updating tendenci site"
            subprocess.check_output("python deploy.py", stderr=subprocess.STDOUT, shell=True)

            print "Restarting Server"
            subprocess.check_output("sudo reload %s" % os.path.basename(settings.PROJECT_ROOT),
                                    stderr=subprocess.STDOUT, shell=True)

            print "Clearing cache"
            call_command('clear_cache')
        except subprocess.CalledProcessError as e:
            email_context['error_message'] = e.output
        except CommandError as e:
            email_context['error_message'] = e

        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()
示例#18
0
文件: __init__.py 项目: licorna/giviu
def event_sent_giftcards_for_today(content):
    '''This event will trigger when giftcards for today are sent'''
    today = datetime.now().strftime('%Y-%m-%d')
    if settings.DEBUG:
        email = [settings.DEBUG_EMAIL_RECEIVER]
    else:
        email = [x[1] for x in settings.GIVIU_FOUNDERS]
    print 'sending to ' + str(email)
    msg = EmailMessage()
    msg.subject = 'Giftcards Sent ' + today
    msg.body = 'Please find attached Giftcards Sent Today'
    msg.from_email = settings.EMAIL_DEFAULT_FROM
    msg.to = email
    msg.attach(filename='data.json',
               mimetype='application/json',
               content=dumps(content))
    msg.send()
示例#19
0
    def to_native(self, value):
        obj = super(ConnectUserSerializer, self).to_native(value)
        value.connection = Professional.objects.get(pk=obj.get('professional_id'))
        value.connected_on = now()
        obj['user_connected'] = True
        value.save()
        notify.send(value, recipient=value.connection, verb=u'has connected to you!', target=value)
        notify.send(value.connection, recipient=value, verb=u'connected!', target=value.connection)

        email = EmailMessage()
        email.subject = "Connected To New Trainer"
        email.body = 'Complete attached document and send back to your Trainer'
        email.from_email = value.connection.email
        email.to = [ value.email, ]
        email.attach_file("email/Client Questionarre-ReleaseEverFIT.docx")
        email.send()

        return obj
示例#20
0
def send_export_email():
    logger.info('Sending exports email')

    email = EmailMessage()
    email.subject = 'Here is your export!'
    email.body = (
        'Hi there 👋,\n\n'
        'We have attached your backlink export results to this email.\n\n'
        'Best,\n'
        'Scane')
    email.from_email = settings.DEFAULT_EMAIL_SENDER
    email.reply_to = settings.REPLY_TO_EMAIL
    email.to = [settings.DEFAULT_EMAIL_RECIEVER]

    exports = shutil.make_archive('exports', 'zip', settings.EXPORTS_DIR)
    email.attach_file(exports)
    email.send()
    shutil.rmtree(settings.EXPORTS_DIR)
    def send_file(self):
        attachment = self.generate_excel()

        if not self.mailer:
            log.error(u'Cannot create and send email without mailer information')
            return

        mail = EmailMessage()
        mail.body = "Hallo " + self.mailer.first_name + " " + self.mailer.last_name + "\n\n"\
                    "Anbei die Liste zum Dienstplan der Freiwilligen.\nDies ist ein Service von volunteer-planner.org"
        mail.subject = "Dienstplan fuer den " + self.shifts[0].starting_time.strftime("%d.%m.%Y") + \
                       " der Freiwilligen in der Unterkunft " + self.shifts[0].facility.name
        mail.from_email = settings.DEFAULT_FROM_EMAIL
        mail.to = [str(self.mailer.email)]
        if attachment is not None:
            mail.attach_file(path=attachment, mimetype='application/vnd.ms-excel')
            mail.send()
        else:
            log.warn(u'No attachment, not mail.')
示例#22
0
def send_email(request):
    RECIPIENTS = ['*****@*****.**', '*****@*****.**']
    response = {'success': False}

    email_form = EmailForm(request.POST)
    if email_form.is_valid():
        user_email = email_form.cleaned_data['email']

        for to in RECIPIENTS:
            email = EmailMessage()
            email.subject = u'Nowe zgłoszenie w rekrutacji IT'
            email.body = u'Nowe zgłoszenie w rekrutacji IT: ' + user_email
            email.content_subtype = 'html'
            email.from_email = u'isivi.pl <*****@*****.**>'
            email.to = [ to ]
            email.send()

        response['success'] = True

    return JsonResponse(response)
def email_agotado(request, producto):
    emails = []
    emails.append("*****@*****.**")
    emails.append("*****@*****.**")

    producto = producto.titulo
    encoded_str = producto.encode("utf8")

    #Mensaje a enviar
    message = 'El producto: '+ str(encoded_str) + ' se ha agotado.'
    message += 'Visitar en el admin, <a href="www.alquiherramientas.com/administrador/">Producto</a>'

    email = EmailMessage()
    email.subject = '[Alquiherramientas] Producto Agotado'
    email.body = message
    email.from_email = '*****@*****.**'
    email.to = emails
    email.content_subtype = "html"
    enviado=email.send()
    return True
示例#24
0
    def send_file(self):
        attachment = self.generate_excel()

        if not self.mailer:
            log.error(
                u'Cannot create and send email without mailer information')
            return

        mail = EmailMessage()
        mail.body = "Hallo " + self.mailer.first_name + " " + self.mailer.last_name + "\n\n"\
                    "Anbei die Liste zum Dienstplan der Freiwilligen.\nDies ist ein Service von volunteer-planner.org"
        mail.subject = "Dienstplan fuer den " + self.shifts[0].starting_time.strftime("%d.%m.%Y") + \
                       " der Freiwilligen in der Unterkunft " + self.shifts[0].facility.name
        mail.from_email = "Volunteer-Planner.org <*****@*****.**>"
        mail.to = [str(self.mailer.email)]
        if attachment is not None:
            mail.attach_file(path=attachment,
                             mimetype='application/vnd.ms-excel')
            mail.send()
        else:
            log.warn(u'No attachment, not mail.')
def email_venta(request, nombre, apellido, telefono, email, herramienta, cantidad):
    emails = []
    #Informacion del usuario
    emails.append('*****@*****.**')

    #Mensaje a enviar
    message = 'El usuario: '+ str(nombre) +' '+ str(apellido) +'.<br>'
    message += 'Ha realizado el tramite para la compra de: ' + str(herramienta.encode("utf8")) +'<br>'
    message += 'Cantidad: '+ str(cantidad) + '<br/>'
    message += 'Correo de contacto: '+ str(email) + '<br/>'
    message += 'Numero de contacto: '+ str(telefono) + '<br/>'
    message += 'El usuario acepto las clausulas.'

    email = EmailMessage()
    email.subject = '[Alquiherramientas] Nueva Venta'
    email.body = message
    email.from_email = '*****@*****.**'
    email.to = emails
    email.content_subtype = "html"
    enviado=email.send()
    return True
示例#26
0
def _send_email_with_results(recepients, results_csv):
    """
    Triggers email with csv attachment.
    """

    email_subject = _('Progress migration result')
    email_text = _('Migration is finished. Please review this email attachment.')

    from_address = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)
    recepients = recepients or [settings.SERVER_EMAIL]
    attachment_name = 'MigrationResults.csv'

    email = EmailMessage()
    email.subject = email_subject
    email.body = email_text
    email.from_email = from_address
    email.to = recepients
    email.attach(attachment_name, results_csv, 'text/csv')

    email.send()

    log.info('Email with users progress migration results sent to %s', recepients)
示例#27
0
def send_email_reply(request):
    # Save this email in the database.
    emailLog = EmailLog()
    emailLog.subject = request.POST.get('reply_subject')
    emailLog.body = request.POST.get('reply_body')
    emailLog.from_email = request.POST.get('reply_from')
    emailLog.to = request.POST.get('reply_to')
    emailLog.cc = request.POST.get('reply_cc')
    reply_department_id = request.POST.get('department_id')
    reply_department = Department.objects.get(pk=reply_department_id)
    emailLog.department = reply_department
    emailLog.timestamp = timezone.now()
    emailLog.sent_successfully = False
    emailLog.save()

    # Send the message.
    email_message = EmailMessage()
    email_message.subject = emailLog.subject
    email_message.body = emailLog.body
    email_message.from_email = emailLog.from_email

    if emailLog.to:
        email_message.to = emailLog.to.split(',')

    if emailLog.cc:
        email_message.cc = emailLog.cc.split(',')

    try:
        email_message.send()
        emailLog.sent_successfully = True
        emailLog.save()
        return HttpResponse()
    except:
        logger.exception("Error sending email. from_email=" +
                         str(emailLog.from_email) + ", to_department=" +
                         str(emailLog.department) + ", subject=" +
                         str(emailLog.subject))
        return HttpResponseServerError()
示例#28
0
def emailFeed(send_to,message=None,attachment=None,extension=None):
    if send_to == "" or send_to == None:
        print "No email address on record for this user, so I can't send them their feed"
        return

    if (message=="" or message==None) and attachment==None:
        print "nothing to send"
        return 

    email = EmailMessage()
    email.subject = "InfoCatch Feed"

    email.from_email = "*****@*****.**"
    email.to = [ send_to, ] 

    if extension == None:
        mType = "text/plain"
        email.body = message
    elif extension=="pdf":
        email.body = "Please find your feed attatched."
        mType = "application/pdf"
        email.attach(filename = "newspaper", mimetype = mType, content = attachment)
    email.send()
示例#29
0
def record_email_send(request):

    email_invalid = False
    email_sent = False

    if request.method == 'POST':
        pk = int(request.POST['recid'])
        record = DailyRecord.objects.get(pk=pk)
        to_email = request.POST['email']

        # check validity of email
        if validateEmail(to_email):
            email_invalid = False

            # genarate email
            email = EmailMessage()

            email.subject = "Parking Lot Record: " + str(record.date)
            email.body = "PDF Attachment for Customer Record on " + \
                str(record.date) + "."
            email.from_email = "Parking Lot Records <*****@*****.**>"
            email.to = [
                to_email,
            ]

            # generate and attach pdf
            email.attach_file(record_pdf_file(record.pk))
            clear_media()

            # send email
            email.send()
            email_sent = True
        else:
            email_invalid = True

    data = {'email_invalid': email_invalid, 'email_sent': email_sent}
    return JsonResponse(data)
def contact_email(request, form):

    emailF = form
    emails = []

    #Informacion del usuario
    name = emailF.cleaned_data['nombre']
    telephone = emailF.cleaned_data['telefono']
    email = emailF.cleaned_data['correo']
    emails.append('*****@*****.**')

    #Mensaje a enviar
    message = 'Correo de contacto del usuario: '+ str(name) +'.<br> Con correo: ' + str(email) +'<br>'
    message += 'Mensaje: '+ str(emailF.cleaned_data['mensaje'].encode("utf8")) + '<br>'
    message += 'Telefono de contacto: '+ str(telephone)

    email = EmailMessage()
    email.subject = '[Alquiherramientas] Correo contacto'
    email.body = message
    email.from_email = '*****@*****.**'
    email.to = emails
    email.content_subtype = "html"
    enviado=email.send()
    return True
示例#31
0
    def handle(self, *args, **options):
        from tendenci.apps.site_settings.utils import get_setting

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

        pypi = xmlrpc_client.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_id and 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")
            output = subprocess.check_output(
                "%s -m pip install -r requirements/tendenci.txt --upgrade" %
                python_executable(),
                stderr=subprocess.STDOUT,
                shell=True)
            print(output.decode())
            pass_update_tendenci = True

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

        # run deploy iff update_tendenci is successful
        if pass_update_tendenci:
            try:
                print("Updating tendenci site")
                call_command('migrate')
                call_command('deploy')
                pass_update_tendenci_site = True
            except CommandError 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 systemctl restart %s" %
                    os.path.basename(settings.PROJECT_ROOT),
                    stderr=subprocess.STDOUT,
                    shell=True)

            except subprocess.CalledProcessError as e:
                gunicorn_error_msg = e.output.decode()
                if "reload: Unknown job:" in e.output.decode():
                    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.decode()

        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(
                template_name='notification/update_tendenci_notice/short.txt',
                context=email_context)
            subject = subject.strip('\n').strip('\r')
            body = render_to_string(
                template_name='notification/update_tendenci_notice/full.html',
                context=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()
        else:
            for err in errors_list:
                print(err)
示例#32
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
    new_project_description = req.POST.get('project_description')
    if (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

    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()
示例#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
        is_uwsgi = False
        gunicorn_error_msg = None
        uwsgi_error_msg = None
        errors_list = []

        pypi = xmlrpc_client.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 deploy iff update_tendenci is successful
        if pass_update_tendenci:
            try:
                print("Updating tendenci site")
                call_command('deploy')
                pass_update_tendenci_site = True
            except CommandError 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(template_name='notification/update_tendenci_notice/short.txt', context=email_context)
            subject = subject.strip('\n').strip('\r')
            body = render_to_string(template_name='notification/update_tendenci_notice/full.html', context=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 handle(self, *args, **options):
        from tendenci.core.site_settings.utils import get_setting

        pass_update_tendenci = False
        pass_update_tendenci_site = False
        pass_restart_server = False
        is_uwsgi = False
        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("pip install tendenci --upgrade",
                                    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("python deploy.py",
                                        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:
                errors_list.append(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:
                errors_list.append(e.output)

        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()
示例#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 bug_report(req):
    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.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=toggles.toggles_dict(username=report['username'],
                                                   domain=domain).keys(),
                feature_previews=feature_previews.previews_dict(domain).keys(),
                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 = 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

    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'])
        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()
示例#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
    new_project_description = req.POST.get('project_description')
    if (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

    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 post(self, request, *args, **kwargs):
        p = request.POST

        user_data = {}
        try:
            user_data['name'] = p['name']
            user_data['surname'] = p['surname']
            user_data['phone'] = p['phone']
            user_data['email'] = p['email']
#            user_data['attachment'] = p['attachment']
            user_data['attachment_link'] = p['attachment-link']
        except KeyError:
            return HttpResponse('Data was broken.')

        try:
            user_data['test_link'] = p['test']
            user_data['extra'] = p['extra']
        except KeyError:
            user_data['extra'] = ''
            user_data['test_link'] = ''

        try:
            p['job_id']
        except KeyError:
            return HttpResponse('Data was broken.')

        if not self.validate_request(request):
            return HttpResponse('Data was broken.')

        job = Job.objects.get(pk=p['job_id'])

        msg, created = Mail.objects.get_or_create(
            type=MAIL_TYPE_CLIENT,
            defaults={
                'title': u"Allods team",
                'template': self.get_fixture_data('mail_user.txt'),
            }
        )
        if created:
            msg.save()

        # https://docs.djangoproject.com/en/dev/topics/email/#django.core.mail.EmailMessage
        message = EmailMessage(
            msg.title.format(job=job),
            msg.template.format(job=job),
            MAILER_EMAIL_FROM,
            [user_data['email'],]
        )
        message.send()

        staff_msg, created = Mail.objects.get_or_create(
            type=MAIL_TYPE_STAFF,
            defaults={
                'title': u'Заявка на вакансию {job.name} - {job.project} - {job.city}',
                'template': self.get_fixture_data('mail_staff.txt'),
            }
        )
        if created:
            staff_msg.save()

        staff_message = EmailMessage()
        staff_message.subject = staff_msg.title.format(job=job)

        staff_message.body = staff_msg.template.format(
            job = job,

            name = user_data['name'],
            surname = user_data['surname'],
            phone = user_data['phone'],
            email = user_data['email'],
            attachment_link = user_data['attachment_link'],

            test_link = user_data['test_link'],
            extra = user_data['extra'],
        )
        staff_message.from_email = MAILER_EMAIL_FROM

        tmp_file = None
        try:
            data = request.FILES['attachment']

            path = default_storage.save(
                'mail/%s' % request.FILES['attachment'],
                ContentFile(data.read())
            )
            tmp_file = os.path.join(settings.MEDIA_ROOT, path)
        except Exception:
            pass

        if tmp_file:
            staff_message.attach_file(
                os.path.join(settings.MEDIA_ROOT, 'mail', unicode(tmp_file))
            )

        to_list = []
        if job.user:
            to_list.append(job.user.email)
        if job.mailer:
            to_list += job.mailer.split(', ')

        for to in to_list:
            try:
                validate_email(to)
                staff_message.to = [to, ]
                staff_message.send()
            except ValidationError:
                logging.warning('wrong mail - %s' % to)

        return HttpResponse('Data was transferred.')
示例#39
0
def invoice_report(request):
    forecast = Forecast.objects.all()
    if request.method == 'POST':
        post = request.POST
        ay = post.get("fatura_ayi")
        yil = post.get("fatura_yili")
        eposta = post.get("eposta")

        if ay != None and ay != "":
            forecast = forecast.filter(fatura_ayi=int(ay))

        if yil != None and yil != "":
            forecast = forecast.filter(fatura_yili=int(yil))

        if eposta != None and eposta != "":
            book = xlwt.Workbook(encoding='utf8')
            sheet = book.add_sheet('IT Forecast Report_' + str(ay) + '_Ay')

            # Adding style for cell
            # Create Alignment
            alignment = xlwt.Alignment()
            # horz May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT,
            # HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL,
            # HORZ_DISTRIBUTED
            alignment.horz = xlwt.Alignment.HORZ_LEFT
            # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED,
            # VERT_DISTRIBUTED
            alignment.vert = xlwt.Alignment.VERT_TOP
            style = xlwt.XFStyle() # Create Style
            style.alignment = alignment # Add Alignment to Style

            default_style = xlwt.Style.default_style
            datetime_style = xlwt.easyxf(num_format_str='dd/mm/yyyy hh:mm')
            date_style = xlwt.easyxf(num_format_str='dd/mm/yyyy')
            values_list = forecast.filter(fatura_ayi=int(ay)).values_list()

            header = ['ID', 'Fatura Ayı', 'Fatura Yılı', 'Tutar', 'Para Cinsi', 'Tipi', 'Gider Tipi', 'Ödeme Şekli' 'Açıklama', 'Firma', 'Kayıt Tarihi']
            for hcol, hcol_data in enumerate(header):
                sheet.write(0, hcol, hcol_data, style=xlwt.Style.default_style)

            for row, rowdata in enumerate(values_list, start=1):
                for col, val in enumerate(rowdata):
                    if isinstance(val, datetime):
                        style = datetime_style
                    elif isinstance(val, date):
                        style = date_style
                    else:
                        style = default_style

                    sheet.write(row, col, val, style=style)

            response = HttpResponse(mimetype='application/vnd.ms-excel')
            book.save('/downloads/IT_Forecast' + '_' + str(yil) + '_' + str(ay) + '_Ay Raporu' + '.xls')
            filename = ('/downloads/IT_Forecast' + '_' + str(yil) + '_' + str(ay) + '_Ay Raporu' + '.xls')

            smtpserver = 'localhost'
            html_message = "Bu mesaj sistem tarafından otomatik olarak gönderilmiştir."
            email = EmailMessage()
            email.subject = "Aylık IT Forecast Tablosu"
            email.body = html_message
            email.from_email = "IT Forecast <*****@*****.**>"
            email.to = [ eposta, ]
            email.attach_file(filename)
            email.send()

    return render(request, 'welcome/verigoruntuleme.html', {"forecast":forecast})
示例#40
0
def bug_report(req):
    report = dict([(key, req.POST.get(key, '')) for key in (
        'subject',
        'username',
        'domain',
        'url',
        'message',
        'app_id',
    )])

    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
    except Exception:
        full_name = None
    report['full_name'] = full_name

    subject = u'{subject} ({domain})'.format(**report)
    message = (
        u"username: {username}\n"
        u"full name: {full_name}\n"
        u"domain: {domain}\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)

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

    # 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}
    )

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

    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 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()
示例#42
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()
示例#43
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()
示例#44
0
        last_modified_date__contains=day_diff,
        state=lgc_models.INVOICE_STATE_DONE,
        type=lgc_models.INVOICE)
    for i in invoices.all():
        response = http.HttpResponse(content_type='application/pdf')
        filename = 'FA' + str(i.number).zfill(5) + '.pdf'
        pdf = subprocess.Popen(
            os.path.join(settings.BASE_DIR, 'php_pdf/print.php') + ' ' +
            str(i.id),
            shell=True,
            stdout=subprocess.PIPE).stdout.read()
        email = EmailMessage()
        if i.language == 'FR':
            email.subject = r.subject_fr
            body = r.template_fr
        else:
            email.subject = r.subject_en
            body = r.template_en

        email.body = string_template(body).substitute(
            INVOICE_DATE=i.invoice_date,
            FIRST_NAME=i.po_first_name,
            LAST_NAME=i.po_last_name)
        email.from_email = settings.INVOICE_REMINDER_EMAIL
        email.to = [i.po_email]
        email.bcc = [settings.INVOICE_REMINDER_EMAIL]
        email.attach(filename=filename,
                     mimetype='application/pdf',
                     content=pdf)
        email.send()
示例#45
0
def bug_report(req):
    report = dict([(key, req.POST.get(key, '')) for key in (
        'subject',
        'username',
        'domain',
        'url',
        'message',
        'app_id',
    )])

    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
    except Exception:
        full_name = None
    report['full_name'] = full_name

    subject = u'{subject} ({domain})'.format(**report)
    message = (u"username: {username}\n"
               u"full name: {full_name}\n"
               u"domain: {domain}\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)

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

    # 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})

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

    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()