コード例 #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
ファイル: views.py プロジェクト: lynchnf/maneki-neko-web
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()
コード例 #3
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
コード例 #4
0
ファイル: mails.py プロジェクト: jamieconnelly/scane
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()
コード例 #5
0
ファイル: functions.py プロジェクト: FrancoNoriUSB/equity
def contact_email(request, form, correo, inmueble):

    emailF = form
    emails = []

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

    # Verificacion de si posee telefono
    if telephone == '':
        telephone = 'No posee telefono de contacto.'

    # Mensaje a enviar
    message = 'Correo de contacto del usuario: ' + str(name) + '. Con correo: ' + str(emailF.cleaned_data['correo']) + '<br>'
    message += 'Inmueble: ' + inmueble.titulo + '<br>'
    message += 'Mensaje: ' + str(emailF.cleaned_data['comentario']) + '<br>'
    message += 'Telefono de contacto: ' + str(telephone)

    email = EmailMessage()
    email.subject = '[Equity International] Correo contacto'
    email.body = message
    email.to = emails
    email.content_subtype = "html"
    enviado = email.send()
    return enviado
コード例 #6
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})
コード例 #7
0
def enviar_correo(destinatario, asunto, cuerpo):
    email = EmailMessage()
    email.subject = asunto
    email.body = cuerpo
    email.to = destinatario
    email.connection = connection
    email.send()
コード例 #8
0
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
コード例 #9
0
def sanitize_mailjet_recipients(email_message):
    """
    Mailjet API has a **50** number limit for anytype of email recipient:
    * TO
    * CC
    * BCC

    This function:
    * partitions email recipients with more than 50 elements
    * creates new emails with a number of recipients in the Mailjet limit
    * **only** checks for `TO` recipients owerflows

    `email_message` is an EmailMessage object (not serialized)

    Returns a **list** of "sanitized" emails.
    """

    if len(email_message.to) <= _MAILJET_MAX_RECIPIENTS:
        # We're ok, return a list containing the original message
        return [email_message]

    sanitized_emails = []
    to_chunks = chunks(email_message.to, _MAILJET_MAX_RECIPIENTS)
    # We could also combine to, cc and bcc, but it's useless for now

    for to_chunk in to_chunks:
        copy_kvs = {k: email_message.__dict__[k] for k in _EMAIL_KEYS}
        copy_email = EmailMessage(**copy_kvs)
        copy_email.to = to_chunk
        sanitized_emails.append(copy_email)

    return sanitized_emails
コード例 #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_mail_ticket(request, subject, body, to):
    email = EmailMessage()
    email.subject = subject
    email.body = body
    email.to = [to]
    #email.attach_file("/home/romain/Downloads/clement.davin.jpeg")
    email.connection = get_connection()
    return email.send()
コード例 #12
0
def contact_us(request):
    # Save this email in the database.
    emailLog = EmailLog()
    emailLog.subject = request.POST.get('subject')
    emailLog.body = request.POST.get('message')
    emailLog.from_email = request.POST.get('from_email')
    to_department_id = request.POST.get('to_department')
    to_department = Department.objects.get(pk=to_department_id)
    emailLog.to = to_department.email

    cc = []
    emailLog.cc = None
    cc_departments = Department.objects.filter(chair=True).exclude(
        id=to_department_id)
    for cc_department in cc_departments:
        cc.append(cc_department.email)
        if emailLog.cc == None:
            emailLog.cc = cc_department.email
        else:
            emailLog.cc += "," + cc_department.email

    emailLog.department = to_department
    emailLog.timestamp = timezone.now()
    emailLog.sent_successfully = False
    emailLog.save()

    # Send the message.
    email_message = EmailMessage()
    subject = settings.CONTACT_US_SUBJECT_PREFIX + emailLog.subject
    body = "-------------------------------------------------------------------------------\n"
    body += "    Message sent from %s on %s.\n" % (
        emailLog.from_email, emailLog.timestamp.strftime("%Y-%m-%d %I:%M %p"))
    body += "    Go to %s?emailId=%s to reply.\n" % (
        request.build_absolute_uri("/staff-only/email-log/"), emailLog.id)
    body += "-------------------------------------------------------------------------------\n"
    if emailLog.body == None or emailLog.body == "":
        subject = subject + "<eom>"
    else:
        body += emailLog.body

    email_message.subject = subject
    email_message.body = body
    email_message.to = [emailLog.to]
    if cc:
        email_message.cc = cc

    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()
