Beispiel #1
0
    def execute(self, context):
        """
        :param context: Script Context.
        :type context: shuup.notify.script.Context
        """
        recipient = get_email_list(self.get_value(context, "recipient"))
        if not recipient:
            context.log(logging.INFO,
                        "Info! %s: Not sending mail, no recipient.",
                        self.identifier)
            return

        send_identifier = self.get_value(context, "send_identifier")
        if send_identifier and context.log_entry_queryset.filter(
                identifier=send_identifier).exists():
            context.log(
                logging.INFO,
                "Info! %s: Not sending mail, it was already sent (%r).",
                self.identifier, send_identifier)
            return

        languages = [
            language for language in [
                self.get_value(context, "language"),
                self.get_value(context, "fallback_language"),
            ] if language and language in dict(settings.LANGUAGES).keys()
        ]

        if not languages:
            languages = [settings.PARLER_DEFAULT_LANGUAGE_CODE]

        strings = self.get_template_values(context, languages)

        subject = unescape(strings.get("subject"))
        body = unescape(strings.get("body"))
        email_template_id = strings.get("email_template")

        if email_template_id:
            email_template = EmailTemplate.objects.filter(
                pk=email_template_id).first()

            if email_template and "%html_body%" in email_template.template:
                body = email_template.template.replace("%html_body%", body)

        content_type = strings.get("content_type")
        if not (subject and body):
            context.log(
                logging.INFO,
                "Info! %s: Not sending mail to %s, either subject or body empty.",
                self.identifier, recipient)
            return

        reply_to = get_email_list(self.get_value(context, "reply_to_address"))
        from_email = self.get_value(context, "from_email")
        bcc = get_email_list(self.get_value(context, "bcc"))
        cc = get_email_list(self.get_value(context, "cc"))

        subject = " ".join(
            subject.splitlines())  # Email headers may not contain newlines
        message = EmailMessage(subject=subject,
                               body=body,
                               to=recipient,
                               reply_to=reply_to,
                               from_email=from_email,
                               bcc=bcc,
                               cc=cc)
        message.content_subtype = content_type
        notification_email_before_send.send(sender=type(self),
                                            action=self,
                                            message=message,
                                            context=context)
        message.send()
        context.log(logging.INFO, "Info! %s: Mail sent to %s.",
                    self.identifier, recipient)

        notification_email_sent.send(sender=type(self),
                                     message=message,
                                     context=context)

        if send_identifier:
            context.add_log_entry_on_log_target(
                "Info! Email sent to %s: %s" % (recipient, subject),
                send_identifier)
Beispiel #2
0
 def _send(subject, text, from_email, email):
     EmailMessage(subject, text, from_email, [email]).send()
Beispiel #3
0
    def post(self, req, *args, **kwargs):
        report = dict([(key, req.POST.get(key, '')) for key in (
            'subject',
            'username',
            'domain',
            'url',
            'message',
            'app_id',
            'cc',
            'email',
            '500traceback',
            'sentry_id',
        )])

        try:
            couch_user = req.couch_user
            full_name = couch_user.full_name
            if couch_user.is_commcare_user():
                email = report['email']
            else:
                email = couch_user.get_email()
        except Exception:
            full_name = None
            email = report['email']
        report['full_name'] = full_name
        report['email'] = email or report['username']

        if report['domain']:
            domain = report['domain']
        elif len(couch_user.domains) == 1:
            # This isn't a domain page, but the user has only one domain, so let's use that
            domain = couch_user.domains[0]
        else:
            domain = "<no domain>"

        message = ("username: {username}\n"
                   "full name: {full_name}\n"
                   "domain: {domain}\n"
                   "url: {url}\n").format(**report)

        domain_object = Domain.get_by_name(
            domain) if report['domain'] else None
        debug_context = {
            'datetime':
            datetime.utcnow(),
            'self_started':
            '<unknown>',
            'scale_backend':
            '<unknown>',
            'has_handoff_info':
            '<unknown>',
            'project_description':
            '<unknown>',
            'sentry_error':
            '{}{}'.format(getattr(settings, 'SENTRY_QUERY_URL', ''),
                          report['sentry_id'])
        }
        if domain_object:
            current_project_description = domain_object.project_description if domain_object else None
            new_project_description = req.POST.get('project_description')
            if (domain_object and req.couch_user.is_domain_admin(domain=domain)
                    and new_project_description and
                    current_project_description != new_project_description):
                domain_object.project_description = new_project_description
                domain_object.save()

            message += (("software plan: {software_plan}\n").format(
                software_plan=Subscription.get_subscribed_plan_by_domain(
                    domain), ))

            debug_context.update({
                'self_started':
                domain_object.internal.self_started,
                'scale_backend':
                should_use_sql_backend(domain),
                'has_handoff_info':
                bool(domain_object.internal.partner_contact),
                'project_description':
                domain_object.project_description,
            })

        subject = '{subject} ({domain})'.format(subject=report['subject'],
                                                domain=domain)
        cc = [el for el in report['cc'].strip().split(",") if el]

        if full_name and not any([c in full_name for c in '<>"']):
            reply_to = '"{full_name}" <{email}>'.format(**report)
        else:
            reply_to = report['email']

        # if the person looks like a commcare user, fogbugz can't reply
        # to their email, so just use the default
        if settings.HQ_ACCOUNT_ROOT in reply_to:
            reply_to = settings.SERVER_EMAIL

        message += "Message:\n\n{message}\n".format(message=report['message'])
        if req.POST.get('five-hundred-report'):
            extra_message = (
                "This message was reported from a 500 error page! "
                "Please fix this ASAP (as if you wouldn't anyway)...")
            extra_debug_info = (
                "datetime: {datetime}\n"
                "Is self start: {self_started}\n"
                "Is scale backend: {scale_backend}\n"
                "Has Support Hand-off Info: {has_handoff_info}\n"
                "Project description: {project_description}\n"
                "Sentry Error: {sentry_error}\n").format(**debug_context)
            traceback_info = cache.cache.get(
                report['500traceback']) or 'No traceback info available'
            cache.cache.delete(report['500traceback'])
            message = "\n\n".join(
                [message, extra_debug_info, extra_message, traceback_info])

        email = EmailMessage(subject=subject,
                             body=message,
                             to=self.recipients,
                             headers={'Reply-To': reply_to},
                             cc=cc)

        uploaded_file = req.FILES.get('report_issue')
        if uploaded_file:
            filename = uploaded_file.name
            content = uploaded_file.read()
            email.attach(filename=filename, content=content)

        # only fake the from email if it's an @dimagi.com account
        is_icds_env = settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS
        if re.search(r'@dimagi\.com$', report['username']) and not is_icds_env:
            email.from_email = report['username']
        else:
            email.from_email = settings.CCHQ_BUG_REPORT_EMAIL

        email.send(fail_silently=False)

        if req.POST.get('five-hundred-report'):
            messages.success(
                req,
                "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem."
            )
            return HttpResponseRedirect(reverse('homepage'))

        return HttpResponse()
