Example #1
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, self.from_address
            text_content = self.content

            msg = EmailMultiAlternatives(subject, text_content, from_email)

            if self.reply_to:
                msg.reply_to = [email.strip() for email in self.reply_to.split(',')
                                if email.strip()]

            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")

            msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()]
            msg.cc = [email.strip() for email in self.cc_address.split(',') if email.strip()]
            msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                path = attachment.file_attachment.path
                if os.path.isfile(path):
                    with open(path, 'rb') as f:
                        content = f.read()
                    msg.attach(attachment.original_filename, content, None)
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
 def sendMail(self, mailFrom='*****@*****.**', mailTo=None, mailCC=None, mailBCC=None, replyTo=None, subject=None, bodyHTML=None, bodyText=None):
     surpress = (EmailSuppression.objects.filter(suppression_date=date.today()).count() > 0)
     
     if surpress:
         log.warn("Surpressing e-mail")
         return
         
     if bodyText and bodyHTML:
         message = EmailMultiAlternatives()
         message.body = bodyText
         message.attach_alternative(transform(bodyHTML), "text/html")
         
     elif bodyText:
         message = EmailMessage()
         message.body = bodyText
         
     elif bodyHTML:
         message = EmailMessage()
         message.body = transform(bodyHTML)
         message.content_subtype = "html"
     else:
         raise TypeError("bodyHTML or bodyText must be set")
     
     if not (mailTo or mailCC or mailBCC):
         raise TypeError("Message must have at least one recipient")
     
     if subject:
         message.subject = subject
     
     
     overrideEmail = None
     
     #Try to get override email from settings
     try:
          overrideEmail = [settings.ENRICHMENT_OVERRIDE_EMAIL]
     except AttributeError:
         pass
     
     #Take presidence on the parameter
     if self.overrideEmail:
         overrideEmail = self.overrideEmail
     
     if not overrideEmail:
         if mailTo:
             message.to = list(mailTo)
 
         if mailCC:
             message.cc = list(mailCC)
 
         if mailBCC:
             message.bcc = list(mailBCC)
     else:
         message.to = overrideEmail
     
     if replyTo:
         message.reply_to = list(replyTo)
     
             
     message.from_email = mailFrom
     message.send()
Example #3
0
def send_mail(context,
              template_prefix,
              to=[],
              reply_to=None,
              subject=None,
              from_email=settings.DEFAULT_FROM_EMAIL):
    validated_to = []
    for m in to:
        if validateEmail(m):
            validated_to.append(m)
    to = validated_to
    if 'site' not in context.keys():
        context['site'] = Site.objects.get_current()
    template_prefix_dict = {'template_prefix': template_prefix}
    template_body = get_template('mails/%(template_prefix)s/body.txt' %
                                 template_prefix_dict)
    body = template_body.render(context)
    template_subject = get_template('mails/%(template_prefix)s/subject.txt' %
                                    template_prefix_dict)
    subject = subject or template_subject.render(context).replace(
        '\n', '').replace('\r', '')
    email = EmailMultiAlternatives(subject, body, from_email, to)
    try:
        template_body_html = get_template(
            'mails/%(template_prefix)s/body.html' % template_prefix_dict)
        html_content = template_body_html.render(context)
        email.attach_alternative(html_content, "text/html")
    except TemplateDoesNotExist:
        pass
    if reply_to is not None:
        email.reply_to = [reply_to]
    email.send()