コード例 #13
0
ファイル: mail.py プロジェクト: joseamaya/tambox
def enviar_correo(destinatario,asunto,cuerpo):
    email = EmailMessage()
    email.subject = asunto
    email.body = cuerpo
    email.to = destinatario
    email.connection = connection
    try:
        email.send()
    except:
        pass
コード例 #14
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()
コード例 #15
0
ファイル: utils.py プロジェクト: agiliq/leave-tracker-app
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()
コード例 #16
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()
コード例 #17
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()
コード例 #18
0
def send_email_to_register(destination_email):
    email = EmailMessage()
    email.subject = "Join our network!"
    email.body = """
    Hi, bro!

    Join us and participate our events !!!

    Hugs,
    """
    email.to = [destination_email]
    email.send()
コード例 #19
0
def send_email(recipient_list, subject, body):
    """
    Send email according to given parameters.
    """
    message = EmailMessage()
    message.to = recipient_list
    message.subject = subject
    message.body = body
    try:
        message.send(fail_silently=False)
    except Exception:
        raise
コード例 #20
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()
コード例 #21
0
ファイル: views.py プロジェクト: lynchnf/maneki-neko-web
def contact_us(request):
    # Save this email in the database.
    emailLog = EmailLog()
    emailLog.subject = request.POST.get('subject')
    emailLog.body = request.POST.get('message')
    emailLog.from_email = request.POST.get('from_email')
    to_department_id = request.POST.get('to_department')
    to_department = Department.objects.get(pk=to_department_id)
    emailLog.to = to_department.email
    
    cc = []
    emailLog.cc = None
    cc_departments = Department.objects.filter(chair=True).exclude(id=to_department_id)
    for cc_department in cc_departments:
        cc.append(cc_department.email)
        if emailLog.cc == None:
            emailLog.cc = cc_department.email
        else:
            emailLog.cc += "," + cc_department.email
            
    emailLog.department = to_department     
    emailLog.timestamp = timezone.now()
    emailLog.sent_successfully = False
    emailLog.save()
    
    # Send the message.
    email_message = EmailMessage()
    subject = settings.CONTACT_US_SUBJECT_PREFIX + emailLog.subject
    body = "-------------------------------------------------------------------------------\n"
    body += "    Message sent from %s on %s.\n" % (emailLog.from_email, emailLog.timestamp.strftime("%Y-%m-%d %I:%M %p"))
    body += "    Go to %s?emailId=%s to reply.\n" % (request.build_absolute_uri("/staff-only/email-log/"), emailLog.id)
    body += "-------------------------------------------------------------------------------\n"
    if emailLog.body == None or emailLog.body == "":
        subject = subject + "<eom>"
    else:
        body += emailLog.body
        
    email_message.subject = subject
    email_message.body = body
    email_message.to = [emailLog.to]
    if cc:
        email_message.cc = cc

    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()
コード例 #22
0
def __send_invitation_update_notification_by_email(sender, instance):
    choices = dict(sender.status.field.choices)
    choice_label = choices.get(instance.status.upper())

    email = EmailMessage()
    email.subject = "Invitation status updated"
    email.body = f"""
    Hi {instance.invitation_from.username},

    The invitation sent to {instance.invitation_to.username} was {choice_label}.

    Hugs,
    """
    email.to = [instance.invitation_from.email]
    email.send()
コード例 #23
0
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()
コード例 #24
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()
コード例 #25
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()
コード例 #26
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
コード例 #27
0
ファイル: views.py プロジェクト: nworks16/gacerh
def cerrargasto(request):
	idview = request.POST.get('id').replace(',', '')
	print idview
	print "Cerrando gasto"
	gasto = Gasto.objects.get(id=idview);
	gasto.estatus = "CERRADO"
	gasto.save()
	
	correo = EmailMessage()
	correo.subject = " Reporte de Gastos ACERH"
	correo.body = """Hola Administrador,
	El usuario """+ gasto.comprador.username +','+ gasto.comprador.first_name + ' ' + gasto.comprador.last_name +""", acaba de finalizar el reporte """+ gasto.referencia + """ de un monto total de """+ str(gasto.total_final) + """
	Notificaciones de Gastos ACERH """
	correo.to = ['*****@*****.**']
	correo.send()


	return render(request, 'adming.html',{'gasto':gasto})