Beispiel #4
0
def send_mail(subject,
              email_body,
              user_to=None,
              email_to=None,
              email_from=None,
              reply_to=None):
    """
    Sends email with a lot of defaults. The function will check if user's email is valid based on bounce info and will
    not send to this user in other case. Parameters user_to and email_to are mutually exclusive, if one is set, other
    should be None.
    @:param user_to is a single user object, or a list of them. If it is set, email_to parameter should be None
    @:param email_to is a single email string, or a list of them. If it is set, user_to parameter should be None.
    Strings should be only used for emails that are not related to users, e.g. support or admins, otherwise user_to
    parameter should be used to provide user object(s) instead of email address
    @:param email_from is a email string that shows up as sender. The default value is DEFAULT_FROM_EMAIL in config
    @:param reply_to can only be a single email address that will be added as a header to all mails being sent
    @:returns False if no emails were send successfully, True otherwise
    """
    assert bool(user_to) != bool(
        email_to
    ), "One of parameters user_to and email_to should be set, but not both"

    if email_from is None:
        email_from = settings.DEFAULT_FROM_EMAIL

    if user_to:
        user_to = _ensure_list(user_to)
        email_to = []
        for user in user_to:

            # check if user's email is valid for delivery and add the correct email address to the list og email_to
            if user.profile.email_is_valid():
                email_to.append(user.profile.get_email_for_delivery())

            if len(email_to) == 0:  # all users have invalid emails
                return False

    if email_to:
        email_to = _ensure_list(email_to)

    if settings.ALLOWED_EMAILS:  # for testing purposes, so we don't accidentally send emails to users
        email_to = [
            email for email in email_to if email in settings.ALLOWED_EMAILS
        ]

    try:
        emails = tuple(((settings.EMAIL_SUBJECT_PREFIX + subject, email_body,
                         email_from, [email]) for email in email_to))

        # Replicating send_mass_mail functionality and adding reply-to header if requires
        connection = get_connection(username=None,
                                    password=None,
                                    fail_silently=False)
        headers = None
        if reply_to:
            headers = {'Reply-To': reply_to}
        messages = [
            EmailMessage(subject, message, sender, recipient, headers=headers)
            for subject, message, sender, recipient in emails
        ]

        connection.send_messages(messages)
        return True

    except Exception:
        return False
Beispiel #5
0
def contato(request, cidade_slug):
    cidade = get_object_or_404(Cidade, slug=cidade_slug)
    cidades_disponiveis = Cidade.objects.all()
    #Mapa
    gmap = maps.Map(
        opts={
            'center': maps.LatLng('-34', '20'),
            'mapTypeId': maps.MapTypeId.ROADMAP,
            'zoom': 15,
            'mapTypeControlOptions': {
                'style': maps.MapTypeControlStyle.DROPDOWN_MENU
            },
        })
    marker = maps.Marker(opts={
        'map': gmap,
        'position': maps.LatLng('-34', '20'),
    })
    maps.event.addListener(marker, 'mouseover', 'myobj.markerOver')
    maps.event.addListener(marker, 'mouseout', 'myobj.markerOut')
    info = maps.InfoWindow({
        'content':
        '<h3>' + 'Clipper Magazine' + '</h3>' + '<p>Rua: ' + 'etc etc' +
        '</p>' + '<p>Telefone: ' + '62 888992212' + '</p>',
        'disableAutoPan':
        False
    })
    info.open(gmap, marker)

    #formulario de contato
    if request.POST:
        postdata = request.POST.copy()
        form_contato = Contato_Form(postdata)
        if form_contato.is_valid():
            cad_contato = Contato()
            cad_contato.nome = form_contato.cleaned_data['nome']
            cad_contato.empresa = form_contato.cleaned_data['empresa']
            cad_contato.email = form_contato.cleaned_data['email']
            cad_contato.telefone = cad_contato.cleaned_data['telefone']
            cad_contato.mensagem = form_contato.cleaned_data['mensagem']
            cad_contato.save()

            mensagem_site = form_contato.cleaned_data['mensagem']
            mensagem = "Ola\nO %s Mandou a seguinte mensagem:\n%s" % (
                cad_contato.nome, mensagem_site)
            email = EmailMessage(cad_contato.mensagem,
                                 mensagem,
                                 to=['*****@*****.**'])
            email.send()

            if request.is_ajax():
                return render_to_response('contato/sucesso.html')
            else:
                return redirect('contato_sucesso')
    else:
        form_contato = Contato_Form()

    if request.session.get('email_cadastrado', False):
        email_cadastrado = True
        email_form = None
    else:
        email_cadastrado = False
        email_form = EmailForm()
        email_duplicado = False

    if request.POST:
        postdata = request.POST.copy()
        email_form = EmailForm(postdata)
        if email_form.is_valid():
            cad_email = EmailInscricao()
            cad_email.email = email_form.cleaned_data['email']
            cad_email.cidade = email_form.cleaned_data['cidade']
            cad_email.save()
            email_cadastrado = True

    context = {
        'form_mapa': MapForm(initial={'map': gmap}),
        'email_form': email_form,
        'email_cadastrado': email_cadastrado,
        'form_contato': form_contato,
        'cidades_disponiveis': cidades_disponiveis,
        'cidade': cidade,
    }
    return render_to_response('contato/contato.html',
                              context,
                              context_instance=RequestContext(request))
