Example #1
0
def email_results(batch, failures, runs):
    long_runners = UnitTestRunResult.objects.filter(test_run__in=runs).order_by('-runtime')[:5]
    long_runners.select_related()
    long_runner_classes = UnitTestRun.objects.filter(batch=batch).order_by('-runtime')[:5]
    long_runner_classes.select_related()

    try:
        schedule = UnitTestSchedule.objects.get(branch=batch.branch)
    except ObjectDoesNotExist:
        logger.error(
                'No Schedule exists for this branch (' + batch.branch.name + '), so no way to figure out who to email')
        return

    email_host = ConfigCache.get_config_value('email.host')
    conn = mail.get_connection(host=email_host)

    from_address = ConfigCache.get_config_value('email.from')

    if schedule.email_only_failures and len(failures) == 0:
        return

    template = get_template('unit_test_results_email.html')
    c = Context({'batch': batch, 'failures': failures, 'long_runners': long_runners,
                 'long_runner_classes': long_runner_classes})

    subject = 'Unit test results for ' + batch.branch.name.upper() + ' started at ' + str(batch.batch_time)
    from_email, to = from_address, schedule.results_email_address
    text_content = 'Please join the 21st century and get an HTML compatible email client to see the content of this email.'
    html_content = template.render(c)
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.connection = conn
    msg.send(fail_silently=False)
Example #2
0
def send_message(message_id):
    message = Message.objects.get(id=message_id)
    if not message:
        return

    msg = EmailMultiAlternatives(
        subject=message.subject,
        body=message.content,
        from_email=message.sender,
        to=message.to,
    )

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

    mailbox = message.mailbox

    if mailbox.type == MailBoxType.SMTP:
        backend = "django.core.mail.backends.smtp.EmailBackend"
        connection = get_connection(
            backend=backend,
            host=mailbox.smtp_host,
            port=int(mailbox.smtp_port),
            username=mailbox.smtp_username,
            password=mailbox.smtp_password,
            use_tls=mailbox.smtp_use_tls
        )
    elif mailbox.type == MailBoxType.SES:
        backend = "django_ses.SESBackend"
        extra = {}
        if mailbox.enable_dkim and mailbox.dkim_key:
            extra['dkim_domain'] = str(mailbox.domain)
            extra['dkim_key'] = str(mailbox.dkim_key.replace('\r', ''))

        connection = get_connection(
            backend,
            aws_access_key=mailbox.aws_access_key,
            aws_secret_key=mailbox.aws_access_secret_key, **extra)

    else:
        return

    msg.connection = connection

    msg.send(fail_silently=False)

    message.is_sent = True
    message.sent_at = datetime.now()
    message.save()
Example #3
0
def email_results(batch, failures, runs):
    long_runners = UnitTestRunResult.objects.filter(
        test_run__in=runs).order_by('-runtime')[:5]
    long_runners.select_related()
    long_runner_classes = UnitTestRun.objects.filter(
        batch=batch).order_by('-runtime')[:5]
    long_runner_classes.select_related()

    try:
        schedule = UnitTestSchedule.objects.get(branch=batch.branch)
    except ObjectDoesNotExist:
        logger.error('No Schedule exists for this branch (' +
                     batch.branch.name +
                     '), so no way to figure out who to email')
        return

    email_host = ConfigCache.get_config_value('email.host')
    conn = mail.get_connection(host=email_host)

    from_address = ConfigCache.get_config_value('email.from')

    if schedule.email_only_failures and len(failures) == 0:
        return

    template = get_template('unit_test_results_email.html')
    #    c = Context({'batch': batch, 'failures': failures, 'long_runners': long_runners,
    #                 'long_runner_classes': long_runner_classes})
    c = {
        'batch': batch,
        'failures': failures,
        'long_runners': long_runners,
        'long_runner_classes': long_runner_classes
    }

    subject = 'Unit test results for ' + batch.branch.name.upper(
    ) + ' started at ' + str(batch.batch_time)
    from_email, to = from_address, schedule.results_email_address
    text_content = 'Please join the 21st century and get an HTML compatible email client to see the content of this email.'
    html_content = template.render(c)
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.connection = conn
    msg.send(fail_silently=False)
