def save(self, validated_data): email = validated_data.get('email') new_user = User( username=email, email=email, is_active=False, ) new_user.save() # Create new salary instance new_salary = Salary(user=new_user) new_salary.save() # Create new adminprofile instance new_adminprofile = AdminProfile(user=new_user) new_adminprofile.save() # Create new company instance and assign admin_profile to new admin_profile, other fields have placeholder values new_company = Company(adminprofile=new_adminprofile) new_company.save() registration = Registration( user=new_user, code_type='RV', profile_type='AP', ) registration.save() email = Email( to=email, subject='Thank you for registering with RazzPay!', content=f'Here is your validation code: {registration.code}') email.save(request=self.context['request']) return new_user
def reenviar_email_confirmacion(request, usuario_id): # Se determina el usuario al que hay que volver a enviar el email de confirmación usuario = Usuario.objects.get(id=usuario_id) # Se llama al proceso que envía el mail Email.enviar_correo_registro_usuario(usuario=usuario) # Se recarga la página donde se encuentra el usuario return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def invite(request, id): event = get(Event, pk=id) email = Email(user = request.user, subject = "You're invited to %s" % (event.title), message = render_to_string("event_invite_email.txt", locals()), event = event ) email.save() return HttpResponseRedirect(reverse('emails-update', args=[email.id]))
def save(self, validated_data): # Obtain user info email = validated_data.get('email') first_name = validated_data.get('first_name') last_name = validated_data.get('last_name') company = self.context['request'].user.company # Obtain salary info gross_month = validated_data.get('gross_month') position = validated_data.get('position') new_user = User( username=email, email=email, first_name=first_name, last_name=last_name, company_id=company.id, # Mark as true so that employee user instance can be used immediately without waiting for employee to register via email code is_active=True, ) new_user.save() # Create new employeeprofile instance new_employeeprofile = EmployeeProfile(user=new_user) new_employeeprofile.save() # Create new salary instance new_salary = Salary(user=new_user, position=position, gross_month=round((gross_month), 2), ahv_amount=round((gross_month * 0.05125), 2), alv_amount=round((gross_month * 0.011), 2), pension=round((gross_month * 0.01), 2), net=round( (gross_month - (gross_month * 0.05125) - (gross_month * 0.011) - (gross_month * 0.01)), 2)) new_salary.save() registration = Registration( user=new_user, code_type='RV', profile_type='EP', ) registration.save() email = Email( to=email, subject='Welcome to RazzPay!', content=f'Here is your validation code: {registration.code}') email.save(request=self.context['request']) return new_user
def send_password_reset_email(self): email = self.validated_data.get('email') user = User.objects.get(email=email) user.registration.code = code_generator() user.registration.code_used = False user.registration.code_type = 'PR' user.registration.save() email = Email( to=email, subject='Reset your password for RazzPay', content= f'Here is your RazzPay password reset code: {user.registration.code}' ) email.save(request=self.context['request'])
def map_emails(g): unread_list = g.inbox().mail(unread=True) for email_object in unread_list: email_object.fetch() message_id = email_object.headers['Message-ID'].replace('<', '').replace('>', '') sender = email_object.headers['From'] body = strip_tags(email_object.body) body = '\n'.join(filter(None, body.replace('\t', '').replace('\r\n', '\n').split('\n'))) if body.strip(' \t\n\r') == '' or Email.objects.filter(message_id=message_id).count() > 0: email_object.add_label('discarded') continue subject = email_object.subject new = Email(message_id=message_id, subject=subject, body=body, sender=sender) new.save() email_object.read()
def send_message(message, to_user, email_type): # comment this out to test sending emails in other environments if settings.ENVIRONMENT != 'production': return email = Email(user=to_user, subject=message.subject, text_body=message.text, html_body=message.html, to_address=message.to[0], from_address=message.from_address, email_type=email_type) email.save() s = sendgrid.Sendgrid(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD, secure=True) s.smtp.send(message)
def email_script_errors(err_msg): """Send error message to us in case of an error. """ email = Email() email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress') email.sender_display = get_setting('site', 'global', 'sitedisplayname') site_url = get_setting('site', 'global', 'siteurl') now = datetime.now() nowstr = time.strftime("%d-%b-%y %I:%M %p", now.timetuple()) email.recipient = get_script_support_emails() if email.recipient: email.body = '%s \n\nTime Submitted: %s\n' % (err_msg, nowstr) email.content_type = "text" email.subject = 'Error Setting Up Campaign Monitor Account on New Site %s' % site_url email.send()
def get(self, request, *args, **kwargs): try: date_from = request.GET['date_from'] date_to = request.GET['date_to'] date_from = int(date_from, base=10) date_to = int(date_to, base=10) query_params = dict() query_params['date_from'] = timestamp_to_date(date_from) query_params['date_to'] = timestamp_to_date(date_to) query_params['empresa'] = request.GET['empresas'] query_params['tipo_receptor'] = request.GET['tipo_receptor'] statistic = Email.get_statistics_count_by_dates(**query_params) results = Email.get_statistics_range_by_dates(**query_params) data = { 'statistic': statistic, 'results': results, } data = json.dumps(data) return HttpResponse(data, content_type='application/json') except Exception as e: logger.error(e)
def get(self, request, *args, **kwargs): try: date_from = request.GET['date_from'] date_to = request.GET['date_to'] date_from = int(date_from, base=10) date_to = int(date_to, base=10) query_params = dict() query_params['date_from'] = timestamp_to_date(date_from) query_params['date_to'] = timestamp_to_date(date_to) query_params['empresa'] = request.GET['empresas'] query_params['tipo_receptor'] = request.GET['tipo_receptor'] statistic = Email.get_statistics_count_by_dates(**query_params) results = Email.get_statistics_range_by_dates(**query_params) data = { 'statistic': statistic, 'results': results, } data = json.dumps(data) return HttpResponse(data, content_type='application/json') except Exception, e: logging.error(e)
def recovery_password(cls, email, host): # 1 - Determinar si existe un usuario asociado al email indicado if not cls.objects.filter(user__email=email): message = 'No existe ninguna cuenta registrada con el E-Mail indicado' print(message) return {'message': message} else: # 2 - Generar un nuevo código de recuperación para el usuario asociado al email usuario = cls.objects.get(user__email=email) new_recovery_password_code = Codigo_Recovery_Password.nuevo_codigo_recovery_password( usuario).codigo # 3 - Enviar un email con una URL que incluya el código de recuperación, para que el usuario vea un formulario donde pueda # escribir su nueva contraseña recovery_password_email = Email.enviar_correo_recovery_password( host=host, code=new_recovery_password_code, email=email)
def email(user, subj, template, context, check_pref=False, from_email=settings.DEFAULT_FROM_EMAIL): from emails.models import Email from subs.models import Subscription if user.bounce not in (None, 0, 1): # 1 bounce is ok, but not more return False if check_pref: c = MailoutCategory.objects.get(pk=check_pref) s = MailoutUser.objects.filter(user=user, category=c).first() if not s: return subject = 'Hi %s, %s' % (user.first_name, subj) from_email = "%s <%s>" % (settings.NAME, from_email) if 'Feedback' in subj: subject = subj # subject must not contain newlines subject = ''.join(subject.splitlines()) em = Email(to=user, subject=subject, body='') em.save() # add some generic_context context.update(settings.GENERIC_CONTEXT) context.update({ 'user': user, 'subject': subj, # use original short subject here 'template': template, # for tracking 'em': em, 'category': check_pref or '' }) body = render_to_string('emails/%s.html' % template, context) text = render_as_text(body) em.body = '%s<!--\n%s\n-->' % (body, text) em.save() headers = { 'List-Unsubscribe': '<mailto:%s>' % UNSUBSCRIBE_EMAIL, 'X-EMAIL-ID': str(em.pk), 'X-USER-ID': str(user.pk), } m = mail.EmailMultiAlternatives(subject, text, from_email, [user.email], headers=headers) m.attach_alternative(body, "text/html") # live or test, no sending in dev if not settings.DEBUG or hasattr(mail, 'outbox'): try: m.send() except Exception as e: logging.basicConfig(filename=settings.LOG) logging.warning(e) return False return True
def post(self, request, *args, **kwargs): date_from = request.POST['date_from'] date_to = request.POST['date_to'] empresa = request.POST['empresas'] date_from = datetime.strptime(str(date_from), '%d/%m/%Y') date_to = datetime.strptime(str(date_to), '%d/%m/%Y') empresa = str(empresa) data = Email.get_emails_by_dates(date_from, date_to, empresa) report_file = create_tablib(data, empresa) report_file_format = get_report_file_format(empresa) if report_file_format == 'xlsx': response_file = report_file.xlsx response_filename = 'consolidado' + get_date_to_string() + report_file_format response_filetype = 'application/vnd.ms-excel' elif report_file_format == 'tsv': response_file = report_file.tsv response_filename = 'consolidado' + get_date_to_string() + report_file_format response_filetype = 'text/tsv' else: response_file = report_file.csv response_filename = 'consolidado' + get_date_to_string() + report_file_format response_filetype = 'text/csv' general_conf = GeneralConfiguration.get_configuration(empresa) if general_conf is not None and general_conf.report_file_zipped: # ejecutar proceso de comprimir reporte in_memory = StringIO() with ZipFile(in_memory, 'w') as archive: archive.writestr(response_filename, str(response_file), ZIP_DEFLATED) response = HttpResponse(in_memory.getvalue(), content_type="application/x-zip-compressed") response['Content-Disposition'] = 'attachment; filename="reporte.zip"' return response else: # retornar el reporte response = HttpResponse(response_file, content_type=response_filetype) response['Content-Disposition'] = 'attachment; filename="' + response_filename + '"' return response
def post(self, request, *args, **kwargs): request_body = json.loads(request.body.decode('utf-8')) for body in request_body: logger.info(body) try: evento_sendgrid = str(body['event']).decode('utf-8') correo = str(body['email']).decode('utf-8') numero_folio = str(body['numero_folio']).decode('utf-8') tipo_dte = str(body['tipo_dte']).decode('utf-8') rut_emisor = str(body['rut_emisor']).decode('utf-8') resolucion_emisor = str( body['resolucion_emisor']).decode('utf-8') empresa = str(body['empresa']).decode('utf-8') id_envio = str(body['id_envio']).decode('utf-8') tipo_receptor = str(body['tipo_receptor']).decode('utf-8') logger.info(evento_sendgrid) except Exception, e: logger.error(e) return HttpResponse(e) try: if evento_sendgrid and correo and numero_folio and tipo_dte and rut_emisor and resolucion_emisor and tipo_receptor: correo = str(correo).lower() numero_folio = int(numero_folio, base=10) logger.info("es un webhook para el tracking") if evento_sendgrid == 'processed': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio, tipo_receptor) logger.info(email) if email is not None: email.smtp_id = str( body['smtp-id']).decode('utf-8') email.processed_date = body['timestamp'] email.processed_event = evento_sendgrid email.processed_sg_event_id = str( body['sg_event_id']).decode('utf-8') email.processed_sg_message_id = str( body['sg_message_id']).decode('utf-8') email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: logger.info("paso else no existe") e = Email.set_default_fields(body) # parametros del evento e.smtp_id = str(body['smtp-id']).decode('utf-8') e.processed_date = body['timestamp'] e.processed_event = evento_sendgrid e.processed_sg_event_id = str( body['sg_event_id']).decode('utf-8') e.processed_sg_message_id = str( body['sg_message_id']).decode('utf-8') e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'delivered': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio, tipo_receptor) logger.info(email) if email is not None: email.empresa_id = empresa email.smtp_id = str( body['smtp-id']).decode('utf-8') email.delivered_date = body['timestamp'] email.delivered_event = evento_sendgrid email.delivered_sg_event_id = str( body['sg_event_id']).decode('utf-8') email.delivered_sg_message_id = str( body['sg_message_id']).decode('utf-8') email.delivered_response = str( body['response']).decode('utf-8') email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento e.smtp_id = str(body['smtp-id']).decode('utf-8') e.delivered_date = body['timestamp'] e.delivered_event = evento_sendgrid e.delivered_sg_event_id = str( body['sg_event_id']).decode('utf-8') e.delivered_sg_message_id = str( body['sg_message_id']).decode('utf-8') e.delivered_response = str( body['response']).decode('utf-8') e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'open': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio, tipo_receptor) logger.info(email) if email is not None: email.empresa_id = empresa if email.opened_first_date is None: email.opened_first_date = body['timestamp'] email.opened_last_date = body['timestamp'] email.opened_event = evento_sendgrid email.opened_ip = str(body['ip']).decode('utf-8') email.opened_user_agent = str( body['useragent']).decode('utf-8') email.opened_sg_event_id = str( body['sg_event_id']).decode('utf-8') email.opened_sg_message_id = str( body['sg_message_id']).decode('utf-8') email.opened_count += 1 email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento if e.opened_first_date is None: e.opened_first_date = body['timestamp'] e.opened_last_date = body['timestamp'] e.opened_event = evento_sendgrid e.opened_ip = str(body['ip']).decode('utf-8') e.opened_user_agent = str( body['useragent']).decode('utf-8') e.opened_sg_event_id = str( body['sg_event_id']).decode('utf-8') e.opened_sg_message_id = str( body['sg_message_id']).decode('utf-8') e.opened_count += 1 e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'dropped': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio, tipo_receptor) if email is not None: logger.info(email) email.empresa_id = empresa email.smtp_id = str( body['smtp-id']).decode('utf-8') email.dropped_date = body['timestamp'] email.dropped_sg_event_id = str( body['sg_event_id']).decode('utf-8') email.dropped_sg_message_id = str( body['sg_message_id']).decode('utf-8') email.dropped_reason = str( body['reason']).decode('utf-8') email.dropped_event = evento_sendgrid email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento e.smtp_id = str(body['smtp-id']).decode('utf-8') e.dropped_date = body['timestamp'] e.dropped_sg_event_id = str( body['sg_event_id']).decode('utf-8') e.dropped_sg_message_id = str( body['sg_message_id']).decode('utf-8') e.dropped_reason = str( body['reason']).decode('utf-8') e.dropped_event = evento_sendgrid e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'bounce': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio, tipo_receptor) if email is not None: logger.info(email) email.empresa_id = empresa email.bounce_date = body['timestamp'] email.bounce_event = evento_sendgrid email.bounce_sg_event_id = str( body['sg_event_id']).decode('utf-8') email.bounce_sg_message_id = str( body['sg_message_id']).decode('utf-8') email.bounce_reason = str( body['reason']).decode('utf-8') email.bounce_status = str( body['status']).decode('utf-8') email.bounce_type = str( body['type']).decode('utf-8') email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento e.bounce_date = body['timestamp'] e.bounce_event = evento_sendgrid e.bounce_sg_event_id = str( body['sg_event_id']).decode('utf-8') e.bounce_sg_message_id = str( body['sg_message_id']).decode('utf-8') e.bounce_reason = str( body['reason']).decode('utf-8') e.bounce_status = str( body['status']).decode('utf-8') e.bounce_type = str(body['type']).decode('utf-8') e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'unsubscribe': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio, tipo_receptor) if email is not None: logger.info(email) email.empresa_id = empresa email.unsubscribe_date = body['timestamp'] email.unsubscribe_uid = str( body['uid']).decode('utf-8') email.unsubscribe_purchase = str( body['purchase']).decode('utf-8') email.unsubscribe_id = str( body['id']).decode('utf-8') email.unsubscribe_event = evento_sendgrid email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento e.unsubscribe_date = body['timestamp'] e.unsubscribe_uid = str( body['uid']).decode('utf-8') e.unsubscribe_purchase = str( body['purchase']).decode('utf-8') e.unsubscribe_id = str(body['id']).decode('utf-8') e.unsubscribe_event = evento_sendgrid e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'click': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio, tipo_receptor) if email is not None: logger.info(email) email.empresa_id = empresa email.click_ip = str(body['ip']).decode('utf-8') email.click_purchase = '' email.click_useragent = str( body['useragent']).decode('utf-8') email.click_event = evento_sendgrid email.click_email = str( body['email']).decode('utf-8') email.click_date = body['timestamp'] email.click_url = str(body['url']).decode('utf-8') email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento e.click_ip = str(body['ip']).decode('utf-8') e.click_purchase = '' e.click_useragent = str( body['useragent']).decode('utf-8') e.click_event = evento_sendgrid e.click_email = str(body['email']).decode('utf-8') e.click_date = body['timestamp'] e.click_url = str(body['url']).decode('utf-8') e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: logger.error( "parametros incompletos, correo no corresponde.") except Exception, e: logger.error(e) return HttpResponse(e, status=500)
def get(self, request, date_from, date_to, empresa, correo, folio, rut, mount_from, mount_to, fallidos, op1, op2, op3, *args, **kwargs): parameters = dict() # preparación de parámetros date_from = int(date_from, base=10) date_to = int(date_to, base=10) date_from = timestamp_to_date(date_from) date_to = timestamp_to_date(date_to) parameters['date_from'] = date_from parameters['date_to'] = date_to parameters['empresa'] = empresa if correo == '-': correo = None parameters['correo'] = correo if folio == '-': folio = None parameters['folio'] = folio if rut == '-': rut = None parameters['rut'] = rut if mount_from == '-': mount_from = None else: mount_from = int(mount_from, base=10) parameters['mount_from'] = mount_from if mount_to == '-': mount_to = None else: mount_to = int(mount_to, base=10) parameters['mount_to'] = mount_to if fallidos == 'true': parameters['fallidos'] = True elif fallidos == 'false': parameters['fallidos'] = False else: parameters['fallidos'] = False if op1 == '-': parameters['opcional1'] = None else: parameters['opcional1'] = op1 if op2 == '-': parameters['opcional2'] = None else: parameters['opcional2'] = op2 if op3 == '-': parameters['opcional3'] = None else: parameters['opcional3'] = op3 # preparación de parámetros de paginación echo = request.GET['sEcho'] display_start = request.GET['iDisplayStart'] display_length = request.GET['iDisplayLength'] parameters['display_start'] = int(display_start, base=10) parameters['display_length'] = int(display_length, base=10) # ejecución de query dinamica emails = Email.get_emails_by_dynamic_query(**parameters) response = self.serializer_class(emails['data'], many=True) data = { 'sEcho': echo, 'data': response.data, 'iTotalDisplayRecords': emails['query_total'], 'iTotalRecords': emails['query_total'], } return Response(data)
def post(self, request, *args, **kwargs): request_body = json.loads(request.body.decode('utf-8')) for body in request_body: logging.info(request_body) try: evento_sendgrid = str(body['event']).decode('utf-8') email_id = str(body['email_id']).decode('utf-8') logging.info(evento_sendgrid) except Exception, e: logging.error(e) return HttpResponse(e) try: if evento_sendgrid and email_id: email_id = int(email_id, base=10) logging.info("es un webhook para el tracking") if evento_sendgrid == 'processed': email = Email.get_email_by_id(email_id) if email is not None: logging.info(email) email.smtp_id = str(body['smtp-id']).decode('utf-8') email.processed_date = body['timestamp'] email.processed_event = evento_sendgrid email.processed_sg_event_id = str(body['sg_event_id']).decode('utf-8') email.processed_sg_message_id = str(body['sg_message_id']).decode('utf-8') email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'delivered': email = Email.get_email_by_id(email_id) if email is not None: logging.info(email) email.smtp_id = str(body['smtp-id']).decode('utf-8') email.delivered_date = body['timestamp'] email.delivered_event = evento_sendgrid email.delivered_sg_event_id = str(body['sg_event_id']).decode('utf-8') email.delivered_sg_message_id = str(body['sg_message_id']).decode('utf-8') email.delivered_response = str(body['response']).decode('utf-8') email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'open': email = Email.get_email_by_id(email_id) if email is not None: logging.info(email) if email.opened_first_date is None: email.opened_first_date = body['timestamp'] email.opened_last_date = body['timestamp'] email.opened_event = evento_sendgrid email.opened_ip = str(body['ip']).decode('utf-8') email.opened_user_agent = str(body['useragent']).decode('utf-8') email.opened_sg_event_id = str(body['sg_event_id']).decode('utf-8') email.opened_sg_message_id = str(body['sg_message_id']).decode('utf-8') email.opened_count += 1 email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'dropped': email = Email.get_email_by_id(email_id) if email is not None: logging.info(email) email.smtp_id = str(body['smtp-id']).decode('utf-8') email.dropped_date = body['timestamp'] email.dropped_sg_event_id = str(body['sg_event_id']).decode('utf-8') email.dropped_sg_message_id = str(body['sg_message_id']).decode('utf-8') email.dropped_reason = str(body['reason']).decode('utf-8') email.dropped_event = evento_sendgrid email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'bounce': email = Email.get_email_by_id(email_id) if email is not None: logging.info(email) email.bounce_date = body['timestamp'] email.bounce_event = evento_sendgrid email.bounce_sg_event_id = str(body['sg_event_id']).decode('utf-8') email.bounce_sg_message_id = str(body['sg_message_id']).decode('utf-8') email.bounce_reason = str(body['reason']).decode('utf-8') email.bounce_status = str(body['status']).decode('utf-8') email.bounce_type = str(body['type']).decode('utf-8') email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'unsubscribe': email = Email.get_email_by_id(email_id) if email is not None: logging.info(email) email.unsubscribe_date = body['timestamp'] email.unsubscribe_uid = str(body['uid']).decode('utf-8') email.unsubscribe_purchase = str(body['purchase']).decode('utf-8') email.unsubscribe_id = str(body['id']).decode('utf-8') email.unsubscribe_event = evento_sendgrid email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'click': email = Email.get_email_by_id(email_id) if email is not None: logging.info(email) email.click_ip = str(body['ip']).decode('utf-8') email.click_purchase = '' email.click_useragent = str(body['useragent']).decode('utf-8') email.click_event = evento_sendgrid email.click_email = str(body['email']).decode('utf-8') email.click_date = body['timestamp'] email.click_url = str(body['url']).decode('utf-8') email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: logging.error("parametros incompletos, correo no corresponde.") except Exception, e: logging.error(e) return HttpResponse(e, status=500)
def post(self, request, *args, **kwargs): request_body = json.loads(request.body.decode('utf-8')) for body in request_body: logging.info(body) try: evento_sendgrid = str(body['event']).decode('utf-8') correo = str(body['email']).decode('utf-8') numero_folio = str(body['numero_folio']).decode('utf-8') tipo_dte = str(body['tipo_dte']).decode('utf-8') rut_emisor = str(body['rut_emisor']).decode('utf-8') resolucion_emisor = str(body['resolucion_emisor']).decode('utf-8') empresa = str(body['empresa']).decode('utf-8') id_envio = str(body['id_envio']).decode('utf-8') logging.info(evento_sendgrid) except Exception, e: logging.error(e) return HttpResponse(e) try: if evento_sendgrid and correo and numero_folio and tipo_dte and rut_emisor and resolucion_emisor: correo = str(correo).lower() numero_folio = int(numero_folio, base=10) logging.info("es un webhook para el tracking") if evento_sendgrid == 'processed': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio) logging.info(email) if email is not None: email.smtp_id = str(body['smtp-id']).decode('utf-8') email.processed_date = body['timestamp'] email.processed_event = evento_sendgrid email.processed_sg_event_id = str(body['sg_event_id']).decode('utf-8') email.processed_sg_message_id = str(body['sg_message_id']).decode('utf-8') email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: logging.info("paso else no existe") e = Email.set_default_fields(body) # parametros del evento e.smtp_id = str(body['smtp-id']).decode('utf-8') e.processed_date = body['timestamp'] e.processed_event = evento_sendgrid e.processed_sg_event_id = str(body['sg_event_id']).decode('utf-8') e.processed_sg_message_id = str(body['sg_message_id']).decode('utf-8') e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'delivered': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio) logging.info(email) if email is not None: email.empresa_id = empresa email.smtp_id = str(body['smtp-id']).decode('utf-8') email.delivered_date = body['timestamp'] email.delivered_event = evento_sendgrid email.delivered_sg_event_id = str(body['sg_event_id']).decode('utf-8') email.delivered_sg_message_id = str(body['sg_message_id']).decode('utf-8') email.delivered_response = str(body['response']).decode('utf-8') email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento e.smtp_id = str(body['smtp-id']).decode('utf-8') e.delivered_date = body['timestamp'] e.delivered_event = evento_sendgrid e.delivered_sg_event_id = str(body['sg_event_id']).decode('utf-8') e.delivered_sg_message_id = str(body['sg_message_id']).decode('utf-8') e.delivered_response = str(body['response']).decode('utf-8') e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'open': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio) logging.info(email) if email is not None: email.empresa_id = empresa if email.opened_first_date is None: email.opened_first_date = body['timestamp'] email.opened_last_date = body['timestamp'] email.opened_event = evento_sendgrid email.opened_ip = str(body['ip']).decode('utf-8') email.opened_user_agent = str(body['useragent']).decode('utf-8') email.opened_sg_event_id = str(body['sg_event_id']).decode('utf-8') email.opened_sg_message_id = str(body['sg_message_id']).decode('utf-8') email.opened_count += 1 email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento if e.opened_first_date is None: e.opened_first_date = body['timestamp'] e.opened_last_date = body['timestamp'] e.opened_event = evento_sendgrid e.opened_ip = str(body['ip']).decode('utf-8') e.opened_user_agent = str(body['useragent']).decode('utf-8') e.opened_sg_event_id = str(body['sg_event_id']).decode('utf-8') e.opened_sg_message_id = str(body['sg_message_id']).decode('utf-8') e.opened_count += 1 e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'dropped': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio) if email is not None: logging.info(email) email.empresa_id = empresa email.smtp_id = str(body['smtp-id']).decode('utf-8') email.dropped_date = body['timestamp'] email.dropped_sg_event_id = str(body['sg_event_id']).decode('utf-8') email.dropped_sg_message_id = str(body['sg_message_id']).decode('utf-8') email.dropped_reason = str(body['reason']).decode('utf-8') email.dropped_event = evento_sendgrid email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento e.smtp_id = str(body['smtp-id']).decode('utf-8') e.dropped_date = body['timestamp'] e.dropped_sg_event_id = str(body['sg_event_id']).decode('utf-8') e.dropped_sg_message_id = str(body['sg_message_id']).decode('utf-8') e.dropped_reason = str(body['reason']).decode('utf-8') e.dropped_event = evento_sendgrid e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'bounce': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio) if email is not None: logging.info(email) email.empresa_id = empresa email.bounce_date = body['timestamp'] email.bounce_event = evento_sendgrid email.bounce_sg_event_id = str(body['sg_event_id']).decode('utf-8') email.bounce_sg_message_id = str(body['sg_message_id']).decode('utf-8') email.bounce_reason = str(body['reason']).decode('utf-8') email.bounce_status = str(body['status']).decode('utf-8') email.bounce_type = str(body['type']).decode('utf-8') email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento e.bounce_date = body['timestamp'] e.bounce_event = evento_sendgrid e.bounce_sg_event_id = str(body['sg_event_id']).decode('utf-8') e.bounce_sg_message_id = str(body['sg_message_id']).decode('utf-8') e.bounce_reason = str(body['reason']).decode('utf-8') e.bounce_status = str(body['status']).decode('utf-8') e.bounce_type = str(body['type']).decode('utf-8') e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'unsubscribe': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio) if email is not None: logging.info(email) email.empresa_id = empresa email.unsubscribe_date = body['timestamp'] email.unsubscribe_uid = str(body['uid']).decode('utf-8') email.unsubscribe_purchase = str(body['purchase']).decode('utf-8') email.unsubscribe_id = str(body['id']).decode('utf-8') email.unsubscribe_event = evento_sendgrid email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento e.unsubscribe_date = body['timestamp'] e.unsubscribe_uid = str(body['uid']).decode('utf-8') e.unsubscribe_purchase = str(body['purchase']).decode('utf-8') e.unsubscribe_id = str(body['id']).decode('utf-8') e.unsubscribe_event = evento_sendgrid e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'click': email = Email.get_email(correo, numero_folio, tipo_dte, rut_emisor, resolucion_emisor, id_envio) if email is not None: logging.info(email) email.empresa_id = empresa email.click_ip = str(body['ip']).decode('utf-8') email.click_purchase = '' email.click_useragent = str(body['useragent']).decode('utf-8') email.click_event = evento_sendgrid email.click_email = str(body['email']).decode('utf-8') email.click_date = body['timestamp'] email.click_url = str(body['url']).decode('utf-8') email.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: e = Email.set_default_fields(body) # parametros del evento e.click_ip = str(body['ip']).decode('utf-8') e.click_purchase = '' e.click_useragent = str(body['useragent']).decode('utf-8') e.click_event = evento_sendgrid e.click_email = str(body['email']).decode('utf-8') e.click_date = body['timestamp'] e.click_url = str(body['url']).decode('utf-8') e.save() # proceso intermedio de soap web service soap_ws = SoapMiddleware(e.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: logging.error("parametros incompletos, correo no corresponde.") except Exception, e: logging.error(e) return HttpResponse(e, status=500)
def handle(self, *args, **options): verbosity = 1 if 'verbosity' in options: verbosity = options['verbosity'] from django.conf import settings from memberships.models import Notice, Membership, NoticeLog, NoticeLogRecord from base.utils import fieldify from emails.models import Email from profiles.models import Profile from site_settings.utils import get_setting site_display_name = get_setting('site', 'global', 'sitedisplayname') site_contact_name = get_setting('site', 'global', 'sitecontactname') site_contact_email = get_setting('site', 'global', 'sitecontactemail') site_url = get_setting('site', 'global', 'siteurl') corp_replace_str = """ <br /><br /> <font color="#FF0000"> Organizational Members, please contact your company Membership coordinator to ensure that your membership is being renewed. </font> """ email = Email() email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress') email.sender_display = site_display_name email.reply_to = site_contact_email now = datetime.now() nowstr = time.strftime("%d-%b-%y %I:%M %p", now.timetuple()) def email_admins_recap(notices, total_sent): """Send admins recap after the notices were processed. """ email.recipient = get_admin_emails() if email.recipient: template_name = "memberships/notices/email_recap.html" try: recap_email_content = render_to_string(template_name, {'notices':notices, 'total_sent':total_sent, 'site_url': site_url, 'site_display_name': site_display_name, 'site_contact_name': site_contact_name, 'site_contact_email': site_contact_email}) email.body = recap_email_content email.content_type = "html" email.subject = '%s Membership Notices Distributed' % site_display_name email.send() except TemplateDoesNotExist: pass def email_script_errors(err_msg): """Send error message to us if any. """ email.recipient = get_script_support_emails() if email.recipient: email.body = '%s \n\nTime Submitted: %s\n' % (err_msg, nowstr) email.content_type = "text" email.subject = 'Error Processing Membership Notices on %s' % site_url email.send() def get_script_support_emails(): admins = getattr(settings, 'ADMINS', None) if admins: recipients_list = [admin[1] for admin in admins] return ','.join(recipients_list) return None def get_admin_emails(): admin_emails = get_setting('module', 'memberships', 'membershiprecipients').strip() if admin_emails: admin_emails = admin_emails.split(',') if not admin_emails: admin_emails = (get_setting('site', 'global', 'admincontactemail').strip()).split(',') if admin_emails: admin_emails = ','.join(admin_emails) return admin_emails def process_notice(notice): notice.members_sent = [] num_sent = 0 if notice.notice_time == 'before': start_dt = now + timedelta(days=notice.num_days) else: start_dt = now - timedelta(days=notice.num_days) memberships = Membership.objects.filter(status=1) if notice.notice_type == 'join': memberships = memberships.filter(subscribe_dt__year=start_dt.year, subscribe_dt__month=start_dt.month, subscribe_dt__day=start_dt.day, renewal=False) elif notice.notice_type == 'renew': memberships = memberships.filter(subscribe_dt__year=start_dt.year, subscribe_dt__month=start_dt.month, subscribe_dt__day=start_dt.day, renewal=True) else: # 'expire' memberships = memberships.filter(expire_dt__year=start_dt.year, expire_dt__month=start_dt.month, expire_dt__day=start_dt.day) # filter by membership type if notice.membership_type: memberships = memberships.filter(membership_type=notice.membership_type) if memberships: email.content_type = notice.content_type # password passwd_str = """ If you've forgotten your password or need to reset the auto-generated one, click <a href="%s%s">here</a> and follow the instructions on the page to reset your password. """ % (site_url, reverse('auth_password_reset')) # notice.email_content = notice.email_content.replace("[password]", passwd_str) global_context = {'sitedisplayname': site_display_name, 'sitecontactname': site_contact_name, 'sitecontactemail': site_contact_email, 'timesubmitted': nowstr, 'password': passwd_str } # log notice sent notice_log = NoticeLog(notice=notice, num_sent=0) notice_log.save() notice.log = notice_log notice.err = '' memberships_count = memberships.count() for membership in memberships: try: email_member(notice, membership, global_context) if memberships_count <= 50: notice.members_sent.append(membership) num_sent += 1 # log record notice_log_record = NoticeLogRecord(notice_log=notice_log, membership=membership) notice_log_record.save() except: # catch the exception and email to developers notice.err += traceback.format_exc() if num_sent > 0: notice_log.num_sent = num_sent notice_log.save() return num_sent def email_member(notice, membership, global_context): user = membership.user body = notice.email_content context = membership.entry_items context.update(global_context) body = body.replace("[membershiptypeid]", str(membership.membership_type.id)) body = body.replace("[membershiplink]", '%s%s' % (site_url, membership.get_absolute_url())) # memberships page ------------ memberships_page = "%s%s%s" % \ (site_url, reverse('profile', args=[membership.user]), "#userview-memberships") body = body.replace("[renewlink]", memberships_page) if membership.expire_dt: body = body.replace("[expirationdatetime]", time.strftime("%d-%b-%y %I:%M %p", membership.expire_dt.timetuple())) else: body = body.replace("[expirationdatetime]", '') # corporate member corp_replace_str if membership.corporate_membership_id: body = body.replace("<!--[corporatemembernotice]-->", corp_replace_str) else: body = body.replace("<!--[corporatemembernotice]-->", "") context.update({'membershiptypeid': str(membership.membership_type.id), 'membershiplink': '%s%s' % (site_url, membership.get_absolute_url()), 'renewlink': memberships_page, 'membernumber': membership.member_number, 'membershiptype': membership.membership_type.name, }) if membership.expire_dt: context['expirationdatetime'] = time.strftime("%d-%b-%y %I:%M %p", membership.expire_dt.timetuple()) # corporate member corp_replace_str if membership.corporate_membership_id: context['corporatemembernotice'] = corp_replace_str body = fieldify(body) body = '%s <br /><br />%s' % (body, get_footer()) context = Context(context) template = Template(body) body = template.render(context) email.recipient = user.email email.subject = notice.subject.replace('(name)', user.get_full_name()) email.body = body if notice.sender: email.sender = notice.sender email.reply_to = notice.sender if notice.sender_display: email.sender_display = notice.sender_display email.send() if verbosity > 1: print 'To ', email.recipient, email.subject def get_footer(): return """ This e-mail was generated by Tendenci® Software - a web based membership management software solution www.tendenci.com developed by Schipul - The Web Marketing Company """ exception_str = "" notices = Notice.objects.filter(status=1, status_detail='active').exclude(notice_time='attimeof') if notices: if verbosity > 1: print "Start sending out notices to members:" total_notices = 0 total_sent = 0 for notice in notices: total_notices += 1 total_sent += process_notice(notice) if hasattr(notice, 'err'): exception_str += notice.err if total_sent > 0: processed_notices = [notice for notice in notices if hasattr(notice, 'log') and notice.log.num_sent>0] email_admins_recap(processed_notices, total_sent) # if there is any error, notify us if exception_str: email_script_errors(exception_str) if verbosity > 1: print 'Total notice processed: %d' % (total_notices) print 'Total email sent: %d' % (total_sent) print "Done" else: if verbosity > 1: print "No notices on the site."
def post(self, request, *args, **kwargs): logging.info(request.body) export_type = request.POST.get('export_type') if export_type == 'export_general_email': tipo_receptor = request.POST.get('tipo_receptor') empresa = request.POST.get('empresa') user_email = request.POST.get('user_email') file_name = request.POST.get('file_name') date_from = request.POST.get('date_from') date_to = request.POST.get('date_to') date_from = int(date_from, base=10) date_to = int(date_to, base=10) date_from = timestamp_to_date(date_from) date_to = timestamp_to_date(date_to) params = dict() params['date_from'] = date_from params['date_to'] = date_to params['empresa'] = empresa params['tipo_receptor'] = tipo_receptor # Consulta data = Email.get_emails_by_dates_async(**params) elif export_type == 'export_sended_email': tipo_receptor = request.POST.get('tipo_receptor') empresa = request.POST.get('empresa') user_email = request.POST.get('user_email') file_name = request.POST.get('file_name') date_from = request.POST.get('date_from') date_to = request.POST.get('date_to') date_from = int(date_from, base=10) date_to = int(date_to, base=10) date_from = timestamp_to_date(date_from) date_to = timestamp_to_date(date_to) params = dict() params['date_from'] = date_from params['date_to'] = date_to params['empresa'] = empresa params['tipo_receptor'] = tipo_receptor # Consulta data = Email.get_sended_emails_by_dates_async(**params) elif export_type == 'export_failure_email': tipo_receptor = request.POST.get('tipo_receptor') empresa = request.POST.get('empresa') user_email = request.POST.get('user_email') file_name = request.POST.get('file_name') date_from = request.POST.get('date_from') date_to = request.POST.get('date_to') date_from = int(date_from, base=10) date_to = int(date_to, base=10) date_from = timestamp_to_date(date_from) date_to = timestamp_to_date(date_to) params = dict() params['date_from'] = date_from params['date_to'] = date_to params['empresa'] = empresa params['tipo_receptor'] = tipo_receptor # Consulta data = Email.get_failure_emails_by_dates_async(**params) elif export_type == 'export_dynamic_emails': user_email = request.POST.get('user_email') empresa = request.POST.get('empresa') file_name = request.POST.get('file_name') params = request.POST.get('params') params = json.loads(params) logging.info(params) data = Email.get_emails_by_dynamic_query_async(**params) if data is not None: # Creación del documento report_file = create_tablib(data, empresa) # evaluacion del formato del archivo reporte report_file_format = get_report_file_format(empresa) if report_file_format == 'xlsx': response_file = report_file.xlsx response_filename = file_name elif report_file_format == 'tsv': response_file = report_file.tsv response_filename = file_name else: response_file = report_file.csv response_filename = file_name # evaluar si el archivo es comprimido en zip general_conf = GeneralConfiguration.get_configuration(empresa) if general_conf is not None and general_conf.report_file_zipped: # ejecutar proceso de comprimir reporte in_memory = StringIO() with ZipFile(in_memory, 'w') as archive: archive.writestr(response_filename, str(response_file), ZIP_DEFLATED) response_file = in_memory.getvalue() response_filename = file_name + '.zip' # Crear objeto para enviarlo por correo data = dict() data['name'] = response_filename data['report'] = response_file # preparación de parametros mail = EmailClient(empresa) mail.send_report_to_user_with_attach(user_email, data) data = {"status": "ok"} return HttpResponse(json.dumps(data), content_type="application/json") else: logging.info("No se crear el archivo reporte por consulta vacía.") data = {"status": "consulta vacía"} return HttpResponse(json.dumps(data), content_type="application/json")
def __init__(self, email_id, event): self.email_id = email_id self.event = event holding = Email.get_email_by_id(email_id).empresa.holding self.soap_conf = SoapWebService.get_ws_conf(holding) logging.info("Objeto SoapMiddleware creado")
def __init__(self, email_id, event): self.email_id = email_id self.event = event holding = Email.get_email_by_id(email_id).empresa.holding self.soap_conf = SoapWebService.get_ws_conf(holding) logger.info("Objeto SoapMiddleware creado")
def nuevo_usuario_tras_pago_paypal(cls, payer): # Hay que obtener primero que nada el email con el que se ha realizado la compra, y ver si pertenece # a algún usuario del sitio. Si es así, no se crea el usuario sino que se registra toda la información en relación a su cuenta # En caso contrario hay que crear el usuario y pasar la información en la session a nuestra BD payer_data = Paypal_App.get_payer_data(payer=payer) email = payer_data['email'] first_name = payer_data['first_name'] last_name = payer_data['last_name'] pais_paypal = payer_data['pais_paypal'] provincia_paypal = payer_data['provincia_paypal'] direccion = payer_data['direccion'] ciudad = payer_data['ciudad'] codigo_postal = payer_data['codigo_postal'] if cls.objects.filter(user__email=email): n_usuario = cls.objects.get(user__email=email) return n_usuario else: # Se intenta determinar el país, pero si no se puede, se establece None try: country = Pais.get_pais_from_name(name=pais_paypal) except: country = None # Igualmente se intenta establecer el objeto Provincia a partir de la información de Paypal, o None try: provincia = Provincia.get_provincia_from_name( name=provincia_paypal) except: provincia = None # Intentaremos usar el namespace del email para crear un username, si no se puede porque ya existe, # probamos a añadirle al final 4 caracteres aleatorios, hasta que encontremos una combinación inexistente en nuestra BD username = cls.create_username_from_email(email) password = generate_random_password() # Ahora con los datos recogidos, se crea el usuario user_model = User.objects.create( username=username, email=email, first_name=first_name, last_name=last_name, ) # Se le asigna el password user_model.set_password(password) user_model.save() # Crea el objeto Usuario asociado al Usuario creado. n_usuario = cls.nuevo_usuario( user=user_model, raw_password=password, ) # El usuario se modifica con los datos recibidos de Paypal en el momento de la compra n_usuario.verificado_email = True # Un usuario que se crea porque pague no debe validar el email que utilizó para la compra n_usuario.pais = country n_usuario.provincia = provincia n_usuario.ciudad = ciudad n_usuario.codigo_postal = codigo_postal n_usuario.direccion = direccion n_usuario.save() # Se envía un Email de registro sin necesidad de validar la dirección Email.enviar_correo_registro_usuario_sin_validacion(n_usuario) # Devolvemos el usuario que hemos creado return n_usuario
company=random.choice(companies), position=fake.job(), email=fake.email(), phone_number=fake.phone_number(), is_warm_contact=fake.boolean(), ) contact.save() contacts.append(contact) print("Generating emails...") emails = [] for i in range(100): status = random.choice(["sent", "scheduled", "draft"]) email = Email( subject=fake.sentences(nb=1, ext_word_list=None)[0], body=fake.text(max_nb_chars=200, ext_word_list=None), status=status, created_by=random.choice(users), ) if status == "scheduled": email.time_scheduled = fake.date_time_this_month(before_now=False, after_now=True, tzinfo=pytz.UTC) elif status == "sent": email.time_sent = fake.date_time_this_month(before_now=True, after_now=False, tzinfo=pytz.UTC) email.save() emails.append(email) print("Generating hackathons...") hackathons = []
def save(self, request): from django.template.loader import render_to_string from django.template import RequestContext from emails.models import Email from newsletters.utils import newsletter_articles_list, newsletter_news_list, \ newsletter_pages_list, newsletter_jobs_list from site_settings.utils import get_setting # converted from function newsletters_generate_processor opening_text = render_to_string('newsletters/opening_text.txt', context_instance=RequestContext(request)) simplified = self.cleaned_data['format'] try: simplified = int(simplified) except: simplified = 0 # articles art_content = "" if self.cleaned_data['articles']: articles_days = self.cleaned_data['articles_days'] art_content = newsletter_articles_list(request, articles_days, simplified) # calendar events event_content = "" if self.cleaned_data['events']: pass # news news_content = "" if self.cleaned_data['news']: news_days = self.cleaned_data['news_days'] news_content = newsletter_news_list(request, news_days, simplified) # jobs job_content = "" if self.cleaned_data['jobs']: jobs_days = self.cleaned_data['jobs_days'] job_content = newsletter_jobs_list(request, jobs_days, simplified) # pages page_content = "" if self.cleaned_data['pages']: pages_days = self.cleaned_data['pages_days'] page_content = newsletter_pages_list(request, pages_days, simplified) # jumplink jumplink_content = "" if self.cleaned_data['jump_links']: jumplink_content = render_to_string('newsletters/jumplinks.txt', locals(), context_instance=RequestContext(request)) # login block login_content = "" if self.cleaned_data['include_login']: login_content = render_to_string('newsletters/login.txt', context_instance=RequestContext(request)) # rss list email_d = {} # store all content in email_d["[content]"] # will be used to replace [content] in the template email_d["[content]"] = opening_text # get the newsletter template now template = 'newsletters/templates/%s' % (self.cleaned_data['template']) email_d['template_path_name'] = template #check if we have [jumplink] in the email template, if not, #include the jumplinks at the top of the newsletter template_content = render_to_string(template) if jumplink_content: if template_content.find("[jumplinks]") == -1: email_d["[content]"] += jumplink_content email_d["[content]"] += "%s%s%s%s%s%s" % (login_content, event_content, art_content, news_content, job_content, page_content) email_d["[jumplinks]"] = jumplink_content email_d["[articles]"] = art_content email_d["[calendarevents]"] = event_content email_d["[events]"] = event_content email_d["[jobs]"] = job_content email_d["[contentmanagers]"] = page_content email_d["[pages]"] = page_content email_d["[releases]"] = news_content email_d["[news]"] = news_content email_d["[sitewebmaster]"] = get_setting('site', "global", "sitewebmaster") email_d["[sitedisplayname]"] = get_setting('site', "global", "sitedisplayname") today = datetime.date.today() email_d["[monthsubmitted]"] = today.strftime("%B") # June email_d["[yearsubmitted]"] = today.strftime("%Y") # 2010 email_d["[unsubscribeurl]"] = "[unsubscribeurl]" email_d["[currentweekdayname]"] = today.strftime("%A") # Wednesday email_d["[currentday]"] = today.strftime("%d") email_d["[currentmonthname]"] = today.strftime("%B") email = Email() is_valid = email.template_body(email_d) email.sender_display = "%s %s" % (request.user.first_name, request.user.last_name) email.sender = request.user.email email.reply_to = request.user.email email.recipient = request.user.email #email.send_to_email2 email.content_type = 'text/html' personalize_subject_first_name = self.cleaned_data['personalize_subject_first_name'] personalize_subject_last_name = self.cleaned_data['personalize_subject_last_name'] email.subject = self.cleaned_data['subject'] if personalize_subject_first_name and personalize_subject_last_name: email.subject = "[firstname] [lastname], " + email.subject elif personalize_subject_first_name: email.subject = "[firstname], " + email.subject elif personalize_subject_last_name: email.subject = "[lastname], " + email.subject email.status = 1 email.status_detail = 'active' email.category = 'marketing' email.save(request.user) # action object - these 3 already included on the form: member_only, group and send_to_emails now = datetime.datetime.now() self.instance.email = email self.instance.name = email.subject self.instance.type = 'Distribution E-mail' self.instance.name = email.subject self.instance.description = '%s Electronic Newsletter: generated %s' % \ (get_setting('site', "global", "sitedisplayname"), now.strftime('%d-%b-%y %I:%M:%S %p')) self.instance.category = 'marketing' self.instance.due_dt = now try: entity = (request.user.get_profile()).entity except: entity = None if entity: self.instance.entity = entity self.instance.status = 1 self.instance.status_detail = 'open' self.instance.save(request.user) return self.instance
def execute(self): """ Validar si la URL para el servicio web esta disponible """ if self.soap_conf.url: # Creacion de la instancia Client client = Client(self.soap_conf.url, cache=None) email = Email.get_email_by_id(self.email_id) documento = None body = None if email is not None: email = email.__dict__ if self.soap_conf.con_autenticacion: """ Método por definir cuando el cliente solicita algún metodo de autenticación a un web service """ pass if self.soap_conf.con_objeto_documento: # Se prepara el objeto documento logger.info("creando objeto documento") documento = client.factory.create( self.soap_conf.nombre_objeto_documento) doc_attr = self.soap_conf.parametros_objeto_documento.split( ';') doc_field = self.soap_conf.campos_objeto_documento.split( ';') for att, field in map(None, doc_attr, doc_field): documento[att] = email[field] logger.info("imprimiendo documento") logger.info(documento) if self.soap_conf.con_objeto_request: logger.info("Creando objeto request") body = client.factory.create( self.soap_conf.nombre_objeto_request) if self.soap_conf.solo_default: """ Método por definir cuando se utiliza un solo metodo para notificar eventos sendgrid a un web service """ pass else: if self.event == 'processed': logger.info("ws procesados") data = dict() params = self.soap_conf.parametros_procesado.split(';') fields = self.soap_conf.campos_procesado.split(';') client = getattr(client.service, self.soap_conf.metodo_procesado) for param, field in map(None, params, fields): logger.info(field) logger.info(email[field]) """ Validar si los parametros se guardan en la variable data o en body. """ if self.soap_conf.con_objeto_request: if field.endswith( '_date') and email[field] is not None: logger.info(email[field]) field = timestamp_to_date(email[field]) body[param] = field elif field.endswith( '_date') and email[field] is None: body[param] = datetime.now() else: body[param] = email[field] if documento is not None: body[ self.soap_conf. nombre_parametro_documento] = documento logger.info("imprimiendo resultado del WS") logger.info(client(body)) else: if field.endswith( '_date') and email[field] is not None: logger.info(email[field]) field = timestamp_to_date(email[field]) data[param] = field elif field.endswith( '_date') and email[field] is None: data[param] = datetime.now() else: data[param] = email[field] if documento is not None: data[ self.soap_conf. nombre_parametro_documento] = documento logger.info("imprimiendo resultado del WS") logger.info(client(**data)) elif self.event == 'delivered': logger.info("ws enviados") data = dict() params = self.soap_conf.parametros_enviado.split(';') fields = self.soap_conf.campos_enviado.split(';') client = getattr(client.service, self.soap_conf.metodo_enviado) for param, field in map(None, params, fields): logger.info(field) if self.soap_conf.con_objeto_request: if field.endswith( '_date') and email[field] is not None: logger.info(email[field]) field = timestamp_to_date(email[field]) body[param] = field elif field.endswith( '_date') and email[field] is None: body[param] = datetime.now() else: body[param] = email[field] if documento is not None: body[ self.soap_conf. nombre_parametro_documento] = documento logger.info("imprimiendo resultado del WS") logger.info(client(body)) else: if field.endswith( '_date') and email[field] is not None: logger.info(email[field]) field = timestamp_to_date(email[field]) data[param] = field elif field.endswith( '_date') and email[field] is None: data[param] = datetime.now() else: data[param] = email[field] if documento is not None: data[ self.soap_conf. nombre_parametro_documento] = documento logger.info("imprimiendo resultado del WS") logger.info(client(**data)) elif self.event == 'open': logger.info("ws leidos") data = dict() params = self.soap_conf.parametros_leido.split(';') fields = self.soap_conf.campos_leido.split(';') client = getattr(client.service, self.soap_conf.metodo_leido) for param, field in map(None, params, fields): if self.soap_conf.con_objeto_request: if field.endswith( '_date') and email[field] is not None: logger.info(email[field]) field = timestamp_to_date(email[field]) body[param] = field elif field.endswith( '_date') and email[field] is None: body[param] = datetime.now() else: body[param] = email[field] if documento is not None: body[ self.soap_conf. nombre_parametro_documento] = documento logger.info("imprimiendo resultado del WS") logger.info(client(body)) else: if field.endswith( '_date') and email[field] is not None: logger.info(email[field]) field = timestamp_to_date(email[field]) data[param] = field elif field.endswith( '_date') and email[field] is None: data[param] = datetime.now() else: data[param] = email[field] if documento is not None: data[ self.soap_conf. nombre_parametro_documento] = documento logger.info("imprimiendo resultado del WS") logger.info(client(**data)) elif self.event == 'dropped': logger.info("ws rechazados") data = dict() params = self.soap_conf.parametros_rechazado.split(';') fields = self.soap_conf.campos_rechazado.split(';') client = getattr(client.service, self.soap_conf.metodo_rechazado) for param, field in map(None, params, fields): if self.soap_conf.con_objeto_request: if field.endswith( '_date') and email[field] is not None: logger.info(email[field]) field = timestamp_to_date(email[field]) body[param] = field elif field.endswith( '_date') and email[field] is None: body[param] = datetime.now() else: body[param] = email[field] if documento is not None: body[ self.soap_conf. nombre_parametro_documento] = documento logger.info("imprimiendo resultado del WS") logger.info(client(body)) else: if field.endswith( '_date') and email[field] is not None: logger.info(email[field]) field = timestamp_to_date(email[field]) data[param] = field elif field.endswith( '_date') and email[field] is None: data[param] = datetime.now() else: data[param] = email[field] if documento is not None: data[ self.soap_conf. nombre_parametro_documento] = documento logger.info("imprimiendo resultado del WS") logger.info(client(**data)) elif self.event == 'bounce': logger.info("ws rebotados") data = dict() params = self.soap_conf.parametros_rebotado.split(';') fields = self.soap_conf.campos_rebotado.split(';') client = getattr(client.service, self.soap_conf.metodo_rebotado) for param, field in map(None, params, fields): if self.soap_conf.con_objeto_request: if field.endswith( '_date') and email[field] is not None: logger.info(email[field]) field = timestamp_to_date(email[field]) body[param] = field elif field.endswith( '_date') and email[field] is None: body[param] = datetime.now() else: body[param] = email[field] if documento is not None: body[ self.soap_conf. nombre_parametro_documento] = documento logger.info("imprimiendo resultado del WS") logger.info(client(body)) else: if field.endswith( '_date') and email[field] is not None: logger.info(email[field]) field = timestamp_to_date(email[field]) data[param] = field elif field.endswith( '_date') and email[field] is None: data[param] = datetime.now() else: data[param] = email[field] if documento is not None: data[ self.soap_conf. nombre_parametro_documento] = documento logger.info("imprimiendo resultado del WS") logger.info(client(**data)) else: logger.error("Email id no corresponde") else: logger.error('No hay url soap ws configurada')
def post(self, request, *args, **kwargs): request_body = json.loads(request.body.decode('utf-8')) for body in request_body: logger.info(request_body) try: evento_sendgrid = str(body['event']).decode('utf-8') email_id = str(body['email_id']).decode('utf-8') logger.info(evento_sendgrid) except Exception, e: logger.error(e) return HttpResponse(e) try: if evento_sendgrid and email_id: email_id = int(email_id, base=10) logger.info("es un webhook para el tracking") if evento_sendgrid == 'processed': email = Email.get_email_by_id(email_id) if email is not None: logger.info(email) email.smtp_id = str( body['smtp-id']).decode('utf-8') email.processed_date = body['timestamp'] email.processed_event = evento_sendgrid email.processed_sg_event_id = str( body['sg_event_id']).decode('utf-8') email.processed_sg_message_id = str( body['sg_message_id']).decode('utf-8') email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'delivered': email = Email.get_email_by_id(email_id) if email is not None: logger.info(email) email.smtp_id = str( body['smtp-id']).decode('utf-8') email.delivered_date = body['timestamp'] email.delivered_event = evento_sendgrid email.delivered_sg_event_id = str( body['sg_event_id']).decode('utf-8') email.delivered_sg_message_id = str( body['sg_message_id']).decode('utf-8') email.delivered_response = str( body['response']).decode('utf-8') email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'open': email = Email.get_email_by_id(email_id) if email is not None: logger.info(email) if email.opened_first_date is None: email.opened_first_date = body['timestamp'] email.opened_last_date = body['timestamp'] email.opened_event = evento_sendgrid email.opened_ip = str(body['ip']).decode('utf-8') email.opened_user_agent = str( body['useragent']).decode('utf-8') email.opened_sg_event_id = str( body['sg_event_id']).decode('utf-8') email.opened_sg_message_id = str( body['sg_message_id']).decode('utf-8') email.opened_count += 1 email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'dropped': email = Email.get_email_by_id(email_id) if email is not None: logger.info(email) email.smtp_id = str( body['smtp-id']).decode('utf-8') email.dropped_date = body['timestamp'] email.dropped_sg_event_id = str( body['sg_event_id']).decode('utf-8') email.dropped_sg_message_id = str( body['sg_message_id']).decode('utf-8') email.dropped_reason = str( body['reason']).decode('utf-8') email.dropped_event = evento_sendgrid email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'bounce': email = Email.get_email_by_id(email_id) if email is not None: logger.info(email) email.bounce_date = body['timestamp'] email.bounce_event = evento_sendgrid email.bounce_sg_event_id = str( body['sg_event_id']).decode('utf-8') email.bounce_sg_message_id = str( body['sg_message_id']).decode('utf-8') email.bounce_reason = str( body['reason']).decode('utf-8') email.bounce_status = str( body['status']).decode('utf-8') email.bounce_type = str( body['type']).decode('utf-8') email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'unsubscribe': email = Email.get_email_by_id(email_id) if email is not None: logger.info(email) email.unsubscribe_date = body['timestamp'] email.unsubscribe_uid = str( body['uid']).decode('utf-8') email.unsubscribe_purchase = str( body['purchase']).decode('utf-8') email.unsubscribe_id = str( body['id']).decode('utf-8') email.unsubscribe_event = evento_sendgrid email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) elif evento_sendgrid == 'click': email = Email.get_email_by_id(email_id) if email is not None: logger.info(email) email.click_ip = str(body['ip']).decode('utf-8') email.click_purchase = '' email.click_useragent = str( body['useragent']).decode('utf-8') email.click_event = evento_sendgrid email.click_email = str( body['email']).decode('utf-8') email.click_date = body['timestamp'] email.click_url = str(body['url']).decode('utf-8') email.save() soap_ws = SoapMiddleware(email.pk, evento_sendgrid) soap_ws.evaluate() # proceso de registrar eventos en tabla log EmailLogEvent.write_event(evento_sendgrid, body) else: logger.error( "parametros incompletos, correo no corresponde.") except Exception, e: logger.error(e) return HttpResponse(e, status=500)
def log_email(to, from_email, subject, message): email = Email( to=to, from_email=from_email, subject=subject, message=message ) email.save()
emailid, "(RFC822)" ) # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc email_body = data[0][1] # getting the mail content mail = email.message_from_string(email_body) # parsing the mail content to get a mail object print i try: print "[" + mail["From"] + "] :" + mail["Subject"] except: try: print "[" + mail["From"] + "] :" except: pass content = unicode(mail.__str__(), errors="ignore") mailsave = Email() mailsave.Sender = mail["From"] mailsave.Content = content mailsave.Title = mail["Subject"] mailsave.save() if mail.get_content_maintype() != "multipart": continue # we use walk to creatone a generator so we can iterate on the parts and forget about the recursive headach j = 0 for part in mail.walk(): # multipart are just containers, so we skip them if part.get_content_maintype() == "multipart": continue # is this part an attachment ?
def execute(self): """ Validar si la URL para el servicio web esta disponible """ if self.soap_conf.url: # Creacion de la instancia Client client = Client(self.soap_conf.url, cache=None) email = Email.get_email_by_id(self.email_id) documento = None body = None if email is not None: email = email.__dict__ if self.soap_conf.con_autenticacion: """ Método por definir cuando el cliente solicita algún metodo de autenticación a un web service """ pass if self.soap_conf.con_objeto_documento: # Se prepara el objeto documento logging.info("creando objeto documento") documento = client.factory.create(self.soap_conf.nombre_objeto_documento) doc_attr = (self.soap_conf.parametros_objeto_documento).split(';') doc_field = (self.soap_conf.campos_objeto_documento).split(';') for att, field in map(None, doc_attr, doc_field): documento[att] = email[field] logging.info("imprimiendo documento") logging.info(documento) if self.soap_conf.con_objeto_request: logging.info("Creando objeto request") body = client.factory.create(self.soap_conf.nombre_objeto_request) if self.soap_conf.solo_default: """ Método por definir cuando se utiliza un solo metodo para notificar eventos sendgrid a un web service """ pass else: if self.event == 'processed': logging.info("ws procesados") data = dict() params = (self.soap_conf.parametros_procesado).split(';') fields = (self.soap_conf.campos_procesado).split(';') client = getattr(client.service, self.soap_conf.metodo_procesado) for param, field in map(None, params, fields): logging.info(field) logging.info(email[field]) """ Validar si los parametros se guardan en la variable data o en body. """ if self.soap_conf.con_objeto_request: if field.endswith('_date') and email[field] is not None: logging.info(email[field]) field = timestamp_to_date(email[field]) body[param] = field elif field.endswith('_date') and email[field] is None: body[param] = datetime.now() else: body[param] = email[field] if documento is not None: body[self.soap_conf.nombre_parametro_documento] = documento logging.info("imprimiendo resultado del WS") logging.info(client(body)) else: if field.endswith('_date') and email[field] is not None: logging.info(email[field]) field = timestamp_to_date(email[field]) data[param] = field elif field.endswith('_date') and email[field] is None: data[param] = datetime.now() else: data[param] = email[field] if documento is not None: data[self.soap_conf.nombre_parametro_documento] = documento logging.info("imprimiendo resultado del WS") logging.info(client(**data)) elif self.event == 'delivered': logging.info("ws enviados") data = dict() params = (self.soap_conf.parametros_enviado).split(';') fields = (self.soap_conf.campos_enviado).split(';') client = getattr(client.service, self.soap_conf.metodo_enviado) for param, field in map(None, params, fields): logging.info(field) if self.soap_conf.con_objeto_request: if field.endswith('_date') and email[field] is not None: logging.info(email[field]) field = timestamp_to_date(email[field]) body[param] = field elif field.endswith('_date') and email[field] is None: body[param] = datetime.now() else: body[param] = email[field] if documento is not None: body[self.soap_conf.nombre_parametro_documento] = documento logging.info("imprimiendo resultado del WS") logging.info(client(body)) else: if field.endswith('_date') and email[field] is not None: logging.info(email[field]) field = timestamp_to_date(email[field]) data[param] = field elif field.endswith('_date') and email[field] is None: data[param] = datetime.now() else: data[param] = email[field] if documento is not None: data[self.soap_conf.nombre_parametro_documento] = documento logging.info("imprimiendo resultado del WS") logging.info(client(**data)) elif self.event == 'open': logging.info("ws leidos") data = dict() params = (self.soap_conf.parametros_leido).split(';') fields = (self.soap_conf.campos_leido).split(';') client = getattr(client.service, self.soap_conf.metodo_leido) for param, field in map(None, params, fields): if self.soap_conf.con_objeto_request: if field.endswith('_date') and email[field] is not None: logging.info(email[field]) field = timestamp_to_date(email[field]) body[param] = field elif field.endswith('_date') and email[field] is None: body[param] = datetime.now() else: body[param] = email[field] if documento is not None: body[self.soap_conf.nombre_parametro_documento] = documento logging.info("imprimiendo resultado del WS") logging.info(client(body)) else: if field.endswith('_date') and email[field] is not None: logging.info(email[field]) field = timestamp_to_date(email[field]) data[param] = field elif field.endswith('_date') and email[field] is None: data[param] = datetime.now() else: data[param] = email[field] if documento is not None: data[self.soap_conf.nombre_parametro_documento] = documento logging.info("imprimiendo resultado del WS") logging.info(client(**data)) elif self.event == 'dropped': logging.info("ws rechazados") data = dict() params = (self.soap_conf.parametros_rechazado).split(';') fields = (self.soap_conf.campos_rechazado).split(';') client = getattr(client.service, self.soap_conf.metodo_rechazado) for param, field in map(None, params, fields): if self.soap_conf.con_objeto_request: if field.endswith('_date') and email[field] is not None: logging.info(email[field]) field = timestamp_to_date(email[field]) body[param] = field elif field.endswith('_date') and email[field] is None: body[param] = datetime.now() else: body[param] = email[field] if documento is not None: body[self.soap_conf.nombre_parametro_documento] = documento logging.info("imprimiendo resultado del WS") logging.info(client(body)) else: if field.endswith('_date') and email[field] is not None: logging.info(email[field]) field = timestamp_to_date(email[field]) data[param] = field elif field.endswith('_date') and email[field] is None: data[param] = datetime.now() else: data[param] = email[field] if documento is not None: data[self.soap_conf.nombre_parametro_documento] = documento logging.info("imprimiendo resultado del WS") logging.info(client(**data)) elif self.event == 'bounce': logging.info("ws rebotados") data = dict() params = (self.soap_conf.parametros_rebotado).split(';') fields = (self.soap_conf.campos_rebotado).split(';') client = getattr(client.service, self.soap_conf.metodo_rebotado) for param, field in map(None, params, fields): if self.soap_conf.con_objeto_request: if field.endswith('_date') and email[field] is not None: logging.info(email[field]) field = timestamp_to_date(email[field]) body[param] = field elif field.endswith('_date') and email[field] is None: body[param] = datetime.now() else: body[param] = email[field] if documento is not None: body[self.soap_conf.nombre_parametro_documento] = documento logging.info("imprimiendo resultado del WS") logging.info(client(body)) else: if field.endswith('_date') and email[field] is not None: logging.info(email[field]) field = timestamp_to_date(email[field]) data[param] = field elif field.endswith('_date') and email[field] is None: data[param] = datetime.now() else: data[param] = email[field] if documento is not None: data[self.soap_conf.nombre_parametro_documento] = documento logging.info("imprimiendo resultado del WS") logging.info(client(**data)) else: logging.error("Email id no corresponde") else: logging.error('No hay url soap ws configurada')
def _process_email_for_display(email: Email): email.html = get_email_html(email) for attachment in email.emailattachment_set.all(): attachment.file.display_name = os.path.basename(attachment.file.name)
def login_view(request): if request.user.is_authenticated(): return redirect('website:index') if request.method == 'POST': # Caso en que el POST venga del formulario de Login de usuario if 'login' in request.POST: # Esto debe aparecer en el name del submit login_form = Login_Form(request.POST) register_form = Registro_Usuario() if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] # Comprueba que existe un usuario con ese username o con ese email if User.objects.filter(username=username): user = authenticate(username=username, password=password) elif User.objects.filter(email=username): usuario = User.objects.get(email=username) user = authenticate(username=usuario.username, password=password) else: # Si no existe ningún usuario registrado con un username o un email igual al valor pasado por el usuario, user = None user = None # Realiza las acciones correspondientes si se ha encontrado un usuario con las credenciales adquiridas if user: # Comprueba que el usuario no está desactivado if user.is_active: # Realiza el login del usuario login(request, user) # Redirecciona a la página que se desee return redirect('/index/') else: class_alert = 'alert alert-danger' message = 'Este usuario se encuentra inactivo' login_form = Login_Form(request.POST) else: class_alert = 'alert alert-danger' message = 'El usuario o password introducido es incorrecto' login_form = Login_Form(request.POST) else: class_alert = 'alert alert-danger' message = 'Hay errores en el formulario' login_form = Login_Form(request.POST) # Caso en que el POST venga del formulario de Registro de nuevo usuario elif 'register' in request.POST: # Esto debe aparecer en el name del submit register_form = Registro_Usuario(request.POST) login_form = Login_Form() if register_form.is_valid(): username = register_form.cleaned_data['username'] email = register_form.cleaned_data['email'] password = register_form.cleaned_data['password'] password2 = register_form.cleaned_data['password2'] # Comprueba que el username no exista en la BD if register_form.check_username(username): # Comprueba que el email no exista en la BD if register_form.check_email(email): # Comprueba que los dos passwords introducidos coinciden if register_form.check_password(password, password2): # Crea el nuevo usuario user_model = User.objects.create( username=username, email=email, ) # Se le asigna el password user_model.set_password(password) user_model.save() # Intentamos determinar el País a partir de la IP para añadir el dato en la creación del Usuario pais, provincia = None, None if 'user_data' in request.session: user_data = request.session['user_data'] if 'country_code' in user_data: country_code = user_data['country_code'] if Pais.objects.filter( codigo_iso_alfa2__exact=country_code ): pais = Pais.objects.get( codigo_iso_alfa2=country_code) else: pais = None if 'region_name' in user_data: provincia_name = user_data['region_name'] provincia = Provincia.get_provincia_from_name( provincia_name) # Crea el objeto Usuario asociado al Usuario creado. n_usuario = Usuario.nuevo_usuario( user=user_model, raw_password=password, pais=pais, provincia=provincia, ) # Se envía el email con el link de Activación del Usuario # 1 - Se crea el Email de Registro de Usuario Email.enviar_correo_registro_usuario( n_usuario, request.get_host()) # Se define el mensaje a mostrar en la página # TODO: Definir mensaje a mostrar en el Index que indique al usuario que se ha creado la cuenta y que se ha enviado un mail para su validación # Realiza el login del usuario # login(request, user_model) # Se definen los parámetros a pasar en el template context = { 'login_form': Login_Form(), 'register_form': Registro_Usuario(), } # Se añade el mensaje de acción exitosa context['class_alert'] = 'alert alert-success' context[ 'message'] = 'Hemos enviado un email con un enlcace de confirmación a la dirección que nos ha indicado. Por favor, siga las instrucciones para poder validar su cuenta' # Se renderiza el template con la información correspondiente context.update(custom_context(request)) return render(request, 'usuarios/login.html', context) else: class_alert = 'alert alert-danger' message = 'Las contraseñas no coinciden' register_form = Registro_Usuario(request.POST) else: class_alert = 'alert alert-danger' message = 'Ya existe un usuario registrado con este E-Mail' register_form = Registro_Usuario(request.POST) else: class_alert = 'alert alert-danger' message = 'Ya existe un usuario registrado con este username(%s)' % ( username) register_form = Registro_Usuario(request.POST) else: class_alert = 'alert alert-danger' message = 'El formulario de registro contiene errores' register_form = Registro_Usuario(request.POST) else: print( 'Se ha recibido un POST que no viene ni de Login ni de Registro' ) class_alert = None message = None login_form = Login_Form() register_form = Registro_Usuario() else: class_alert = None message = None login_form = Login_Form() register_form = Registro_Usuario() # Se definen los parámetros a pasar en el template context = { 'login_form': login_form, 'register_form': register_form, } # Se añade un mensaje si es necesario if class_alert and message: context['class_alert'] = class_alert context['message'] = message # Se renderiza el template con la información correspondiente context.update(custom_context(request)) return render(request, 'usuarios/login.html', context)
def export_task(**kwargs): logger.info(kwargs) export_type = kwargs['export_type'] if export_type == 'export_general_email': tipo_receptor = kwargs['tipo_receptor'] empresa = kwargs['empresa'] user_email = kwargs['user_email'] file_name = kwargs['file_name'] date_from = kwargs['date_from'] date_to = kwargs['date_to'] date_from = int(date_from, base=10) date_to = int(date_to, base=10) date_from = timestamp_to_date(date_from) date_to = timestamp_to_date(date_to) params = dict() params['date_from'] = date_from params['date_to'] = date_to params['empresa'] = empresa params['tipo_receptor'] = tipo_receptor # Consulta data = Email.get_emails_by_dates_async(**params) elif export_type == 'export_sended_email': tipo_receptor = kwargs['tipo_receptor'] empresa = kwargs['empresa'] user_email = kwargs['user_email'] file_name = kwargs['file_name'] date_from = kwargs['date_from'] date_to = kwargs['date_to'] date_from = int(date_from, base=10) date_to = int(date_to, base=10) date_from = timestamp_to_date(date_from) date_to = timestamp_to_date(date_to) params = dict() params['date_from'] = date_from params['date_to'] = date_to params['empresa'] = empresa params['tipo_receptor'] = tipo_receptor # Consulta data = Email.get_sended_emails_by_dates_async(**params) elif export_type == 'export_failure_email': tipo_receptor = kwargs['tipo_receptor'] empresa = kwargs['empresa'] user_email = kwargs['user_email'] file_name = kwargs['file_name'] date_from = kwargs['date_from'] date_to = kwargs['date_to'] date_from = int(date_from, base=10) date_to = int(date_to, base=10) date_from = timestamp_to_date(date_from) date_to = timestamp_to_date(date_to) params = dict() params['date_from'] = date_from params['date_to'] = date_to params['empresa'] = empresa params['tipo_receptor'] = tipo_receptor # Consulta data = Email.get_failure_emails_by_dates_async(**params) elif export_type == 'export_dynamic_emails': user_email = kwargs['user_email'] empresa = kwargs['empresa'] file_name = kwargs['file_name'] params = kwargs['params'] params = json.loads(params) logger.info(params) data = Email.get_emails_by_dynamic_query_async(**params) if data is not None: try: logger.info("Existen datos para reporte") # Creación del documento report_file = create_tablib(data, empresa) logger.info("Se ha creado el archivo tablib.") # evaluacion del formato del archivo reporte report_file_format = get_report_file_format(empresa) logger.info("Se va a exportar archivo en formato %s", report_file_format) if report_file_format == 'xlsx': response_file = report_file.xlsx response_filename = file_name elif report_file_format == 'tsv': response_file = report_file.tsv response_filename = file_name else: response_file = report_file.csv response_filename = file_name # evaluar si el archivo es comprimido en zip general_conf = GeneralConfiguration.get_configuration(empresa) logger.info("Se obtiene configuración General de la Empresa") logger.info(general_conf.__dict__) if general_conf is not None and general_conf.report_file_zipped: logger.info("Intentando comprimir archivo reporte") # ejecutar proceso de comprimir reporte in_memory = StringIO() with ZipFile(in_memory, 'w') as archive: archive.writestr(response_filename, str(response_file), ZIP_DEFLATED) response_file = in_memory.getvalue() response_filename = file_name + '.zip' logger.info("Archivo comprimido exitosamente.") # Crear objeto para enviarlo por correo data = dict() data['name'] = response_filename data['report'] = response_file # preparación de parametros mail = EmailClient(empresa) mail.send_report_to_user_with_attach(user_email, data) logger.info("Reportes generado correctamente") except Exception as e: logger.error("Error al enviar correo reporte") logger.error(e) else: logger.info("No se crear el archivo reporte por consulta vacía.")
def hold(request): if request.method == "POST": # Grab all the data from POST requests subject = request.POST["email_subject"] unformatted_body = request.POST["email_body"] from_name = request.POST["email_from_name"] from_email = request.POST["email_from_email"].strip() # CSV IMPORTING to_name_list = [] to_email_list = [] if request.FILES != {}: csvfile = request.FILES['csv_file'] dialect = csv.Sniffer().sniff(codecs.EncodedFile(csvfile, "utf-8").read(1024)) csvfile.open() reader = csv.reader(codecs.EncodedFile(csvfile, "utf-8"), delimiter=',', dialect=dialect) for row in reader: to_name_list.append(row[0]) to_email_list.append(row[1].strip()) else: to_name_list = request.POST.getlist("email_recipients_name") to_email_list = request.POST.getlist("email_recipients_email") #TODO: QUICK HACKY FORM VALIDATION if subject == "" or unformatted_body == "" or from_name == "" or to_name_list[0] == "" or to_email_list[0] == "": return HttpResponseRedirect('/') # Format all the data and store into lists of correct emails formatted_to_email_list = [] holding_email_list = [] for i in range(len(to_name_list)): if to_name_list[i] == "" or to_email_list[i] == "": break body = unformatted_body.replace("[First]", getFirstName(to_name_list[i])) formatted_to_email_list.append(formatEmail(to_name_list[i], to_email_list[i].strip())); email = Email(from_name = from_name, from_email = from_email, to_name = to_name_list[i], to_email = to_email_list[i], subject = subject, body = body, uid = _createId(), sent = False) email.save() holding_email_list.append(email); #TODO: STOP Confirmation from happening if emails blank createConfirmationEmail(holding_email_list, from_name, from_email, formatted_to_email_list) return render_to_response('holding.html', {"count" : len(formatted_to_email_list), "to_emails" : formatted_to_email_list, "from" : getFirstName(from_name), "subject" : subject, "body" : unformatted_body}, context_instance=RequestContext(request)) return HttpResponseRedirect('/')
def transaccion_exitosa(request): # En esta vista recibimos la información del pago para proceder según corresponda. # Obtenemos el paymentID del diccionario GET del objeto request, para si está la información correcta, ejecutar el pago if 'paymentId' in request.GET and 'PayerID' in request.GET: paymentId = request.GET.get('paymentId') PayerID = request.GET.get('PayerID') # Se ejecuta el pago, pero antes verificamos que el mismo esté reflejado correctamente en nuestra BD # Lo anterior nos asegura que disponemos de la información necesaria del producto que se ha comprado if Pago.objects.filter(paypal_payment_id=paymentId): # Relacionamos el pago de Paypal que nos llega con el pago que debemos tener pendiente registrado en nuestra BD pago = Pago.objects.get(paypal_payment_id=paymentId) # Ahora se ejecuta el pago, para que se haga efectiva la transferencia del dinero executed_payment = pago.ejecutar_pago(PayerID) if executed_payment: # Luego que se ha ejecutado el pago, se debe actuar de una forma u otra en función de si el usuario que ha pagado # se encuentra logeado en el sistema o es un usuario anónimo # 1 - Escenario en que el usuario está logeado (autenticado) en el sistema # 1.1 - Se redirecciona a la vista de reserva confirmada sin mayores acciones payer = executed_payment['payer'] if request.user.is_authenticated: # Se comprueba si hay que completar algún dato del Usuario que no esté en el perfil y que se pueda tomar de Paypal usuario = Usuario.objects.get(user=request.user) usuario.completar_datos_from_Paypal(payer=payer) reservas = [pago.reserva] # 2 - El usuario que ha pagado es un usuario anónimo else: reservas = [] # Para la creación (o selección) del usuario que ha pagado, hacemos uso del diccionario "payer" que devuelve Paypal # Creamos el nuevo usuario o seleccionamos el que corresponda con la dirección de email aportada en el pago n_usuario = Usuario.nuevo_usuario_tras_pago_paypal( payer=payer) # Al tener ya un objeto Usuario, debemos pasar a BD todas las Reservas que hay en la session for reserva_dict in request.session['en_el_carro']: reservas.append( Reserva.crear_reserva_from_session( usuario=n_usuario, reserva_dict=reserva_dict, )) # Debemos pasar también a BD los registros de Favoritos if 'favoritos' in request.session: for favorito in request.session['favoritos']: Favorito.nuevo_favorito( servicio=Servicio.objects.get( id=int(favorito)), usuario=n_usuario, ) # Al terminar de procesar todas las reservas y Favoritos, se vacían dichos diccionarios de request.session if 'en_el_carro' in request.session: del request.session['en_el_carro'] request.session['en_el_carro'] = [] if 'favoritos' in request.session: del request.session['favoritos'] request.session['favoritos'] = [] # Se realiza el login del usuario login(request, n_usuario.user) # -- Independientemente del caso de autenticación, hechos todos los pasos anteriores, se prosigue con lo siguiente: # Se genera un pdf con la información de la reserva y se envía por mail al cliente # TODO: Sustituir por celery for reserva in reservas: Email.enviar_correo_reserva_alojamiento( host=request.get_host(), reserva_id=reserva.id) # Se genera un pdf con la información de la reserva y se envía por mail al proveedor # TODO: sustituir por celery Email.enviar_correo_reserva_alojamiento_proveedor( host=request.get_host(), reserva_id=reserva.id) # Realizados todos los cambios, se redirige a la vista de reserva confirmada return redirect('pagos:reserva_confirmada', pago_id=pago.id) else: return redirect('pagos:transaccion_error') else: return redirect('pagos:transaccion_error') else: return redirect('pagos:transaccion_error')