コード例 #28
0
ファイル: mails.py プロジェクト: jamieconnelly/scane
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)
コード例 #29
0
ファイル: functions.py プロジェクト: FrancoNoriUSB/equity
def reporte_email(request, user, pais, inmueble):

    emails = []
    emails.append('*****@*****.**')
    emails.append('*****@*****.**')
    emails.append('*****@*****.**')

    message = '<p>Email de reporte de mercado de usuario' + user.email + '</p>'

    if inmueble:
        message += '<a href="http://www.equity-international.com/' + pais + '/inmuebles/' + inmueble.codigo + '/" >' + inmueble.titulo + '</a>'

    email = EmailMessage()
    email.subject = '[Equity International] Reporte de Mercado'
    email.body = message
    email.to = emails
    email.content_subtype = "html"
    enviado = email.send()
    return enviado
コード例 #30
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 = 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.')
コード例 #31
0
ファイル: views.py プロジェクト: isivi/awesome-score
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)
コード例 #32
0
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
コード例 #33
0
ファイル: functions.py プロジェクト: FrancoNoriUSB/equity
def favoritos_email(request, user, favoritos, pais):

    emails = []
    emails.append(user.email)

    message = '<h3>Resumen de inmuebles favoritos Equity International</h3><br><br>'
    message += '<table><thead><tr><th>País</th><th>Ciudad</th><th>Inmueble</th><th>M2</th><th>Hab</th></tr></thead>'

    for favorito in favoritos:
        message += '<tr><td>' + str(pais.encode('UTF-8', 'strict')) + '</td><td>' + str(favorito.modulo.inmueble.ciudad.nombre.encode('UTF-8', 'strict')) + '</td><td>' + str(favorito.modulo.inmueble.titulo.encode('UTF-8', 'strict')) + '</td><td>' + str(favorito.modulo.metros).encode('UTF-8', 'strict') + '</td><td>' + str(favorito.modulo.dormitorios.encode('UTF-8', 'strict')) + '</td></tr>'

    message += '</table>'

    email = EmailMessage()
    email.subject = '[Equity International] Resumen Favoritos'
    email.body = message
    email.to = emails
    email.content_subtype = "html"
    enviado = email.send()
    return enviado
コード例 #34
0
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
コード例 #35
0
ファイル: functions.py プロジェクト: FrancoNoriUSB/equity
def movil_email(request, form, inmueble):

    emailF = form
    emails = []

    # Informacion del usuario
    emails.append('*****@*****.**')
    emails.append('*****@*****.**')
    emails.append('*****@*****.**')

    # Mensaje a enviar
    message = 'Correo de solicitud de visita de usuario con correo: ' + str(emailF.cleaned_data['correo']) + '<br>'
    message += 'Inmueble: ' + inmueble.titulo

    email = EmailMessage()
    email.subject = '[Equity International] Correo Visita'
    email.body = message
    email.to = emails
    email.content_subtype = "html"
    enviado = email.send()
    return enviado
コード例 #36
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.')
コード例 #37
0
def __send_invitation_creation_notification_by_email(sender, instance):
    destination_email = instance.invitation_to.email

    if CustomUser.objects.is_unregistered(
            destination_email):  # pragma: no cover -> no complexity
        send_email_to_register(destination_email)
    else:
        choices = dict(sender.type.field.choices)
        choice_label = choices.get(instance.type.upper())

        email = EmailMessage()
        email.subject = f"You have a new {choice_label} Invitation"
        email.body = f"""
        Hi {instance.invitation_to.username},

        {instance.invitation_from.username} sent an email to you.

        Hugs,
        """
        email.to = [instance.invitation_to.email]
        email.send()
コード例 #38
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)
コード例 #39
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()
コード例 #40
0
ファイル: downloadFeeds.py プロジェクト: Davidhw/infocatch
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()
コード例 #41
0
def active(request):
    id = request.POST.get('id')
    user2 = User.objects.get(id=id)
    user2.is_active = 1
    user2.save()

    print 'usuario activado'

    correo = EmailMessage()
    correo.subject = "Confirmación de acceso Portal Gastos"
    correo.body = """¡Bienvenido!
    Su solicitud fue confirmada. Ya puede ingresar al portal y registrar sus gastos, compras o
    consumos de tarjeta.
    Siempre a la orden.
    Equipo ACERH """
    correo.to = [user2.email]
    correo.send()

    user = User.objects.filter(is_active=0)
    return render(request, 'activate.html', {
        'user': user,
        'users': user.all()
    })