Example #4
0
def send_test_email(host=None,
                    port=None,
                    host_user=None,
                    host_password=None,
                    use_tls=None,
                    to_email=EMPTY_STRING):
    test_is_ok = False
    try:
        if host and port:
            from repanier.apps import REPANIER_SETTINGS_GROUP_NAME
            # Avoid : string payload expected: <class 'django.utils.functional.__proxy__'>
            subject = "{}".format(
                _("Test mail server configuration from Repanier"))
            body = "{} {}".format(
                _("The mail server configuration is working on your website {}."
                  ).format(REPANIER_SETTINGS_GROUP_NAME),
                _("Do not forget to activate it."))
            to_email = list({to_email, host_user})
            email = EmailMultiAlternatives(
                subject=subject,
                body=body,
                from_email=host_user,
                to=to_email,
            )
            with mail.get_connection(host=host,
                                     port=port,
                                     username=host_user,
                                     password=host_password,
                                     use_tls=use_tls,
                                     use_ssl=not use_tls) as connection:
                email.connection = connection
                email.send()
                test_is_ok = True
    except SMTPAuthenticationError:
        pass
    except SMTPRecipientsRefused:
        pass
    except:
        pass
    if not test_is_ok:
        # delay to avoid too many attempts in a too short period of time
        time.sleep(10)
    return test_is_ok
Example #5
0
def sendResumeInformMail(request, resumes):
    top_image = None
    bottom_image = None

    if request.FILES.get('top_image'):
        top_image = MIMEImage(request.FILES['top_image'].read())
        top_image.add_header('Content-ID', '<top_image>')

    if request.FILES.get('bottom_image'):
        bottom_image = MIMEImage(request.FILES['bottom_image'].read())
        bottom_image.add_header('Content-ID', '<bottom_image>')

    sender = User.objects.get(username=request.POST.get('sender'))
    username = settings.EMAIL_HOST_USER
    password = settings.EMAIL_HOST_PASSWORD

    if request.POST.get('mail_password'):
        username = sender.email
        password = request.POST.get('mail_password')

    connection = get_connection(host=settings.EMAIL_HOST,
                                port=settings.EMAIL_PORT,
                                username=username,
                                password=password,
                                user_tls=settings.EMAIL_USE_TLS)

    sent_count = 0
    failed = []

    for resume in resumes:
        subject = request.POST.get('subject')
        password = request.POST.get('password')
        message_template = Template(request.POST.get('message'))
        message = message_template.render(Context({
            'resume': resume,
        }))

        variables = Context({
            'resume': resume,
            'message': message,
            'top_image': top_image,
            'bottom_image': bottom_image,
        })

        html = get_template('mail/resume_inform.html').render(variables)
        text = get_template('mail/resume_inform_text.html').render(variables)

        msg = EmailMultiAlternatives(
            subject,
            text,
            '%s%s <%s>' % (sender.last_name, sender.first_name, sender.email),
            [resume.email])
        msg.attach_alternative(html, "text/html")
        msg.content_subtype = 'html'
        msg.connection = connection

        if top_image:
            msg.attach(top_image)

        if bottom_image:
            msg.attach(bottom_image)

        try:
            result = msg.send(fail_silently=False)

            if result == 0:
                failed.append(resume.email)
            else:
                sent_count += result
        except:
            failed.append(resume.email)

    connection.close()

    return {
        'sent_count': sent_count,
        'failed': failed,
    }
    def send_activation_email(self, site):
        """
        Send an activation email to the user associated with this
        ``RegistrationProfile``.

        The activation email will make use of two templates:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. Because it is used as the subject line of an email,
            this template's output **must** be only a single line of
            text; output longer than one line will be forcibly joined
            into only a single line.

        ``registration/activation_email.txt``
            This template will be used for the plain-text body of the email.

        ``registration/activation_email.html``
            This template will be used for the HTML body of the email.

        These templates will each receive the following context
        variables:

        ``activation_key``
            The activation key for the new account.

        ``expiration_days``
            The number of days remaining during which the account may
            be activated.

        ``user``
            The user who is receiving the activation email.

        ``site``
            An object representing the site on which the user
            registered; depending on whether ``django.contrib.sites``
            is installed, this may be an instance of either
            ``django.contrib.sites.models.Site`` (if the sites
            application is installed) or
            ``django.contrib.sites.models.RequestSite`` (if
            not). Consult the documentation for the Django sites
            framework for details regarding these objects' interfaces.

        """
        ctx_dict = Context({
            'activation_key': self.activation_key,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
            'user': self.user,
            'site': site
        })
        subject = render_to_string('registration/activation_email_subject.txt',
                                   ctx_dict)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())

        message = {}
        for ext in ['txt', 'html']:
            try:
                t = get_template(
                    'registration/activation_email.{0}'.format(ext))
                message[ext] = t.render(ctx_dict)
            except TemplateDoesNotExist:
                pass

        # Make sure there is at least a .txt version
        if 'txt' not in message:
            raise TemplateDoesNotExist('registration/activation_email.txt')

        from_email = settings.DEFAULT_FROM_EMAIL
        email = EmailMultiAlternatives(unicode(_(subject)), message['txt'],
                                       from_email, [self.user.email])

        if 'html' in message:
            email.attach_alternative(message['html'], 'text/html')

        email.connection = get_connection(backend=EMAIL_BACKEND)
        email.send()