def send_mail(context,
              template_prefix,
              to=[],
              reply_to=None,
              subject=None,
              from_email=settings.DEFAULT_FROM_EMAIL):
    validated_to = []
    for m in to:
        if validateEmail(m):
            validated_to.append(m)
    to = validated_to
    if 'site' not in context.keys():
        context['site'] = Site.objects.get_current()
    template_prefix_dict = {'template_prefix': template_prefix}
    template_body = get_template('mails/%(template_prefix)s/body.txt' % template_prefix_dict)
    body = template_body.render(context)
    template_subject = get_template('mails/%(template_prefix)s/subject.txt' % template_prefix_dict)
    subject = subject or template_subject.render(context).replace('\n', '').replace('\r', '')
    email = EmailMultiAlternatives(subject, body, from_email, to)
    try:
        template_body_html = get_template('mails/%(template_prefix)s/body.html' % template_prefix_dict)
        html_content = template_body_html.render(context)
        email.attach_alternative(html_content, "text/html")
    except TemplateDoesNotExist:
        pass
    if reply_to is not None:
        email.reply_to = [reply_to]
    email.send()
 def send_all(self):
     connection = get_connection()
     messages = []
     for subject, text, html, from_email, recipient in self.email_data:
         message = EmailMultiAlternatives(subject, text, from_email,
                                          recipient)
         message.attach_alternative(html, 'text/html')
         if settings.EMAIL_REPLY_TO:
             message.reply_to = (settings.EMAIL_REPLY_TO, )
         messages.append(message)
     self.stdout.write(f"Sending {len(messages)} emails")
     return connection.send_messages(messages)
Example #6
0
def handle_signoff_emails(instance, created, **kwargs):
    if not created:
        return

    message = EmailMultiAlternatives()

    # Collect recipients based on site settings
    if hasattr(settings, 'SIGNOFF_EMAIL_USER') and\
       settings.SIGNOFF_EMAIL_USER:
        message.to = [
            instance.user.email,
        ]

    if hasattr(settings, 'SIGNOFF_EMAIL_RECEIPT') and\
       settings.SIGNOFF_EMAIL_RECEIPT:
        if message.to:
            message.bcc = settings.SIGNOFF_EMAIL_RECEIPT
        else:
            message.to = settings.SIGNOFF_EMAIL_RECEIPT

    # If neither key is true, then we have no recipients, and therefore no mail
    # to send
    if not message.to:
        return

    if hasattr(settings, 'SIGNOFF_EMAIL_FROM') and\
       settings.SIGNOFF_EMAIL_FROM:
        message.from_email = settings.SIGNOFF_EMAIL_FROM

    if hasattr(settings, 'SIGNOFF_EMAIL_REPLY_TO') and\
       settings.SIGNOFF_EMAIL_REPLY_TO:
        message.reply_to = (settings.SIGNOFF_EMAIL_REPLY_TO, )

    # Build message
    template_context = {
        'document': instance.document,
        'user': instance.user,
        'instance': instance,
    }

    message.subject = render_to_string(
        'signoff/email_subject.txt',
        context=template_context,
    ).strip()

    html_body = render_to_string(
        'signoff/email_body.html',
        context=template_context,
    ).strip()

    message.body = html_body
    message.attach_alternative(html_body, 'text/html')
    message.send()
Example #7
0
    def send_email_html(self, template, context):
        html_content = render_to_string(template, context)
        text_content = strip_tags(html_content).strip()
        email = EmailMultiAlternatives()
        if self.email_subject:
            email.subject = self.email_subject
        if self.email_to:
            email.to = [x.strip() for x in self.email_to.split(',')]
        if self.email_cc:
            email.cc = [x.strip() for x in self.email_cc.split(',')]
        if self.email_bcc:
            email.bcc = [x.strip() for x in self.email_bcc.split(',')]
        if self.email_reply_to:
            email.reply_to = [
                x.strip() for x in self.email_reply_to.split(',')
            ]
        # if self.email_msg:
        #     email.body = msg

        email.body = html_content
        email.attach_alternative(text_content, 'text/plain')

        email.content_subtype = "html"
        email.mixed_subtype = 'related'

        fp = open('static/image/logo.png', 'rb')
        msg_img1 = MIMEImage(fp.read())
        fp.close()
        msg_img1.add_header('Content-ID', '<{}>'.format("logo.png"))
        email.attach(msg_img1)

        fp = open(context['order'].door_image.image.url.replace('/', '', 1),
                  'rb')
        msg_img2 = MIMEImage(fp.read())
        fp.close()
        msg_img2.add_header('Content-ID', '<{}>'.format("door.png"))
        email.attach(msg_img2)

        fp = open(context['order'].frame_image.image.url.replace('/', '', 1),
                  'rb')
        msg_img3 = MIMEImage(fp.read())
        fp.close()
        msg_img3.add_header('Content-ID', '<{}>'.format("frame.png"))
        email.attach(msg_img3)

        fp = open(context['order'].handle.image.url.replace('/', '', 1), 'rb')
        msg_img4 = MIMEImage(fp.read())
        fp.close()
        msg_img4.add_header('Content-ID', '<{}>'.format("handle.png"))
        email.attach(msg_img4)

        return email.send(fail_silently=True)