コード例 #42
0
ファイル: views.py プロジェクト: kamiljaved98/parkinglot
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)
コード例 #43
0
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
コード例 #44
0
ファイル: functions.py プロジェクト: FrancoNoriUSB/equity
def financiamiento_email(request, pais, form, inmueble):

    emails = []
    emails.append('*****@*****.**')
    emails.append('*****@*****.**')
    emails.append('*****@*****.**')
    correo = form.cleaned_data['correo']
    telefonos = form.cleaned_data['telefonos']

    message = '<p>Solicita Planes de Financiamiento' + correo + '</p>'

    if inmueble:
        message += '<a href="http://www.equity-international.com/' + pais + '/inmuebles/' + inmueble.codigo + '/" >' + inmueble.titulo + '</a>'

    if telefonos:
        message += '<br/><br/> Telefono de usuario: ' + telefonos

    email = EmailMessage()
    email.subject = '[Equity International] Solicitud de financiamiento'
    email.body = message
    email.to = emails
    email.content_subtype = "html"
    enviado = email.send()
    return enviado
コード例 #45
0
ファイル: views.py プロジェクト: beam018/atproject-server
    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.')
コード例 #46
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()
コード例 #47
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)
コード例 #48
0
def register2(request):
    if request.method == 'POST':
        codigo = request.POST.get('codigo')
        password = request.POST.get('password')
        nombres = request.POST.get('nombres')
        apellidos = request.POST.get('apellidos')
        cedula = request.POST.get('cedula')
        empresa = request.POST.get('empresa')
        puesto = request.POST.get('puesto')
        email = request.POST.get('email')
        telefono = request.POST.get('telefono')
        celular = request.POST.get('celular')
        supervisor = request.POST.get('supervisor')
        sup_email = request.POST.get('sup_email')
        sup_level2 = 'na'

        newuser = User.objects.create(first_name=nombres,
                                      last_name=apellidos,
                                      username=codigo,
                                      email=email)
        newuser.is_active = False
        newuser.set_password(password)
        newuser.save()

        print("usuario creado")

        profile = UserP.objects.create(user=newuser,
                                       cedula=cedula,
                                       empresa=empresa,
                                       puesto=puesto,
                                       telefono=telefono,
                                       celular=celular,
                                       supervisor=supervisor,
                                       email_super=sup_email)
        profile.save()

        print("perfil creado")

        print("preparando correo")

        correo = EmailMessage()
        correo.subject = "Solicitud acceso Gastos ACERH"
        correo.body = """Hola """ + nombres + ' ' + apellidos + """,
        Hemos recibido tu solicitud de acceso a nuestro portal de gastos, tan pronto nuestro
        equipo de gestores o el administrador valide la información enviada, te notificamos
        nuevamente confirmando o rechazando tu solicitud.
        Recordando que tu usuario es: """ + codigo + """ y la contraseña es: """ + password + """.
        Gracias por utilizar nuestros servicios.
        Equipo ACERH """
        correo.to = [email]
        correo.send()

        correo = EmailMessage()
        correo.subject = "Solicitud acceso Gastos ACERH"
        correo.body = """Hola Administrador,
        Tienes una solicitud de acceso en el Portal de Gastos ACERH.
        Usuario:""" + codigo + """
        Nombre:""" + nombres + ' ' + apellidos + """
        Email:""" + email + """ 
        Empresa:""" + empresa + """ """
        correo.to = ['*****@*****.**']
        correo.send()

        print("correo enviado")
        return render(request, 'register.html')
    else:

        return render(request, 'register.html')
コード例 #49
0
ファイル: update_tendenci.py プロジェクト: tendenci/tendenci
    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()
コード例 #50
0
ファイル: views.py プロジェクト: nworks16/gacerh
def email(request):
	email = EmailMessage()
	email.subject = "Hola mensaje de prueba desde el servidor de acerh"
	email.body = "Coneccion totalmente lograda, prueba test #2"
	email.to = [ "*****@*****.**"]
	email.send()
コード例 #51
0
ファイル: cron.py プロジェクト: KrzysztofW/lgc-django
        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()
コード例 #52
0
ファイル: views.py プロジェクト: hkilicer/forecast
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})