Beispiel #6
0
def download_payment_file_post(request):
    download_file = request.POST.get('download_payment_file', None)
    send_file = request.POST.get('send_payment_file', None)
    send_sales_report = request.POST.get('send_sales_report', None)
    if download_file:
        dl_url = get_today_payments()
        if not dl_url:
            return HttpResponseBadRequest('no url found')
        return HttpResponseRedirect(redirect_to=dl_url)
    if send_file:
        dl_url = payment_summary_today()
        msg = "Email sent to " + ', '.join(
            ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**',
             '*****@*****.**', '*****@*****.**', '*****@*****.**'])
        messages.error(request, "Mail sent successfully")
        return HttpResponseRedirect(redirect_to=dl_url)
    if send_sales_report:
        mb = ManualBooking.objects.filter(
            created_on__date=datetime.now().date() - timedelta(days=1)
        ).exclude(
            booking_status='cancelled'
        ).order_by(
            '-shipment_date'
        )
        if mb:
            data = []
            for booking in mb:
                try:
                    data.append([
                        booking.booking_id,
                        '\n'.join(booking.lr_numbers.values_list('lr_number', flat=True)),
                        booking.from_city,
                        booking.to_city,
                        booking.party_rate,
                        booking.charged_weight,
                        booking.total_amount_to_company,
                        booking.supplier_rate,
                        booking.supplier_charged_weight,
                        booking.total_amount_to_owner,
                        booking.total_amount_to_company - booking.total_amount_to_owner,
                        "{0:.2f}".format(((
                                                  booking.total_amount_to_company - booking.total_amount_to_owner) / booking.total_amount_to_owner) * 100)
                    ])
                except ZeroDivisionError:
                    data.append([
                        booking.booking_id,
                        '\n'.join(booking.lr_numbers.values_list('lr_number', flat=True)),
                        booking.from_city,
                        booking.to_city,
                        booking.party_rate,
                        booking.charged_weight,
                        booking.total_amount_to_company,
                        booking.supplier_rate,
                        booking.supplier_charged_weight,
                        booking.total_amount_to_owner,
                        booking.total_amount_to_company - booking.total_amount_to_owner,
                        'Amount to owner is zero'
                    ])

            df = pd.DataFrame(data=data,
                              columns=['Booking ID', 'LR Number(s)', 'From City', 'To City', 'Party Rate',
                                       'Party Weight',
                                       'Party Amount', 'Supplier Rate', 'Supplier Weight', 'Supplier Amount', 'Profit',
                                       '% Profit'])
            bytes_io = BytesIO()
            df.to_csv(bytes_io, index=False)
            bytes_io.seek(0)
            content = bytes_io.getvalue() or '\n'
            filename = datetime.now().strftime('%d%b%Y%I%M') + '.csv'
            s3_upload = save_to_s3_daily_sales_report(filename, content)
            s3_url = s3_upload.public_url()
            subject = '[Aaho] Daily Sales Report for ' + (datetime.now().date() - timedelta(days=1)).strftime(
                '%d-%b-%Y')
            body = get_template('team/emails/last-day-bookings.html').render(context={'mb': mb, 's3_url': s3_url})
            email = EmailMessage(subject, body,
                                 to=['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'])
            email.content_subtype = 'html'
            email.send()
    return HttpResponseRedirect('/team/download-payment-file/')