Example #8
0
 def __send_multipart(self):
     html_content = self.__render_template(self.config['templates']['html'])
     plain_content = self.__render_template(
         self.config['templates']['plain'])
     if html_content and plain_content:
         email = EmailMultiAlternatives(self.config['subject'],
                                        plain_content,
                                        self.config['from_email'],
                                        self.config['recipient'])
         if self.config['reply_to']:
             email.reply_to = self.config['reply_to']
         email.attach_alternative(html_content, 'text/html')
         return self.__deliver(email)
     return False
def send_ticket_update(tid: int, update_type: str, **kwargs):
    ticket = models.Ticket.objects.get(id=tid)

    models.TicketRevision(ticket=ticket,
                          user=None,
                          data=json.dumps({
                              "type": "message",
                              "msg_type": update_type,
                              "kwargs": kwargs
                          })).save()

    if update_type == "ready":
        context = {
            "content":
            "Your repair is complete and your device is ready to collect at your earliest convenience",
            "ticket": ticket
        }
        html_email = render_to_string("emails/ticket_update.html", context)
        plain_email = render_to_string("emails/ticket_update_plain.html",
                                       context)
        text_message = f"Your We Will Fix Your PC repair (ticket #{ticket.id}) of a {ticket.equipment.name.lower()} " \
                       f"is complete and your device is ready to collect at your earliest convenience"
    elif update_type == "custom":
        context = {"content": kwargs.get("update_text", ""), "ticket": ticket}
        html_email = render_to_string("emails/ticket_update.html", context)
        plain_email = render_to_string("emails/ticket_update_plain.html",
                                       context)
        text_message = f"An update on your We Will Fix Your PC (ticket #{ticket.id}) repair of a " \
                       f"{ticket.equipment.name.lower()}: {kwargs.get('update_text', '')}"
    else:
        return

    customer = ticket.get_customer()

    if customer.get("email"):
        mail = EmailMultiAlternatives(
            'An update on your We Will Fix Your PC repair', plain_email,
            'We Will Fix Your PC <*****@*****.**>',
            [customer.get("email")])
        mail.reply_to = ["We Will Fix Your PC <*****@*****.**>"]
        mail.attach_alternative(html_email, 'text/html')
        mail.send()

    requests.post(
        f"{settings.CUSTOMER_SUPPORT_URL}api/send_message/{customer.get('id')}/",
        headers={
            "Authorization":
            f"Bearer {django_keycloak_auth.clients.get_access_token()}"
        },
        json={"text": text_message})
Example #10
0
def send_email_body(email_address: str,
                    subject: str,
                    text_content: str,
                    html_content: str = None) -> int:
    msg = EmailMultiAlternatives(
        from_email=settings.DEFAULT_FROM_EMAIL,
        subject=subject,
        body=text_content,
        to=[email_address],
    )
    if settings.DEFAULT_REPLYTO_EMAIL:
        msg.reply_to = [settings.DEFAULT_REPLYTO_EMAIL]
    if html_content:
        msg.attach_alternative(html_content, "text/html")
    return msg.send()
Example #11
0
    def create_message(self, message):
        """
        Creates email message from a message dictionary

        :param message: The message dictionary
        :return: A email message object
        """
        msg = EmailMultiAlternatives(message["subject"], message["text"], message["from"], [message["to"]])
        if "reply_to" in message:
            msg.reply_to = message["reply_to"]

        # Attach files if any
        if "attachments" in message:
            for filename, file, filetype in message["attachments"]:
                msg.attach(filename, file, filetype)

        return msg