Example #7
0
def send_msg(**kwargs):
    session = kwargs['session']
    session_id = session.session_key
    compose = session['compose']
    email_field = session['email_field']
    total_emails = len(session['csv'])
    recipient = kwargs['row'][session['email_field']]

    ctx = Context(kwargs['row'])
    subject = Template(compose['subject']).render(ctx)
    txt_msg = Template(compose['txt_msg']).render(ctx)
    html_msg = Template(compose['html_msg']).render(ctx)
    msg = EmailMultiAlternatives(subject, txt_msg, compose['sender'],
                                 [recipient])
    msg.attach_alternative(html_msg, 'text/html')

    job = rq.get_current_job()
    job.meta['session_id'] = session_id
    job.save_meta()

    if kwargs['mode'] == 'google':
        msg_str = msg.message().as_string()
        raw_msg = base64.urlsafe_b64encode(msg_str.encode()).decode()

        response = requests.post(
            'https://www.googleapis.com/gmail/v1/users/me/messages/send',
            json={'raw': raw_msg},
            headers={
                'Authorization':
                'Bearer {0}'.format(session['smtp']['access_token']),
                'Content-Type':
                'application/json'
            })
        if not response.ok:
            status = response.content.decode()
            return status
    else:
        smtp = session['smtp']
        connection = {
            'host': smtp['host'],
            'port': smtp['port'],
            'username': smtp['username'],
            'password': smtp['password'],
            'use_tls': smtp['use_tls'],
        }

        msg.connection = get_connection(**connection)
        try:
            msg.send()
        except Exception as ex:
            status = ex.strerror
            return status

    idx = kwargs['idx']
    total_emails = len(session['csv'])

    status = _('{0}% sent.'.format((idx + 1) / total_emails * 100)) + '\r\n'
    status += _('Sent mail to {0}'.format(recipient)) + '\r\n'

    if idx + 1 == total_emails:
        queue_name = os.path.basename(settings.BASE_DIR)
        queue = django_rq.get_queue(queue_name)
        queue.enqueue(delete_session, session_id)
        status = True
    return status
def send_messages(data,
                  template,
                  sheet_title,
                  data_index=None,
                  email_to=None,
                  email_column=None,
                  bcc_column=None,
                  email_splitter=',',
                  email_settings=None):
    heads = data[0]

    if email_settings:
        smtp_host = email_settings['smtp_host']
        smtp_port = email_settings['smtp_port']
        smtp_username = email_settings['smtp_username']
        smtp_password = email_settings['smtp_password']

        mail_backend = EmailBackend(host=smtp_host,
                                    port=smtp_port,
                                    password=smtp_password,
                                    username=smtp_username,
                                    use_tls=True,
                                    timeout=10)
    else:
        mail_backend = None
    if data_index != None:
        data = data[1:][data_index]
        current_task.update_state(state='PROGRESS',
                                  meta={
                                      'current': 0,
                                      'total': 1
                                  })
        html_template = generate_email_template(template, heads, data)
        if email_settings:
            pass
            from_email = email_settings['smtp_from_email']
        else:
            from_email = settings.DEFAULT_FROM_EMAIL
        if email_to:
            sended = send_mail(sheet_title,
                               message=strip_tags(html_template),
                               html_message=html_template,
                               recipient_list=(email_to, ),
                               from_email=from_email,
                               connection=mail_backend)
            current_task.update_state(state='PROGRESS',
                                      meta={
                                          'current': 1,
                                          'total': 1
                                      })
    else:
        data = data[1:]
        data_size = len(data)
        current_task.update_state(state='PROGRESS',
                                  meta={
                                      'current': 0,
                                      'total': data_size
                                  })

        if email_column:
            email_column_index = heads.index(email_column)
        else:
            email_column_index = None

        if bcc_column:
            bcc_column_index = heads.index(bcc_column)
        else:
            bcc_column_index = None

        for i, el_data in enumerate(data):
            sleep(1)
            email_to = el_data[email_column_index]
            html_template = generate_email_template(template, heads, el_data)
            if email_settings:
                from_email = email_settings['smtp_from_email']
            else:
                from_email = settings.DEFAULT_FROM_EMAIL
            msg = EmailMultiAlternatives(subject=sheet_title,
                                         body=strip_tags(html_template),
                                         from_email=from_email)
            msg.attach_alternative(html_template, 'text/html')
            if bcc_column_index:
                msg.bcc = el_data[bcc_column_index].split(email_splitter)
            if email_column_index:
                msg.cc = el_data[email_column_index].split(email_splitter)
            if mail_backend:
                msg.connection = mail_backend

            msg.send()

            current_task.update_state(state='PROGRESS',
                                      meta={
                                          'current': i,
                                          'total': data_size
                                      })