Beispiel #7
0
def user_details_force_sync(auth_entry, strategy, details, user=None, *args, **kwargs):
    """
    Update normally protected user details using data from provider.

    This step in the pipeline is akin to `social_core.pipeline.user.user_details`, which updates
    the user details but has an unconfigurable protection over updating the username & email, and
    is unable to update information such as the user's full name which isn't on the user model, but
    rather on the user profile model.

    Additionally, because the email field is normally used to log in, if the email is changed by this
    forced synchronization, we send an email to both the old and new emails, letting the user know.

    This step is controlled by the `sync_learner_profile_data` flag on the provider's configuration.
    """
    current_provider = provider.Registry.get_from_pipeline({'backend': strategy.request.backend.name, 'kwargs': kwargs})
    if user and current_provider.sync_learner_profile_data:
        # Keep track of which incoming values get applied.
        changed = {}

        # Map each incoming field from the provider to the name on the user model (by default, they always match).
        field_mapping = {field: (user, field) for field in details.keys() if hasattr(user, field)}

        # This is a special case where the field mapping should go to the user profile object and not the user object,
        # in some cases with differing field names (i.e. 'fullname' vs. 'name').
        field_mapping.update({
            'fullname': (user.profile, 'name'),
            'country': (user.profile, 'country'),
        })

        # Remove username from list of fields for update
        field_mapping.pop('username', None)

        # Track any fields that would raise an integrity error if there was a conflict.
        integrity_conflict_fields = {'email': user.email, 'username': user.username}

        for provider_field, (model, field) in field_mapping.items():
            provider_value = details.get(provider_field)
            current_value = getattr(model, field)
            if provider_value is not None and current_value != provider_value:
                if field in integrity_conflict_fields and User.objects.filter(**{field: provider_value}).exists():
                    logger.warning('User with ID [%s] tried to synchronize profile data through [%s] '
                                   'but there was a conflict with an existing [%s]: [%s].',
                                   user.id, current_provider.name, field, provider_value)
                    continue
                changed[provider_field] = current_value
                setattr(model, field, provider_value)

        if changed:
            logger.info(
                "User [%s] performed SSO through [%s] who synchronizes profile data, and the "
                "following fields were changed: %s", user.username, current_provider.name, changed.keys(),
            )

            # Save changes to user and user.profile models.
            strategy.storage.user.changed(user)
            user.profile.save()

            # Send an email to the old and new email to alert the user that their login email changed.
            if changed.get('email'):
                old_email = changed['email']
                new_email = user.email
                email_context = {'old_email': old_email, 'new_email': new_email}
                # Subjects shouldn't have new lines.
                subject = ''.join(render_to_string(
                    'emails/sync_learner_profile_data_email_change_subject.txt',
                    email_context
                ).splitlines())
                body = render_to_string('emails/sync_learner_profile_data_email_change_body.txt', email_context)
                from_email = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)

                email = EmailMessage(subject=subject, body=body, from_email=from_email, to=[old_email, new_email])
                email.content_subtype = "html"
                try:
                    email.send()
                except SMTPException:
                    logger.exception('Error sending IdP learner data sync-initiated email change '
                                     'notification email for user [%s].', user.username)
Beispiel #8
0
 def run(self):
     msg = EmailMessage(self.subject, self.html_content, self.sender,
                        self.recipient_list)
     msg.send()
Beispiel #9
0
def bug_report(req):
    report = dict([(key, req.POST.get(key, '')) for key in (
        'subject',
        'username',
        'domain',
        'url',
        'message',
        'app_id',
        'cc',
        'email',
        '500traceback',
        'sentry_id',
    )])

    report['user_agent'] = req.META['HTTP_USER_AGENT']
    report['datetime'] = datetime.utcnow()

    try:
        couch_user = req.couch_user
        full_name = couch_user.full_name
        if couch_user.is_commcare_user():
            email = report['email']
        else:
            email = couch_user.get_email()
    except Exception:
        full_name = None
        email = report['email']
    report['full_name'] = full_name
    report['email'] = email or report['username']

    if report['domain']:
        domain = report['domain']
    elif len(couch_user.domains) == 1:
        # This isn't a domain page, but the user has only one domain, so let's use that
        domain = couch_user.domains[0]
    else:
        domain = "<no domain>"

    message = (u"username: {username}\n"
               u"full name: {full_name}\n"
               u"domain: {domain}\n"
               u"url: {url}\n"
               u"datetime: {datetime}\n"
               u"User Agent: {user_agent}\n").format(**report)

    domain_object = Domain.get_by_name(domain) if report['domain'] else None
    if domain_object:
        current_project_description = domain_object.project_description if domain_object else None
        new_project_description = req.POST.get('project_description')
        if (domain_object and req.couch_user.is_domain_admin(domain=domain)
                and new_project_description
                and current_project_description != new_project_description):

            domain_object.project_description = new_project_description
            domain_object.save()

        matching_subscriptions = Subscription.objects.filter(
            is_active=True,
            subscriber__domain=domain,
        )
        if len(matching_subscriptions) >= 1:
            software_plan = matching_subscriptions[0].plan_version
        else:
            software_plan = u'domain has no active subscription'

        message += ((
            u"software plan: {software_plan}\n"
            u"Is self start: {self_started}\n"
            u"Feature Flags: {feature_flags}\n"
            u"Feature Previews: {feature_previews}\n"
            u"Is scale backend: {scale_backend}\n"
            u"Has Support Hand-off Info: {has_handoff_info}\n"
            u"Internal Project Information: {internal_info_link}\n"
            u"Project description: {project_description}\n"
            u"Sentry Error: {sentry_error}\n").format(
                software_plan=software_plan,
                self_started=domain_object.internal.self_started,
                feature_flags=toggles.toggles_dict(username=report['username'],
                                                   domain=domain).keys(),
                feature_previews=feature_previews.previews_dict(domain).keys(),
                scale_backend=should_use_sql_backend(domain),
                has_handoff_info=bool(domain_object.internal.partner_contact),
                internal_info_link=reverse('domain_internal_settings',
                                           args=[domain],
                                           absolute=True),
                project_description=domain_object.project_description,
                sentry_error='{}{}'.format(
                    getattr(settings, 'SENTRY_QUERY_URL'),
                    report['sentry_id'])))

    subject = u'{subject} ({domain})'.format(subject=report['subject'],
                                             domain=domain)
    cc = report['cc'].strip().split(",")
    cc = filter(None, cc)

    if full_name and not any([c in full_name for c in '<>"']):
        reply_to = u'"{full_name}" <{email}>'.format(**report)
    else:
        reply_to = report['email']

    # if the person looks like a commcare user, fogbugz can't reply
    # to their email, so just use the default
    if settings.HQ_ACCOUNT_ROOT in reply_to:
        reply_to = settings.SERVER_EMAIL

    message += u"Message:\n\n{message}\n".format(message=report['message'])
    if req.POST.get('five-hundred-report'):
        extra_message = ("This messge was reported from a 500 error page! "
                         "Please fix this ASAP (as if you wouldn't anyway)...")
        traceback_info = cache.cache.get(report['500traceback'])
        cache.cache.delete(report['500traceback'])
        traceback_info = "Traceback of this 500: \n%s" % traceback_info
        message = "%s \n\n %s \n\n %s" % (message, extra_message,
                                          traceback_info)

    email = EmailMessage(subject=subject,
                         body=message,
                         to=settings.BUG_REPORT_RECIPIENTS,
                         headers={'Reply-To': reply_to},
                         cc=cc)

    uploaded_file = req.FILES.get('report_issue')
    if uploaded_file:
        filename = uploaded_file.name
        content = uploaded_file.read()
        email.attach(filename=filename, content=content)

    # only fake the from email if it's an @dimagi.com account
    if re.search('@dimagi\.com$', report['username']):
        email.from_email = report['username']
    else:
        email.from_email = settings.CCHQ_BUG_REPORT_EMAIL

    email.send(fail_silently=False)

    if req.POST.get('five-hundred-report'):
        messages.success(
            req,
            "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem."
        )
        return HttpResponseRedirect(reverse('homepage'))

    return HttpResponse()