Example #12
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, self.from_address
            text_content = self.content

            msg = EmailMultiAlternatives(subject, text_content, from_email)

            if self.reply_to:
                msg.reply_to = [
                    email.strip() for email in self.reply_to.split(',')
                    if email.strip()
                ]

            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")

            msg.to = [
                email.strip() for email in self.to_address.split(',')
                if email.strip()
            ]
            msg.cc = [
                email.strip() for email in self.cc_address.split(',')
                if email.strip()
            ]
            msg.bcc = [
                email.strip() for email in self.bcc_address.split(',')
                if email.strip()
            ]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                path = attachment.file_attachment.path
                if os.path.isfile(path):
                    with open(path, 'rb') as f:
                        content = f.read()
                    msg.attach(attachment.original_filename, content, None)
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
Example #13
0
def send_email_with_logo(subject, text, to_address, from_address, html=None):
    if html is not None:
        msg = EmailMultiAlternatives(subject, text, from_address, to_address)
        msg.attach_alternative(html, "text/html")
    else:
        msg = EmailMessage(subject, text, from_address, to_address)
    msg.reply_to = [from_address]
    if html is not None and html.find(
            "470d34c254ed$74sfr210$0400a8c0@stal") > 0:
        image = get_config("EMAIL_LOGO", None)
        if image is not None and os.path.exists(image):
            img = MIMEImage(open(image, "rb").read())
            img.add_header("Content-ID",
                           "<470d34c254ed$74sfr210$0400a8c0@stal>")
            img.add_header("Content-Disposition", "inline")
            msg.attach(img)
    try:
        msg.send(fail_silently=False)
    except Exception:
        time.sleep(1)
        msg.send(fail_silently=False)
    return True
Example #14
0
def email(subject,
          template_name,
          merge_data={},
          merge_global_data={},
          recipients=[],
          preheader=None,
          bcc=None,
          reply_to=None,
          send=True):

    from django.conf import settings

    if not (subject and template_name and recipients):
        raise NameError()

    if not isinstance(recipients, list):
        raise TypeError("recipients must be a list")

    # bcc is set to False by default.
    # make sure bcc is in a list form when sent over
    if bcc not in [False, None] and not isinstance(bcc, list):
        raise TypeError("recipients must be a list")

    merge_global_data['subject'] = subject
    merge_global_data['current_year'] = timezone.now().year
    merge_global_data['company_name'] = settings.SITE_NAME
    merge_global_data['site_url'] = settings.SITE_URL

    if preheader:
        merge_global_data['preheader'] = preheader

    msg = EmailMultiAlternatives()
    msg.body = render_to_string(f"{template_name}.html")
    msg.content_subtype = "html"
    msg.from_email = f"CoderDojoChi<{settings.DEFAULT_FROM_EMAIL}>"
    msg.merge_data = merge_data
    msg.merge_global_data = merge_global_data
    msg.subject = subject
    msg.to = recipients

    if reply_to:
        msg.reply_to = reply_to

    if send:
        try:
            msg.send()
        except Exception as e:
            logger.error(e)
            logger.error(msg)
            raise e

        for recipient in msg.anymail_status.recipients.keys():
            send_attempt = msg.anymail_status.recipients[recipient]
            if send_attempt.status not in ['queued', 'sent']:
                logger.error(f"user: {recipient}, {timezone.now()}")

                from coderdojochi.models import CDCUser
                user = CDCUser.objects.get(email=recipient)
                user.is_active = False
                user.admin_notes = f"User '{send_attempt.reject_reason}' when checked on {timezone.now()}"
                user.save()

    return msg
