def sent(self, order=None, user=None, coupon=None, to_email=None): """ Отправить Email's. Создается ХТМЛ Шаблон. С заполненными параметрами (если нужно)""" from utils.mail import send_html_email from des.models import DynamicEmailConfiguration des_config = DynamicEmailConfiguration.get_solo() html = self.make_html(order=order, user=user, coupon=coupon) from_email = des_config.from_email # если передан емалй получателья - используется он # иначе выполняется ряд условий if not to_email: to_email = user.email if user else self.to_email if self.is_admin: to_email = from_email elif not to_email: to_email = order.email_sender sent = SentLetter(html_template=self, order=order, user=user, coupon=coupon, html=html) if send_html_email(to_email=to_email, from_email=from_email, subject=self.subject, html=html): sent.is_sent = True return sent.save()
def send_test_email(request): if request.user is None or not request.user.is_staff: return HttpResponseNotFound() email = request.POST.get('email', None) config = DynamicEmailConfiguration.get_solo() if email: try: send_mail( subject, message_text, config.from_email or None, [email], html_message = message_html) messages.success(request, _("Test email sent. Please check \"{}\" for a " "message with the subject \"{}\"").format( email, subject ) ) except Exception as e: messages.error(request, _("Could not send email. {}").format(e)) else: messages.error(request, _("You must provide an email address to test with.")) return HttpResponseRedirect(get_configuration_admin_url())
def envia_email_unico(assunto: str, corpo: str, email: str, html: str = None): config = DynamicEmailConfiguration.get_solo() return send_mail(assunto, corpo, config.from_email or None, [email], html_message=html)
def test_sender_is_in_bcc(self): email = 'new_from_email@test_mail.com' config = DynamicEmailConfiguration.get_solo() config.from_email = email config.save() self.sender.send() self.assertIn(config.from_email, mail.outbox[0].bcc)
def __init__(self, host=None, port=None, username=None, password=None, use_tls=None, fail_silently=None, use_ssl=None, timeout=None, ssl_keyfile=None, ssl_certfile=None, **kwargs): from des.models import DynamicEmailConfiguration configuration = DynamicEmailConfiguration.get_solo() super(ConfiguredEmailBackend, self).__init__( host=configuration.host if host is None else host, port=configuration.port if port is None else port, username=configuration.username if username is None else username, password=configuration.password if password is None else password, use_tls=configuration.use_tls if use_tls is None else use_tls, fail_silently=configuration.fail_silently if fail_silently is None else fail_silently, use_ssl=configuration.use_ssl if use_ssl is None else use_ssl, timeout=configuration.timeout if timeout is None else timeout, ssl_keyfile= ssl_keyfile, # TODO: configuration.ssl_keyfile if ssl_keyfile is not None else ssl_keyfile, ssl_certfile= ssl_certfile, # TODO: configuration.ssl_certfile if ssl_certfile is not None else ssl_certfile, **kwargs)
def test_from_email_is_read_from_des(self): email = 'new_from_email@test_mail.com' config = DynamicEmailConfiguration.get_solo() config.from_email = email config.save() self.sender.send() self.assertEqual(mail.outbox[0].from_email, config.from_email)
def enviar_email_mp(assunto, mensagem, csv): try: config = DynamicEmailConfiguration.get_solo() email_mp = EmailMercadoPago.objects.first() email_novo = None email_ja_enviado = LogEmailMercadoPago.objects.filter( enviar_para=email_mp.email, assunto=assunto, enviado=False, csv=csv) if not email_ja_enviado: email_novo = LogEmailMercadoPago.objects.create( enviar_para=email_mp.email, assunto=assunto, mensagem=mensagem, csv=csv) msg = EmailMessage(subject=assunto, body=mensagem, from_email=config.from_email or None, bcc=(email_mp.email, ), connection=EmailBackend(**config.__dict__)) msg.send() if email_ja_enviado.exists(): email_ja_enviado.update(enviado=True) elif email_novo: email_novo.enviado = True email_novo.save() except Exception as err: logger.error(str(err))
def setUpTestData(cls): # set mock env settings.ENV_TYPE = 'tst' config = DynamicEmailConfiguration.get_solo() config.from_email = '*****@*****.**' config.save() # set mock nodes cls.node1 = Node.objects.create( catalog_id='id1', catalog_url=cls.get_sample('several_assorted_errors.json'), indexable=True) cls.node2 = Node.objects.create( catalog_id='id2', catalog_url=cls.get_sample('full_data.json'), indexable=True) cls.node1.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.node2.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.report_task = ValidationReportTask.objects.create() cls.validation_report_generator = ValidationReportGenerator( cls.report_task) catalog = DataJson(cls.get_sample('several_assorted_errors.json')) cls.report = catalog.validate_catalog(only_errors=True)
def ready(self): if 'runserver' in sys.argv: from des.models import DynamicEmailConfiguration c = DynamicEmailConfiguration.get_solo() if settings.DEFAULT_FROM_EMAIL == global_settings.DEFAULT_FROM_EMAIL: settings.DEFAULT_FROM_EMAIL = c.from_email
def setUpTestData(cls): # set mock env settings.ENV_TYPE = 'tst' config = DynamicEmailConfiguration.get_solo() config.from_email = '*****@*****.**' config.save() # set mock task cls.indicators_task = IndicatorsGenerationTask.objects.create(finished=timezone.now(), logs='test task logs') cls.indicators_task.status = IndicatorsGenerationTask.FINISHED cls.indicators_task.save() # set mock user User.objects.create(username='******', password='******', email='*****@*****.**', is_staff=True) # set mock nodes cls.node1 = Node.objects.create(catalog_id='id1', catalog_url='url', indexable=True) cls.node2 = Node.objects.create(catalog_id='id2', catalog_url='url', indexable=True) cls.node1.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.node2.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.harvest_node = HarvestingNode.objects.create(catalog_id='harvest_id', name='harvest node', url='http://datos.test.ar', apikey='apikey', enabled=True) central_node = CentralNode.get_solo() central_node.node = cls.harvest_node central_node.save() cls.report_task = ReportGenerationTask.objects.create() # set mock indicators type_a = IndicatorType.objects.create(nombre='ind_a', tipo='RED') type_b = IndicatorType.objects.create(nombre='ind_b', tipo='RED') type_c = IndicatorType.objects.create(nombre='ind_c', tipo='RED', resumen=True) type_d = IndicatorType.objects.create(nombre='ind_d', tipo='RED', resumen=True, mostrar=False) type_e = IndicatorType.objects.create(nombre='ind_e', tipo='RED', mostrar=False) types = [type_a, type_b, type_c, type_d, type_e] values = ['42', '[["d1", "l1"], ["d2", "l2"]]', '{"k1": 1, "k2": 2}', '100', '1'] for t, v in zip(types, values): IndicadorRed.objects.create(indicador_tipo=t, indicador_valor=v) values = ['23', '[["d1", "l1"]]', '{"k2": 1}', '500', '2'] for t, v in zip(types, values): Indicador.objects.create(indicador_tipo=t, indicador_valor=v, jurisdiccion_id='id1', jurisdiccion_nombre='nodo1') values = ['19', '[["d2", "l2"]]', '{"k1": 1, "k2": 1}', '50', '2'] for t, v in zip(types, values): Indicador.objects.create(indicador_tipo=t, indicador_valor=v, jurisdiccion_id='id2', jurisdiccion_nombre='nodo2') values = ['23', '[["d2", "l2"]]', '{"k2": 1}', '2', '3'] for t, v in zip(types, values): IndicadorFederador.objects.create(indicador_tipo=t, indicador_valor=v, jurisdiccion_id='harvest_id', jurisdiccion_nombre='harvest node') cls.indicators_report_generator = IndicatorReportGenerator(cls.indicators_task, cls.report_task)
def enviar_email(assunto, mensagem, enviar_para): try: config = DynamicEmailConfiguration.get_solo() send_mail(subject=assunto, message=mensagem, from_email=config.from_email or None, recipient_list=[enviar_para]) logger.info(f'Email enviado para {enviar_para}. Assunto:{assunto}.') except Exception as err: logger.error(str(err))
def send_email(subject, body, to): config = DynamicEmailConfiguration.get_solo() try: dj_send_email(subject, body, config.from_email or settings.DEFAULT_FROM_EMAIL, to, html_message=body) except Exception as e: logger.error("Could not send email. {}".format(e))
def envia_email_em_massa(assunto: str, corpo: str, emails: list, template: str, dados_template: Any, html=None): config = DynamicEmailConfiguration.get_solo() from_email = config.from_email with get_connection() as connection: messages = [] for email in remove_emails_dev(emails): message = EmailMultiAlternatives(assunto, corpo, from_email, [email]) if html: message.attach_alternative(html, 'text/html') messages.append(message) return connection.send_messages(messages)
def send_email(self, mail, node=None): target = node.catalog_id if node else 'Red' mail.to = self._get_recipients(node=node) mail.connection = self.connection mail.from_email = DynamicEmailConfiguration.get_solo().from_email try: mail.send() msg = "Reporte de {} enviado exitosamente".format(target) except SMTPException as e: msg = "Error enviando reporte de {}:\n {}".format(target, str(e)) self.report_task.info(self.report_task, msg)
def envia_email_unico_com_anexo_inmemory(assunto: str, corpo: str, email: str, anexo_nome: str, mimetypes: str, anexo=[]): # noqa E501 # Rever a obrigatoriedade de anexo_nome e mimetypes para implementações futuras, ou generalização. config = DynamicEmailConfiguration.get_solo() email = EmailMessage( assunto, corpo, config.from_email or None, [email] ) email.content_subtype = 'html' email.attach(anexo_nome, anexo, mimetypes) email.send()
def send(self): emails = self.admins.get_emails() config = DynamicEmailConfiguration.get_solo() mail = EmailMultiAlternatives(self.subject, self.body, from_email=config.from_email, to=emails) mail.attach_alternative(self.body, 'text/html') for attachment_args in self.attachments: mail.attach(*attachment_args) mail.send()
def send_email(result: list, task: IntegrationTestTask): subject = u'[{}] API Series de Tiempo: Test de integración'.format(settings.ENV_TYPE) emails = IntegrationTestConfig.get_solo().recipients.values_list('email', flat=True) if not emails: task.log("No hay usuarios registrados para recibir los reportes del test. Mail no enviado.") return msg = "Errores en los datos de las series detectados. Ver el archivo adjunto" config = DynamicEmailConfiguration.get_solo() mail = EmailMultiAlternatives(subject, msg, from_email=config.from_email, to=emails) mail.attach('errors.csv', generate_errors_csv(result), 'text/csv') sent = mail.send() if not sent: task.log("Error mandando el reporte")
def enviar_email_html(assunto, template, context, enviar_para): logger.info('Enviando email para %s', enviar_para) try: config = DynamicEmailConfiguration.get_solo() conteudo = render_to_string(template_name=f'email/{template}', context=context) logger.info(config.from_email) email = EmailMessage(subject=assunto, body=conteudo, from_email=config.from_email or None, bcc=(enviar_para, ), connection=EmailBackend(**config.__dict__)) email.content_subtype = 'html' email.send() except Exception as err: logger.info("Erro email: %s", str(err))
def enviar_email_html(assunto, template, data, enviar_para): try: config = DynamicEmailConfiguration.get_solo() msg_html = render_to_string(f"email/{template}.html", data) msg = EmailMessage( subject=assunto, body=msg_html, from_email=config.from_email or None, bcc=(enviar_para,), ) msg.content_subtype = "html" # Main content is now text/html msg.send() except Exception as err: logger.error(str(err))
def envia_email_unico_com_anexo(assunto: str, corpo: str, email: str, anexo=[]): # noqa B006 # Anexa um arquivo no email. # Usado em enviar_email_para_diretor_da_escola_destino. config = DynamicEmailConfiguration.get_solo() email = EmailMessage( assunto, corpo, config.from_email or None, [email] ) email.content_subtype = 'html' _mimetypes, _ = guess_type(anexo.name) # Este anexo vem da pasta media. nome_anexo = anexo.name.split('/')[-1] nome_anexo = nome_anexo.replace('_auto', '') email.attach(nome_anexo, anexo.read(), _mimetypes) email.send()
def enviar_email_html(assunto, template, contexto, enviar_para, html_salvo=None, lista_emails=None): try: config = DynamicEmailConfiguration.get_solo() msg_html = html_salvo or render_to_string(f"email/{template}.html", contexto) email_sme = None emails_sme = Email.objects.filter(enviar_para=enviar_para, assunto=assunto, enviado=False) if not emails_sme: email_sme = Email.objects.create(enviar_para=enviar_para, assunto=assunto, body=msg_html) emails = lista_emails or ListaEmail.objects.all() if emails: if lista_emails: email_utilizado = emails[contexto.get('id') % len(emails)]['email'] else: email_utilizado = emails[contexto.get('id') % len(emails)].email config.from_email = email_utilizado config.username = email_utilizado msg = EmailMessage(subject=assunto, body=msg_html, from_email=config.from_email or None, bcc=(enviar_para, ), connection=EmailBackend(**config.__dict__)) msg.content_subtype = "html" # Main content is now text/html msg.send() if emails_sme.exists(): emails_sme.update(enviado=True) elif email_sme: email_sme.enviado = True email_sme.save() except Exception as err: logger.error(str(err))
def enviar_email(assunto, mensagem, enviar_para): try: config = DynamicEmailConfiguration.get_solo() email_sme = None emails_sme = Email.objects.filter(enviar_para=enviar_para, assunto=assunto, enviado=False) if not emails_sme: email_sme = Email.objects.create(enviar_para=enviar_para, assunto=assunto, body=mensagem) send_mail(subject=assunto, message=mensagem, from_email=config.from_email or None, recipient_list=[enviar_para]) if emails_sme.exists(): emails_sme.update(enviado=True) elif email_sme: email_sme.enviado = True email_sme.save() except Exception as err: logger.error(str(err))
def send_test_email(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) to_email = body.get('to_email') config = DynamicEmailConfiguration.get_solo() response = {} if to_email: try: send_mail( subject, message_text, config.from_email or None, [to_email], html_message=message_html) response['detail'] = _('Test email sent. Please check \'{}\' for a ' # noqa Q003 'message with the subject \'{}\'').format( # noqa Q003 to_email, subject) except Exception as e: response['error'] = _(f'Could not send email. {e}') else: response['error'] = _('You must provide an email address to test with.') return HttpResponse(json.dumps(response))
def setUpTestData(cls): # set mock env settings.ENV_TYPE = 'tst' config = DynamicEmailConfiguration.get_solo() config.from_email = '*****@*****.**' config.save() # set mock nodes cls.node1 = Node.objects.create(catalog_id='id1', catalog_url='url', indexable=True) cls.node2 = Node.objects.create(catalog_id='id2', catalog_url='url', indexable=True) cls.node3 = Node.objects.create(catalog_id='id3', catalog_url='url', indexable=True) cls.node4 = Node.objects.create(catalog_id='id4', catalog_url='url', indexable=True) cls.node5 = Node.objects.create(catalog_id='id5', catalog_url='url', indexable=True) cls.node6 = Node.objects.create(catalog_id='id6', catalog_url='url', indexable=True) cls.node1.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.node2.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.node3.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.node4.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.node5.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.node6.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) # set mock user User.objects.create(username='******', password='******', email='*****@*****.**', is_staff=True) cls.catalog1 = Catalog.objects.create(title='id1', identifier='id1') cls.catalog2 = Catalog.objects.create(title='id2', identifier='id2') cls.catalog3 = Catalog.objects.create(title='id3', identifier='id3') cls.catalog4 = Catalog.objects.create(title='id4', identifier='id4') cls.catalog5 = Catalog.objects.create(title='id5', identifier='id5') cls.catalog6 = Catalog.objects.create(title='id6', identifier='id6') cls.dataset1 = Dataset.objects.create(identifier='dataset1', metadata='{}', catalog=cls.catalog1, indexable=True, present=True, updated=True) cls.dataset2 = Dataset.objects.create(identifier='dataset2', metadata='{}', catalog=cls.catalog2, indexable=True, present=False, updated=True) cls.dataset3 = Dataset.objects.create(identifier='dataset3', metadata='{}', catalog=cls.catalog3, indexable=True, present=True, updated=True) cls.dataset4 = Dataset.objects.create(identifier='dataset4', metadata='{}', catalog=cls.catalog4, indexable=True, present=False, updated=True) cls.dataset5 = Dataset.objects.create(identifier='dataset5', metadata='{}', catalog=cls.catalog5, indexable=True, present=True, updated=True) cls.dataset6 = Dataset.objects.create(identifier='dataset6', metadata='{}', catalog=cls.catalog6, indexable=True, present=False, updated=True) # set mock dataset present record DatasetPresentRecord.objects.create(dataset_id=cls.dataset1.id, present_record=True) DatasetPresentRecord.objects.create(dataset_id=cls.dataset2.id, present_record=False) DatasetPresentRecord.objects.create(dataset_id=cls.dataset3.id, present_record=False) DatasetPresentRecord.objects.create(dataset_id=cls.dataset4.id, present_record=True) cls.not_present_report_task = NotPresentReportGenerationTask.objects.create() cls.not_present_report_generator = NotPresentReportGenerator(cls.not_present_report_task)
def setUpTestData(cls): # set mock env settings.ENV_TYPE = 'tst' config = DynamicEmailConfiguration.get_solo() config.from_email = '*****@*****.**' config.save() # set mock task cls.newly_report_task = NewlyReportGenerationTask.objects.create( finished=cls.LAST_REPORT_DATE, logs='test task logs') cls.newly_report_task.status = NewlyReportGenerationTask.FINISHED cls.newly_report_task.save() # set mock nodes cls.node1 = Node.objects.create(catalog_id='id1', catalog_url='url', indexable=True) cls.node2 = Node.objects.create(catalog_id='id2', catalog_url='url', indexable=True) cls.node3 = Node.objects.create(catalog_id='id3', catalog_url='url', indexable=True) cls.node1.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.node2.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) cls.node3.admins.create(username='******', password='******', email='*****@*****.**', is_staff=False) # set mock user User.objects.create(username='******', password='******', email='*****@*****.**', is_staff=True) cls.catalog1 = Catalog.objects.create(title='id1', identifier='id1') cls.catalog2 = Catalog.objects.create(title='id2', identifier='id2') cls.catalog3 = Catalog.objects.create(title='id3', identifier='id3') cls.dataset1 = Dataset.objects.create(identifier='dataset1', metadata='{}', catalog=cls.catalog1, indexable=True, present=True, updated=True) cls.dataset2 = Dataset.objects.create(identifier='dataset2', metadata='{}', catalog=cls.catalog2, indexable=True, present=True, updated=True) old_date = timezone.datetime(2000, 10, 10, 10, tzinfo=timezone.utc) with suppress_autotime(Dataset, 'time_created'): cls.dataset3 = Dataset.objects.create(identifier='dataset3', metadata='{}', catalog=cls.catalog3, time_created=old_date, indexable=True, present=True, updated=True) cls.report_task = NewlyReportGenerationTask.objects.create() cls.newly_report_generator = NewlyDatasetReportGenerator( cls.report_task, cls.LAST_REPORT_DATE)