def send_mail(to_list, subject, content):
    email = EmailMessage(subject, content, to=[to for to in to_list])
    email.content_subtype = 'html'
    email.send(fail_silently=True)
Beispiel #11
0
def _generate_notification_for_incoming_match(results, incoming_query,
                                              incoming_request_node,
                                              incoming_patient):
    """
    Generate a SLACK notifcation to say that a VALID match request came in and the following
    results were sent back. If Slack is not supported, a message is not sent, but details persisted.

    Args:
        response_from_matchbox (python requests object): contains the response from matchbox
        incoming_request (Django request object): The request that came into the view
        incoming_patient (JSON): The query patient JSON structure from outside MME node that was matched with
    """
    incoming_patient_id = incoming_patient['patient']['id']

    logger.info('{} MME matches found for patient {} from {}'.format(
        len(results), incoming_patient_id, incoming_request_node))

    institution = incoming_patient['patient']['contact'].get(
        'institution', incoming_request_node)
    contact_href = incoming_patient['patient']['contact'].get(
        'href', '(sorry I was not able to read the information given for URL)')

    if not results:
        message_template = """A match request for {patient_id} came in from {institution} today.
        The contact information given was: {contact}.
        We didn't find any individuals in matchbox that matched that query well, *so no results were sent back*."""
        post_to_slack(
            MME_SLACK_MATCH_NOTIFICATION_CHANNEL,
            message_template.format(institution=institution,
                                    patient_id=incoming_patient_id,
                                    contact=contact_href))
        return

    new_matched_results = MatchmakerResult.objects.filter(
        originating_query=incoming_query).prefetch_related('submission')
    if not new_matched_results:
        message_template = """A match request for {patient_id} came in from {institution} today.
        The contact information given was: {contact}.
        We found {existing_results} existing matching individuals but no new ones, *so no results were sent back*."""
        post_to_slack(
            MME_SLACK_MATCH_NOTIFICATION_CHANNEL,
            message_template.format(institution=institution,
                                    patient_id=incoming_patient_id,
                                    contact=contact_href,
                                    existing_results=len(results)))
        return

    hpo_terms_by_id, genes_by_id, _ = get_mme_genes_phenotypes_for_results(
        [incoming_patient])

    match_results = []
    all_emails = set()
    for result in new_matched_results:
        submission = result.submission
        individual = submission.individual
        project = individual.family.project

        result_text = u"""seqr ID {individual_id} from project {project_name} in family {family_id} inserted into
matchbox on {insertion_date}, with seqr link
{host}project/{project_guid}/family_page/{family_guid}/matchmaker_exchange""".replace(
            '\n', ' ').format(
                individual_id=individual.individual_id,
                project_guid=project.guid,
                project_name=project.name,
                family_guid=individual.family.guid,
                family_id=individual.family.family_id,
                insertion_date=submission.created_date.strftime('%b %d, %Y'),
                host=BASE_URL)
        emails = [
            email.strip() for email in submission.contact_href.replace(
                'mailto:', '').split(',')
            if email.strip() != MME_DEFAULT_CONTACT_EMAIL
        ]
        all_emails.update(emails)
        match_results.append((result_text, emails))

    base_message = u"""Dear collaborators,

    matchbox found a match between a patient from {query_institution} and the following {number_of_results} case(s) 
    in matchbox. The following information was included with the query,

    genes: {incoming_query_genes}
    phenotypes: {incoming_query_phenotypes}
    contact: {incoming_query_contact_name}
    email: {incoming_query_contact_url}

    We sent back the following:

    """.format(
        query_institution=institution,
        number_of_results=len(results),
        incoming_query_genes=', '.join(
            sorted([gene['geneSymbol'] for gene in genes_by_id.values()])),
        incoming_query_phenotypes=', '.join([
            '{} ({})'.format(hpo_id, term)
            for hpo_id, term in hpo_terms_by_id.items()
        ]),
        incoming_query_contact_url=contact_href,
        incoming_query_contact_name=incoming_patient['patient']['contact'].get(
            'name',
            '(sorry I was not able to read the information given for name'),
    )

    message_template = u"""{base_message}{match_results}

    We sent this email alert to: {email_addresses_alert_sent_to}\n{footer}."""

    post_to_slack(
        MME_SLACK_MATCH_NOTIFICATION_CHANNEL,
        message_template.format(
            base_message=base_message,
            match_results='\n'.join([text for text, _ in match_results]),
            email_addresses_alert_sent_to=', '.join(all_emails),
            footer=MME_EMAIL_FOOTER))

    for result_text, emails in match_results:
        email_message = EmailMessage(
            subject='Received new MME match',
            body=message_template.format(
                base_message=base_message,
                match_results=result_text,
                email_addresses_alert_sent_to=', '.join(emails),
                footer=MME_EMAIL_FOOTER),
            to=emails,
            from_email=MME_DEFAULT_CONTACT_EMAIL,
        )
        email_message.send()
 def setUp(self):
     self.email_message = EmailMessage(subject=u'test subject', body=u'test body', from_email='*****@*****.**',
                                       to=['*****@*****.**'], bcc=['*****@*****.**'], attachments=['/path/to/file'],
                                       headers={'Extra-Header': 'extra-value'}, cc=['*****@*****.**'])
     serializer = load_object(django_gearman_proxy.settings.GEARMAN_EMAIL_SERIALIZER)
     self.serialized = json.loads(serializer(self.email_message))