Example #15
0
def email(
    subject,
    template_name,
    context,
    recipients,
    preheader=None,
    bcc=None,
    reply_to=None,
    send=True
):

    from django.conf import settings

    if not (subject and template_name and context and recipients):
        raise NameError()

    if not isinstance(recipients, list):
        raise TypeError("recipients must be a list")

    # bcc is set to False by default.
    # make sure bcc is in a list form when sent over
    if bcc not in [False, None] and not isinstance(bcc, list):
        raise TypeError("recipients must be a list")

    context['subject'] = subject
    context['current_year'] = timezone.now().year
    context['company_name'] = settings.SITE_NAME
    context['site_url'] = settings.SITE_URL

    if preheader:
        context['preheader'] = preheader

    html_content = render_to_string('{}.html'.format(template_name), context)
    text_content = render_to_string('{}.txt'.format(template_name), context)
    msg = EmailMultiAlternatives(
        subject=subject,
        body=text_content,
        from_email=u'CoderDojoChi<{}>'.format(
            settings.DEFAULT_FROM_EMAIL
        ),
        to=recipients
    )

    if reply_to:
        msg.reply_to = reply_to

    msg.inline_css = True
    msg.attach_alternative(html_content, "text/html")

    if send:
        try:
            msg.send()
        except Exception as e:
            response = msg.mandrill_response[0]
            logger.error(
                u'{}'.format(response)
            )

            reject_reasons = [
                'hard-bounce',
                'soft-bounce',
                'spam',
                'unsub',
                'custom',
            ]

            if (
                response['status'] == u'rejected' and
                response['reject_reason'] in reject_reasons
            ):
                logger.error(
                    'user: {}, {}'.format(
                        response['email'],
                        timezone.now()
                    )
                )

                from coderdojochi.models import CDCUser
                user = CDCUser.objects.get(email=response['email'])
                user.is_active = False
                user.admin_notes = u'User \'{}\' when checked on {}'.format(
                    response['reject_reason'],
                    timezone.now()
                )
                user.save()
            else:
                raise e

    return msg
Example #16
0
    def enviar_cotizacion(self, cotizacion, user, email_adicional=None):
        version_cotizacion = cotizacion.version

        from_ventas_email = EmailConfiguration.objects.first(
        ).email_ventas_from
        if not from_ventas_email:
            from_ventas_email = settings.DEFAULT_FROM_EMAIL

        enviar_como = user.user_extendido.email_envio_como
        if enviar_como:
            enviar_como = '%s - %s' % (user.user_extendido.email_envio_como,
                                       user.get_full_name())
        else:
            enviar_como = 'ODECOPACK - %s' % (user.get_full_name())

        if user.email:
            email_split = user.email.split('@')
            if email_split[-1] in list(
                    DominiosEmail.objects.values_list('dominio',
                                                      flat=True).all()):
                from_email = "%s <%s>" % (enviar_como, user.email)
            else:
                from_email = "%s <%s>" % (enviar_como, from_ventas_email)
        else:
            from_email = "%s <%s>" % (enviar_como, from_ventas_email)
        if email_adicional:
            to = [cotizacion.email, email_adicional]
        else:
            to = [cotizacion.email]
        subject = "%s - %s" % ('Cotizacion', cotizacion.nro_cotizacion)
        if version_cotizacion > 1:
            subject = "%s, version %s" % (subject, cotizacion.version)

        ctx = {
            'object': cotizacion,
        }

        try:
            colaborador = Colaborador.objects.get(usuario__user=user)
        except Colaborador.DoesNotExist:
            colaborador = None

        if not cotizacion.cliente_nuevo:
            colaboradores = SucursalBiable.objects.values(
                'vendedor_real__colaborador_id').filter(
                    cliente_id=cotizacion.cliente_biable_id,
                    vendedor_real__isnull=False).distinct()
            if colaboradores.exists():
                if colaboradores.count() == 1:
                    colaborador = Colaborador.objects.get(
                        pk=colaboradores.first()
                        ['vendedor_real__colaborador_id'])
                    cotizacion.usuario = colaborador.usuario.user

                    cotizacion.save()
            else:
                colaborador = Colaborador.objects.get(usuario__user=user)

        if colaborador:
            if colaborador.foto_perfil:
                url_avatar = colaborador.foto_perfil.url
                ctx['avatar'] = url_avatar

        nombre_archivo_cotizacion = "Cotizacion Odecopack - CB %s.pdf" % (
            cotizacion.id)
        if version_cotizacion > 1:
            ctx['version'] = cotizacion.version
            nombre_archivo_cotizacion = "Cotizacion Odecopack - CB %s ver %s.pdf" % (
                cotizacion.id, cotizacion.version)

        text_content = render_to_string('cotizaciones/emails/cotizacion.html',
                                        ctx)

        html_content = get_template(
            'cotizaciones/emails/cotizacion.html').render(Context(ctx))

        output = BytesIO()
        HTML(string=html_content).write_pdf(target=output)
        msg = EmailMultiAlternatives(subject,
                                     text_content,
                                     from_email,
                                     to=to,
                                     reply_to=[user.email])
        msg.attach_alternative(html_content, "text/html")

        msg.attach(nombre_archivo_cotizacion, output.getvalue(),
                   'application/pdf')

        if cotizacion.mis_imagenes:
            for imagen in cotizacion.mis_imagenes.all():
                try:
                    docfile = imagen.imagen.read()
                    if docfile:
                        nombre_archivo = imagen.imagen.name.split("/")[-1]
                        msg.attach(nombre_archivo, docfile)
                        docfile.close()
                    else:
                        pass
                except:
                    pass

        msg.send()

        # Envio al asesor
        msg.from_email = "Confirmación <*****@*****.**>"
        msg.to = [user.email]
        msg.reply_to = None
        msg.send()

        output.close()
        cotizacion.save()

        if not cotizacion.cliente_nuevo:
            seguimiento = SeguimientoComercialCliente()
            seguimiento.cotizacion = cotizacion
            seguimiento.creado_por = self.request.user
            seguimiento.cliente = cotizacion.cliente_biable

            observacion_adicional = "<p> Valor Cotización: " + str(
                cotizacion.total) + "</p>"
            if cotizacion.descuento:
                observacion_adicional += "<p> Descuento Cotización: " + str(
                    cotizacion.descuento) + "</p>"

            seguimiento.observacion_adicional = observacion_adicional
            if version_cotizacion > 1:
                seguimiento.tipo_accion = "Envío version " + str(
                    version_cotizacion)
            else:
                seguimiento.tipo_accion = "Nueva"
            seguimiento.save()
Example #17
0
def email(subject,
          template_name,
          context,
          recipients,
          preheader=None,
          bcc=None,
          reply_to=None,
          send=True):

    from django.conf import settings

    if not (subject and template_name and context and recipients):
        raise NameError()

    if not isinstance(recipients, list):
        raise TypeError("recipients must be a list")

    # bcc is set to False by default.
    # make sure bcc is in a list form when sent over
    if bcc not in [False, None] and not isinstance(bcc, list):
        raise TypeError("recipients must be a list")

    context['subject'] = subject
    context['current_year'] = timezone.now().year
    context['company_name'] = settings.SITE_NAME
    context['site_url'] = settings.SITE_URL

    if preheader:
        context['preheader'] = preheader

    html_content = render_to_string('{}.html'.format(template_name), context)
    text_content = render_to_string('{}.txt'.format(template_name), context)
    msg = EmailMultiAlternatives(subject=subject,
                                 body=text_content,
                                 from_email=u'CoderDojoChi<{}>'.format(
                                     settings.DEFAULT_FROM_EMAIL),
                                 to=recipients)

    if reply_to:
        msg.reply_to = reply_to

    msg.inline_css = True
    msg.attach_alternative(html_content, "text/html")

    if send:
        try:
            msg.send()
        except Exception as e:
            response = msg.mandrill_response[0]
            logger.error(u'{}'.format(response))

            reject_reasons = [
                'hard-bounce',
                'soft-bounce',
                'spam',
                'unsub',
                'custom',
            ]

            if (response['status'] == u'rejected'
                    and response['reject_reason'] in reject_reasons):
                logger.error('user: {}, {}'.format(response['email'],
                                                   timezone.now()))

                from coderdojochi.models import CDCUser
                user = CDCUser.objects.get(email=response['email'])
                user.is_active = False
                user.admin_notes = u'User \'{}\' when checked on {}'.format(
                    response['reject_reason'], timezone.now())
                user.save()
            else:
                raise e

    return msg