Beispiel #13
0
def email(request):
	email = EmailMessage()
	email.subject = "Hola mensaje de prueba desde el servidor de acerh"
	email.body = "Coneccion totalmente lograda, prueba test #2"
	email.to = [ "*****@*****.**"]
	email.send()
Beispiel #14
0
def handle_uploaded_files(request, network, localfiles, lookup={}):

    num = len(localfiles)
    if num == 0:
        return

    def process_file(f, name):
        basename = os.path.basename(name)
        mon, screen = addmonfile(request, network, f, lookup.get(basename))
        if not mon or not screen:
            logger.warning('Bestand {name} overgeslagen'.format(name=name))
            return False
        else:
            screens.add(screen)
            wells.add(screen.well)
            return True

    def process_zipfile(pathname):
        z = zipfile.ZipFile(pathname, 'r')
        result = {}
        for name in z.namelist():
            if name.lower().endswith('.mon'):
                bytes = z.read(name)
                io = StringIO(bytes)
                io.name = name
                try:
                    result[name] = 'Success' if process_file(
                        io, name) else 'Niet gebruikt'
                except Exception as e:
                    logger.exception('Fout in bestand {}'.format(name))
                    result[name] = 'Error'

        return result

    def process_plainfile(pathname):
        with open(pathname) as f:
            return 'Success' if process_file(
                f, os.path.basename(pathname)) else 'Niet gebruikt'

    #incstall handler that buffers logrecords to be sent by email
    buffer = logging.handlers.BufferingHandler(20000)
    logger.addHandler(buffer)
    try:
        logger.info('Verwerking van %d bestand(en)' % num)
        screens = set()
        wells = set()
        result = {}
        for pathname in localfiles:
            msg = []
            filename = os.path.basename(pathname)
            try:
                if zipfile.is_zipfile(pathname):
                    msg = process_zipfile(pathname)
                    result.update(msg)
                    #result.update({filename+'-'+key: val for key,val in msg.iteritems()})
                else:
                    result[filename] = process_plainfile(pathname)
            except Exception as e:
                logger.exception('Probleem met bestand {name}: {error}'.format(
                    name=filename, error=e))
                msg.append('Fout: ' + unicode(e))
                continue

        logger.info('Bijwerken van tijdreeksen')
        num = 0
        for s in screens:
            try:
                logger.info('Tijdreeks {}'.format(unicode(s)))
                update_series(request, s)
                num += 1
            except Exception as e:
                logger.exception(
                    'Bijwerken tijdreeksen voor filter {screen} mislukt: {error}'
                    .format(screen=unicode(s), error=e))
        logger.info('{} tjdreeksen bijgewerkt'.format(num))

        logger.info('Bijwerken van grafieken voor putten')
        num = 0
        for w in wells:
            try:
                logger.info('Put {}'.format(unicode(w)))
                make_chart(w)
                num += 1
            except Exception as e:
                logger.exception(
                    'Bijwerken van grafieken voor put {well} mislukt: {error}'.
                    format(well=unicode(w), error=e))
        logger.info('{} grafieken bijgewerkt'.format(num))

        if request.user.email:

            logbuffer = buffer.buffer
            buffer.flush()

            logger.debug('Sending email to %s (%s)' %
                         (request.user.get_full_name()
                          or request.user.username, request.user.email))

            name = request.user.first_name or request.user.username
            html_message = render_to_string(
                'notify_email_nl.html', {
                    'name': name,
                    'network': network,
                    'result': result,
                    'logrecords': logbuffer
                })
            message = render_to_string(
                'notify_email_nl.txt', {
                    'name': name,
                    'network': network,
                    'result': result,
                    'logrecords': logbuffer
                })
            msg = EmailMessage(
                subject='Meetnet {net}: bestanden verwerkt'.format(
                    net=network),
                body=message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                to=[request.user.email],
                attachments=[('report.html', html_message, 'text/html')])
            msg.send()
    finally:
        logger.removeHandler(buffer)
Beispiel #15
0
def upload(req): 
    r = HttpResponse()
    f = req.FILES["file"]
    id_ensemble = req.GET["id_ensemble"]
    id_source = req.GET["id_source"]
    id_folder = req.GET.get("id_folder", None)
    uid = UR.getUserId(req);
    logging.info("upload uid=%s, id_source=%s, id_ensemble=%s, id_folder=%s" %  (uid,id_source,id_ensemble,id_folder))
    url = "http://%s:%s/%s?id_ensemble=%s" %("localhost", "8000",f.name, id_ensemble)
    payload = {"url": url, "id_source": id_source, "id_folder": id_folder }
    if auth.canInsertFile(uid, id_ensemble, id_folder):
        #the followong data will be deleted in utils_pdf if an PDF error happens later...
        annotations.createSource(uid, payload)
        ownership = annotations.addOwnership(id_source, id_ensemble, id_folder)
        source = ownership.source
        #bug? before it was %s/%s which produced //
        REPOSITORY_DIR = "%s%s" % (settings.HTTPD_MEDIA, "/pdf/repository")
        print REPOSITORY_DIR
        f2 = open("%s/%s" % (REPOSITORY_DIR, id_source,),"wb")    
        f2.write(f.read())
        f2.close()                 
        if insert_pdf_metadata(id_source,  REPOSITORY_DIR):
            V = {"reply_to": settings.SMTP_REPLY_TO,
             "email": source.submittedby.email,
             "title": source.title,  
             "submitted": ownership.published, 
             "protocol": settings.PROTOCOL, 
             "hostname": settings.HOSTNAME, 
             "id_source": id_source, 
             "firstname": source.submittedby.firstname
             }
            msg = render_to_string("email/msg_pdfdone",V)
            email = EmailMessage(
                "The PDF file that you've submitted is now ready on NB.", 
                msg,
                settings.EMAIL_FROM,
                (V["email"], settings.SMTP_CC_USER ), 
                (settings.EMAIL_BCC, ))
            email.send()
        else:
            #send email that stg didn't work and remove that document.         
            V = {"reply_to": settings.SMTP_REPLY_TO,
                     "email": source.submittedby.email,
                     "source_id": id_source,
                     "title": source.title, 
                     "submitted": ownership.published, 
                     "support":  settings.SUPPORT_LINK,
                     "contact_email": settings.NBTEAM_EMAIL,
                     "firstname": source.submittedby.firstname
                     }
            ownership.delete()
            source.delete()
            msg = render_to_string("email/msg_pdferror",V)
            email = EmailMessage(
                "NB was unable to read a PDF file that you've submitted", 
                msg,  
                settings.EMAIL_FROM,
                (V["email"], settings.SMTP_CC_PDFERROR ), (settings.EMAIL_BCC, ))
            email.send()
        r.content =  UR.prepare_response({})
    else: 
        r.content =  UR.prepare_response({}, 1, "NOT ALLOWED to insert a file to this group")
    return r
Beispiel #16
0
def send_new_mail(subject, message, from_email, recipient_list, bcc_list):
    return EmailMessage(subject, message, from_email, recipient_list, bcc_list).send()
Beispiel #17
0
def send_email(request):
    msg = EmailMessage('Request Callback',
                       'Here is the message.',
                       to=['*****@*****.**'])
    msg.send()
    return HttpResponseRedirect('/')
Beispiel #18
0
def enviar_email(asunto, mensaje, mensaje_html, destinos):
    msg = EmailMessage(asunto, mensaje_html, settings.EMAIL_HOST_USER, destinos)
    msg.content_subtype = "html"
    msg.send()
    def _execute(self, job):
        from creme import persons

        from creme.opportunities import get_opportunity_model
        from creme.opportunities.constants import REL_SUB_TARGETS

        from .models import CommercialApproach

        Organisation = persons.get_organisation_model()
        Contact = persons.get_contact_model()
        Opportunity = get_opportunity_model()

        emails = []

        get_ct = ContentType.objects.get_for_model
        ct_orga = get_ct(Organisation)
        ct_contact = get_ct(Contact)
        ct_opp = get_ct(Opportunity)

        now_value = now()
        managed_orga_ids = [
            *Organisation.objects.filter(is_managed=True).values_list(
                'id', flat=True)
        ]
        opp_filter = Opportunity.objects.filter

        EMAIL_SENDER = settings.EMAIL_SENDER

        for rtype, delay in self.list_target_orga:
            com_apps_filter = CommercialApproach.objects \
                                                .filter(creation_date__gt=now_value - timedelta(days=delay)) \
                                                .filter

            # TODO: are 'values_list' real optimizations here ??
            #       ==> remove them when CommercialApproach use real ForeignKey
            for orga in Organisation.objects.filter(
                    is_managed=False,
                    relations__type=rtype,
                    relations__object_entity__in=managed_orga_ids,
            ):
                if com_apps_filter(entity_content_type=ct_orga,
                                   entity_id=orga.id).exists():
                    continue

                if com_apps_filter(
                        entity_content_type=ct_contact,
                        entity_id__in=orga.get_managers().values_list(
                            'id', flat=True)).exists():
                    continue

                if com_apps_filter(
                        entity_content_type=ct_contact,
                        entity_id__in=orga.get_employees().values_list(
                            'id', flat=True)).exists():
                    continue

                if com_apps_filter(entity_content_type=ct_opp,
                                   entity_id__in=opp_filter(
                                       relations__type=REL_SUB_TARGETS,
                                       relations__object_entity=orga,
                                   ).values_list('id', flat=True)).exists():
                    continue

                emails.append(
                    EmailMessage(
                        gettext(
                            '[CremeCRM] The organisation «{}» seems neglected'
                        ).format(orga),
                        gettext(
                            "It seems you haven't created a commercial approach for "
                            "the organisation «{orga}» since {delay} days.").
                        format(
                            orga=orga,
                            delay=delay,
                        ),
                        EMAIL_SENDER,
                        [orga.user.email],
                    ))

        # TODO: factorise jobs which send emails
        if emails:
            try:
                with get_connection() as connection:
                    connection.send_messages(emails)
            except Exception as e:
                JobResult.objects.create(
                    job=job,
                    messages=[
                        gettext('An error has occurred while sending emails'),
                        gettext('Original error: {}').format(e),
                    ],
                )
Beispiel #20
0
def message(**options):
    options.update(base_options)
    email_message = EmailMessage(**options)
    return SparkPostMessage(email_message)
Beispiel #21
0
    def send(self, fail_silently=False, **kwargs):
        recipient_list = []
        recipient_bcc_list = []
        headers = kwargs.get('headers', {})
        attachments = kwargs.get('attachments', [])

        if isinstance(self.recipient, basestring):
            recipient_list = self.recipient.split(',')
            recipient_list = [recipient.strip() for recipient in recipient_list \
                              if recipient.strip() <> '']
        else:
            recipient_list = list(self.recipient)
        if isinstance(self.recipient_cc, basestring):
            recipient_cc_list = self.recipient_cc.split(',')
            recipient_cc_list = [recipient_cc.strip() for recipient_cc in recipient_cc_list if \
                                  recipient_cc.strip() <> '']
            recipient_list += recipient_cc_list
        else:
            recipient_list += list(self.recipient_cc)
        if isinstance(self.recipient_bcc, basestring):
            recipient_bcc_list = self.recipient_bcc.split(',')
            recipient_bcc_list = [recipient_bcc.strip() for recipient_bcc in recipient_bcc_list if \
                                   recipient_bcc.strip() <> '']
        else:
            recipient_bcc_list = list(self.recipient_bcc)

        if self.reply_to:
            headers['Reply-To'] = self.reply_to
        if not self.sender:
            self.sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        if self.sender_display:
            # Add quotes around display name to prevent errors on sending
            # When display name contains comma or other control characters,
            headers['From'] = '"%s"<%s>' % (self.sender_display, self.sender)
        if self.priority and self.priority == 1:
            headers['X-Priority'] = '1'
            headers['X-MSMail-Priority'] = 'High'

        # remove blocked from recipient_list and recipient_bcc_list
        temp_recipient_list = copy.copy(recipient_list)
        for e in temp_recipient_list:
            if self.is_blocked(e):
                recipient_list.remove(e)
        temp_recipient_bcc_list = copy.copy(recipient_bcc_list)
        for e in temp_recipient_bcc_list:
            if self.is_blocked(e):
                recipient_bcc_list.remove(e)

        if recipient_list or recipient_bcc_list:
            msg = EmailMessage(self.subject,
                               self.body,
                               self.sender,
                               recipient_list,
                               recipient_bcc_list,
                               headers=headers,
                               connection=kwargs.get('connection', None))
            if self.content_type == 'html' or self.content_type == self.CONTENT_TYPE_HTML:
                msg.content_subtype = 'html'
            if attachments:
                msg.attachments = attachments
            msg.send(fail_silently=fail_silently)
Beispiel #22
0
 def send_email(self, request, fail_silently=False):
     self.request = request
     return EmailMessage(**self.get_message_dict()).send(
         fail_silently=fail_silently)
Beispiel #23
0
def email(name, subject, mailid, file_path):
    email = EmailMessage("Respected, {}!!".format(name), subject, to=[mailid])

    email.attach_file(file_path)
    email.send()
    print("Email Sent")
Beispiel #24
0
def send_mail_async(self,
                    subject,
                    message,
                    from_email,
                    recipient_list,
                    messaging_event_id=None):
    """ Call with send_mail_async.delay(*args, **kwargs)
    - sends emails in the main celery queue
    - if sending fails, retry in 15 min
    - retry a maximum of 10 times
    """
    from corehq.util.soft_assert import soft_assert
    soft_assert('{}@dimagi.com'.format('skelly'))(all(
        recipient for recipient in recipient_list), 'Blank email addresses', {
            'subject': subject,
            'message': message,
            'recipients': recipient_list
        })

    recipient_list = [_f for _f in recipient_list if _f]

    # todo deal with recipients marked as bounced
    from dimagi.utils.django.email import get_valid_recipients, mark_subevent_bounced
    filtered_recipient_list = get_valid_recipients(recipient_list)
    bounced_recipients = list(
        set(recipient_list) - set(filtered_recipient_list))
    if bounced_recipients and messaging_event_id:
        mark_subevent_bounced(bounced_recipients, messaging_event_id)

    if not filtered_recipient_list:
        return

    headers = {}

    if settings.RETURN_PATH_EMAIL:
        headers['Return-Path'] = settings.RETURN_PATH_EMAIL

    if messaging_event_id is not None:
        headers[COMMCARE_MESSAGE_ID_HEADER] = messaging_event_id
    if settings.SES_CONFIGURATION_SET is not None:
        headers[SES_CONFIGURATION_SET_HEADER] = settings.SES_CONFIGURATION_SET

    try:
        message = EmailMessage(
            subject=subject,
            body=message,
            from_email=from_email,
            to=filtered_recipient_list,
            headers=headers,
        )
        return message.send()
    except SMTPDataError as e:
        # If the SES configuration has not been properly set up, resend the message
        if ("Configuration Set does not exist" in repr(e.smtp_error)
                and SES_CONFIGURATION_SET_HEADER in message.extra_headers):
            del message.extra_headers[SES_CONFIGURATION_SET_HEADER]
            message.send()
            notify_exception(None,
                             message="SES Configuration Set missing",
                             details={'error': e})
        else:
            raise
    except Exception as e:
        notify_exception(None,
                         message="Encountered error while sending email",
                         details={
                             'subject': subject,
                             'recipients': ', '.join(filtered_recipient_list),
                             'error': e,
                             'messaging_event_id': messaging_event_id,
                         })
        if messaging_event_id is not None:
            mark_subevent_gateway_error(messaging_event_id, e, retrying=True)
        try:
            self.retry(exc=e)
        except MaxRetriesExceededError:
            if messaging_event_id is not None:
                mark_subevent_gateway_error(messaging_event_id,
                                            e,
                                            retrying=False)