Ejemplo n.º 1
0
    def _get_and_send_report(self, language, emails):
        from corehq.apps.reports.views import get_scheduled_report_response, render_full_report_notification

        with localize(language):
            title = (
                _(DEFAULT_REPORT_NOTIF_SUBJECT)
                if self.email_subject == DEFAULT_REPORT_NOTIF_SUBJECT
                else self.email_subject
            )

            attach_excel = getattr(self, "attach_excel", False)
            content, excel_files = get_scheduled_report_response(
                self.owner, self.domain, self._id, attach_excel=attach_excel
            )
            slugs = [r.report_slug for r in self.configs]

            for email in emails:
                body = render_full_report_notification(None, content, email, self).content
                send_html_email_async.delay(
                    title,
                    email,
                    body,
                    email_from=settings.DEFAULT_FROM_EMAIL,
                    file_attachments=excel_files,
                    ga_track=True,
                    ga_tracking_info={"cd4": self.domain, "cd10": ", ".join(slugs)},
                )
Ejemplo n.º 2
0
    def _get_and_send_report(self, language, emails):
        from corehq.apps.reports.views import get_scheduled_report_response, render_full_report_notification

        with localize(language):
            title = (
                _(DEFAULT_REPORT_NOTIF_SUBJECT)
                if self.email_subject == DEFAULT_REPORT_NOTIF_SUBJECT
                else self.email_subject
            )

            attach_excel = getattr(self, 'attach_excel', False)
            content, excel_files = get_scheduled_report_response(
                self.owner, self.domain, self._id, attach_excel=attach_excel,
                send_only_active=True
            )

            # Will be False if ALL the ReportConfigs in the ReportNotification
            # have a start_date in the future.
            if content is False:
                return

            for email in emails:
                body = render_full_report_notification(None, content, email, self).content
                send_html_email_async.delay(
                    title, email, body,
                    email_from=settings.DEFAULT_FROM_EMAIL,
                    file_attachments=excel_files)
Ejemplo n.º 3
0
def _send_downgrade_warning(invoice, context):
    if invoice.is_customer_invoice:
        subject = _(
            "CommCare Alert: {}'s subscriptions will be downgraded to Community Plan after tomorrow!".format(
                invoice.account.name
            ))
        subscriptions_to_downgrade = _(
            "subscriptions on {}".format(invoice.account.name)
        )
        bcc = None
    else:
        subject = _(
            "CommCare Alert: {}'s subscription will be downgraded to Community Plan after tomorrow!".format(
                invoice.get_domain()
            ))
        subscriptions_to_downgrade = _(
            "subscription for {}".format(invoice.get_domain())
        )
        bcc = [settings.GROWTH_EMAIL]

    context.update({
        'subscriptions_to_downgrade': subscriptions_to_downgrade
    })
    send_html_email_async.delay(
        subject,
        invoice.contact_emails,
        render_to_string('accounting/email/downgrade_warning.html', context),
        render_to_string('accounting/email/downgrade_warning.txt', context),
        cc=[settings.ACCOUNTS_EMAIL],
        bcc=bcc,
        email_from=get_dimagi_from_email())
Ejemplo n.º 4
0
def activation_24hr_reminder_email():
    """
    Reminds inactive users registered 24 hrs ago to activate their account.
    """
    request_reminders = RegistrationRequest.get_requests_24hrs_ago()

    DNS_name = get_site_domain()

    for request in request_reminders:
        user = WebUser.get_by_username(request.new_user_username)
        registration_link = 'http://' + DNS_name + reverse(
            'registration_confirm_domain') + request.activation_guid + '/'
        email_context = {
            "domain": request.domain,
            "registration_link": registration_link,
            "full_name": user.full_name,
            "first_name": user.first_name,
            'url_prefix': '' if settings.STATIC_CDN else 'http://' + DNS_name,
        }

        message_plaintext = render_to_string(
            'registration/email/confirm_account_reminder.txt', email_context)
        message_html = render_to_string(
            'registration/email/confirm_account.html', email_context)
        subject = ugettext('Reminder to Activate your CommCare project')

        send_html_email_async.delay(
            subject, request.new_user_username, message_html,
            text_content=message_plaintext,
            email_from=settings.DEFAULT_FROM_EMAIL
        )
Ejemplo n.º 5
0
def _send_overdue_notice(invoice, context):
    send_html_email_async.delay(
        ugettext('CommCare Billing Statement 30 days Overdue for {}'.format(invoice.get_domain())),
        invoice.contact_emails,
        render_to_string('accounting/30_days.html', context),
        render_to_string('accounting/30_days.txt', context),
        cc=[settings.ACCOUNTS_EMAIL],
        email_from=get_dimagi_from_email())
Ejemplo n.º 6
0
def send_confirmation_email(invitation):
    invited_user = invitation.email
    subject = "%s accepted your invitation to CommCare HQ" % invited_user
    recipient = WebUser.get_by_user_id(invitation.invited_by).get_email()
    context = {"invited_user": invited_user}
    html_content = render_to_string("domain/email/invite_confirmation.html", context)
    text_content = render_to_string("domain/email/invite_confirmation.txt", context)
    send_html_email_async.delay(subject, recipient, html_content, text_content=text_content)
Ejemplo n.º 7
0
def _send_downgrade_notice(invoice, context):
    send_html_email_async.delay(
        ugettext('Oh no! Your CommCare subscription for {} has been downgraded'.format(invoice.get_domain())),
        invoice.contact_emails,
        render_to_string('accounting/downgrade.html', context),
        render_to_string('accounting/downgrade.txt', context),
        cc=[settings.ACCOUNTS_EMAIL],
        email_from=get_dimagi_from_email()
    )
Ejemplo n.º 8
0
def _send_downgrade_warning(invoice, context):
    send_html_email_async.delay(
        ugettext("CommCare Alert: {}'s subscription will be downgraded to Community Plan after tomorrow!".format(
            invoice.get_domain()
        )),
        invoice.contact_emails,
        render_to_string('accounting/downgrade_warning.html', context),
        render_to_string('accounting/downgrade_warning.txt', context),
        cc=[settings.ACCOUNTS_EMAIL],
        email_from=get_dimagi_from_email())
Ejemplo n.º 9
0
    def email_to_request(self):
        context = self.as_dict()

        html_content = render_to_string("{template}.html".format(template=self.TRANSFER_TO_EMAIL), context)
        text_content = render_to_string("{template}.txt".format(template=self.TRANSFER_TO_EMAIL), context)

        send_html_email_async.delay(
            _('Transfer of ownership for CommCare project space.'),
            self.to_user.email,
            html_content,
            text_content=text_content)
Ejemplo n.º 10
0
 def send_activation_email(self):
     url = absolute_reverse("orgs_accept_invitation",
                            args=[self.organization, self.get_id])
     params = {"organization": self.organization, "url": url,
               "inviter": self.get_inviter().formatted_name}
     text_content = render_to_string("orgs/email/org_invite.txt", params)
     html_content = render_to_string("orgs/email/org_invite.html", params)
     subject = 'Invitation from %s to join CommCareHQ' % self.get_inviter().formatted_name
     send_html_email_async.delay(subject, self.email, html_content,
                                 text_content=text_content,
                                 email_from=settings.DEFAULT_FROM_EMAIL)
Ejemplo n.º 11
0
    def _get_and_send_report(self, language, emails):
        from corehq.apps.reports.views import get_scheduled_report_response

        with localize(language):
            title = _("Scheduled report from CommCare HQ")
            attach_excel = getattr(self, 'attach_excel', False)
            body, excel_files = get_scheduled_report_response(
                self.owner, self.domain, self._id, attach_excel=attach_excel
            )
            for email in emails:
                send_html_email_async.delay(title, email, body.content,
                                            email_from=settings.DEFAULT_FROM_EMAIL,
                                            file_attachments=excel_files)
Ejemplo n.º 12
0
def _email_app_translations_discrepancies(msgs, email, app_name):
    html_content = ghdiff.default_css
    for sheet_name, msg in msgs.items():
        html_content += "<strong>{}</strong>".format(sheet_name) + msg

    subject = _("App Translations Discrepancies for {}").format(app_name)
    text_content = _("Hi, PFA file for discrepancies found for app translations.")
    html_attachment = {
        'title': "{} Discrepancies.html".format(app_name),
        'file_obj': io.StringIO(html_content),
        'mimetype': 'text/html',
    }
    send_html_email_async.delay(subject, email, text_content, file_attachments=[html_attachment])
Ejemplo n.º 13
0
def _send_overdue_notice(invoice, context):
    if invoice.is_customer_invoice:
        bcc = None
    else:
        bcc = [settings.GROWTH_EMAIL]
    send_html_email_async.delay(
        _('CommCare Billing Statement 30 days Overdue for {}'.format(context['domain_or_account'])),
        invoice.contact_emails,
        render_to_string('accounting/email/30_days.html', context),
        render_to_string('accounting/email/30_days.txt', context),
        cc=[settings.ACCOUNTS_EMAIL],
        bcc=bcc,
        email_from=get_dimagi_from_email())
Ejemplo n.º 14
0
def _send_downgrade_warning(invoice, context):
    send_html_email_async.delay(ugettext(
        "CommCare Alert: {}'s subscription will be downgraded to Community Plan after tomorrow!"
        .format(invoice.get_domain())),
                                invoice.contact_emails,
                                render_to_string(
                                    'accounting/downgrade_warning.html',
                                    context),
                                render_to_string(
                                    'accounting/downgrade_warning.txt',
                                    context),
                                cc=[settings.ACCOUNTS_EMAIL],
                                email_from=get_dimagi_from_email())
Ejemplo n.º 15
0
def _send_overdue_notice(invoice, context):
    if invoice.is_customer_invoice:
        bcc = None
    else:
        bcc = [settings.GROWTH_EMAIL]
    send_html_email_async.delay(
        _('CommCare Billing Statement 30 days Overdue for {}'.format(context['domain_or_account'])),
        invoice.contact_emails,
        render_to_string('accounting/email/30_days.html', context),
        render_to_string('accounting/email/30_days.txt', context),
        cc=[settings.ACCOUNTS_EMAIL],
        bcc=bcc,
        email_from=get_dimagi_from_email())
Ejemplo n.º 16
0
def _send_downgrade_notice(invoice, context):
    send_html_email_async.delay(_(
        'Oh no! Your CommCare subscription for {} has been downgraded'.format(
            invoice.get_domain())),
                                invoice.contact_emails,
                                render_to_string(
                                    'accounting/email/downgrade.html',
                                    context),
                                render_to_string(
                                    'accounting/email/downgrade.txt', context),
                                cc=[settings.ACCOUNTS_EMAIL],
                                bcc=[settings.GROWTH_EMAIL],
                                email_from=get_dimagi_from_email())
Ejemplo n.º 17
0
    def email_to_request(self):
        context = self.as_dict()

        html_content = render_to_string(
            "{template}.html".format(template=self.TRANSFER_TO_EMAIL), context)
        text_content = render_to_string(
            "{template}.txt".format(template=self.TRANSFER_TO_EMAIL), context)

        send_html_email_async.delay(
            _(u'Transfer of ownership for CommCare project space.'),
            self.to_user.email,
            html_content,
            text_content=text_content)
Ejemplo n.º 18
0
def send_confirmation_email(invitation):
    invited_user = invitation.email
    subject = '%s accepted your invitation to CommCare HQ' % invited_user
    recipient = WebUser.get_by_user_id(invitation.invited_by).get_email()
    context = {
        'invited_user': invited_user,
    }
    html_content = render_to_string('domain/email/invite_confirmation.html',
                                    context)
    text_content = render_to_string('domain/email/invite_confirmation.txt',
                                    context)
    send_html_email_async.delay(subject, recipient, html_content,
                                text_content=text_content)
Ejemplo n.º 19
0
def _email_app_translations_discrepancies(msgs, checker_messages, email,
                                          app_name, result_wb):
    """
    :param msgs: messages for app translation discrepancies
    :param checker_messages: messages for issues found by translation checker
    :param email: email to
    :param app_name: name of the application
    :param result_wb: result wb of translation checker to attach with the email
    """
    def form_email_content(msgs, checker_messages):
        if msgs:
            html_file_content = ghdiff.default_css
            for sheet_name, msg in msgs.items():
                html_file_content += "<strong>{}</strong>".format(
                    sheet_name) + msg
            text_content = _(
                "Hi, PFA file for discrepancies found for app translations."
            ) + "\n"
        else:
            html_file_content = None
            text_content = _(
                "Hi, No discrepancies found for app translations.") + "\n"
        if checker_messages:
            text_content += _(
                "Issues found with the workbook are as follows :") + "\n"
            text_content += '\n'.join([_(msg) for msg in checker_messages])
        else:
            text_content += _("No issues found with the workbook.")
        return html_file_content, text_content

    def attachment(title, content, mimetype='text/html'):
        return {'title': title, 'file_obj': content, 'mimetype': mimetype}

    subject = _("App Translations Discrepancies for {}").format(app_name)
    html_file_content, text_content = form_email_content(
        msgs, checker_messages)
    attachments = []
    if html_file_content:
        attachments.append(
            attachment("{} Discrepancies.html".format(app_name),
                       io.StringIO(html_file_content)))
    if result_wb:
        attachments.append(
            attachment("{} TranslationChecker.xlsx".format(app_name),
                       io.BytesIO(read_workbook_content_as_file(result_wb)),
                       result_wb.mime_type))

    send_html_email_async.delay(subject,
                                email,
                                linebreaksbr(text_content),
                                file_attachments=attachments)
Ejemplo n.º 20
0
def _email_app_translations_discrepancies(msgs, email, app_name):
    message = '\n\n'.join([
        """Sheet {}:
           {}""".format(sheet_name, '\n '.join(msgs[sheet_name]))
        for sheet_name in msgs if msgs.get(sheet_name)
    ])

    subject = "App Translations Discrepancies for {}".format(app_name)
    body = """Hi,
    Following discrepancies were found for app translations.

    {}""".format(message)

    send_html_email_async.delay(subject, email, linebreaksbr(body))
Ejemplo n.º 21
0
    def email_from_request(self):
        context = self.as_dict()
        context['settings_url'] = "{url_base}{path}".format(
            url_base=get_url_base(),
            path=reverse('transfer_domain_view', args=[self.domain]))

        html_content = render_to_string("{template}.html".format(template=self.TRANSFER_FROM_EMAIL), context)
        text_content = render_to_string("{template}.txt".format(template=self.TRANSFER_FROM_EMAIL), context)

        send_html_email_async.delay(
            _('Transfer of ownership for CommCare project space.'),
            self.from_user.email,
            html_content,
            text_content=text_content)
Ejemplo n.º 22
0
def _send_registry_email(for_domain, subject, template, context):
    recipients = {
        u.get_email()
        for u in WebUser.get_admins_by_domain(for_domain)
    }
    email_html = render_to_string(f'registry/email/{template}.html', context)
    email_plaintext = render_to_string(f'registry/email/{template}.txt',
                                       context)
    send_html_email_async.delay(
        subject,
        recipients,
        email_html,
        text_content=email_plaintext,
    )
Ejemplo n.º 23
0
    def email_from_request(self):
        context = self.as_dict()
        context['settings_url'] = u"{url_base}{path}".format(
            url_base=get_url_base(),
            path=reverse('transfer_domain_view', args=[self.domain]))

        html_content = render_to_string("{template}.html".format(template=self.TRANSFER_FROM_EMAIL), context)
        text_content = render_to_string("{template}.txt".format(template=self.TRANSFER_FROM_EMAIL), context)

        send_html_email_async.delay(
            _(u'Transfer of ownership for CommCare project space.'),
            self.from_user.email,
            html_content,
            text_content=text_content)
Ejemplo n.º 24
0
def run_data_pull(data_pull_slug, domain, month, location_id=None, email=None):
    subject = _('Custom ICDS Data Pull')
    try:
        filename = DataExporter(data_pull_slug,
                                "icds-ucr-citus",
                                month=month,
                                location_id=location_id).export()
    except Exception:
        if email:
            message = _("""
                            Hi,
                            Could not generate the requested data pull.
                            The error has been notified. Please report as an issue for quicker followup
                        """)
            send_html_email_async.delay(subject, [email],
                                        message,
                                        email_from=settings.DEFAULT_FROM_EMAIL)
        raise
    else:
        if email and filename:
            db = get_blob_db()
            download_id = DownloadBase.new_id_prefix + make_uuid()
            with open(filename, 'rb') as _file:
                db.put(
                    _file,
                    domain=domain,
                    parent_id=domain,
                    type_code=CODES.data_export,
                    key=download_id,
                    timeout=24 * 60,
                )
            exposed_download = expose_blob_download(
                filename,
                expiry=24 * 60 * 60,
                mimetype=Format.from_format(Format.ZIP).mimetype,
                content_disposition=safe_filename_header(filename),
                download_id=download_id)
            os.remove(filename)
            path = reverse(
                'retrieve_download',
                kwargs={'download_id': exposed_download.download_id})
            link = f"{web.get_url_base()}{path}?get_file"
            message = _("""
            Hi,
            Please download the data from {link}.
            The data is available only for 24 hours.
            """).format(link=link)
            send_html_email_async.delay(subject, [email],
                                        message,
                                        email_from=settings.DEFAULT_FROM_EMAIL)
Ejemplo n.º 25
0
def send_subscription_change_alert(domain, new_subscription, old_subscription,
                                   internal_change):

    billing_account = (new_subscription.account if new_subscription else
                       old_subscription.account if old_subscription else None)
    # this can be None, though usually this will be initiated
    # by an http request
    request = get_request()
    email_context = {
        'domain':
        domain,
        'domain_url':
        get_default_domain_url(domain),
        'old_plan':
        old_subscription.plan_version if old_subscription else None,
        'new_plan':
        new_subscription.plan_version if new_subscription else None,
        'old_subscription':
        old_subscription,
        'new_subscription':
        new_subscription,
        'billing_account':
        billing_account,
        'username':
        request.couch_user.username
        if getattr(request, 'couch_user', None) else None,
        'referer':
        request.META.get('HTTP_REFERER') if request else None,
    }
    email_subject = "{env}Subscription Change Alert: {domain} from {old_plan} to {new_plan}".format(
        env=("[{}] ".format(settings.SERVER_ENVIRONMENT.upper())
             if settings.SERVER_ENVIRONMENT == "staging" else ""),
        domain=email_context['domain'],
        old_plan=email_context['old_plan'],
        new_plan=email_context['new_plan'],
    )

    sub_change_email_address = (settings.INTERNAL_SUBSCRIPTION_CHANGE_EMAIL
                                if internal_change else
                                settings.SUBSCRIPTION_CHANGE_EMAIL)

    send_html_email_async.delay(
        email_subject,
        sub_change_email_address,
        render_to_string('accounting/subscription_change_email.html',
                         email_context),
        text_content=render_to_string(
            'accounting/subscription_change_email.txt', email_context),
    )
Ejemplo n.º 26
0
def send_upload_fixture_complete_email(email, domain, time_start, time_end,
                                       messages):
    context = {
        "username": email,
        "domain": domain,
        "time_start": time_start,
        "time_end": time_end,
        "messages": messages
    }
    send_html_email_async.delay(
        "Your fixture upload is complete!",
        email,
        render_to_string('fixtures/upload_complete.html', context),
        render_to_string('fixtures/upload_complete.txt', context),
        email_from=settings.DEFAULT_FROM_EMAIL)
    return
Ejemplo n.º 27
0
 def send_handoff_email(self):
     partner_contact = self.internal_settings_form.cleaned_data['partner_contact']
     dimagi_contact = self.internal_settings_form.cleaned_data['dimagi_contact']
     recipients = [partner_contact, dimagi_contact]
     params = {'contact_name': CouchUser.get_by_username(dimagi_contact).human_friendly_name}
     send_html_email_async.delay(
         subject="Project Support Transition",
         recipient=recipients,
         html_content=render_to_string(
             "domain/email/support_handoff.html", params),
         text_content=render_to_string(
             "domain/email/support_handoff.txt", params),
         email_from=settings.SUPPORT_EMAIL,
     )
     messages.success(self.request,
                      _("Sent hand-off email to {}.").format(" and ".join(recipients)))
Ejemplo n.º 28
0
def _notify_failure_to_user(hosted_ccz, build, user_email):
    build_profile = hosted_ccz.build_profile
    profile_name = build_profile.get('name') if build_profile else None
    content = "Hi,\n"\
              "CCZ could not be created for the following request:\n" \
              "App: {app}\n" \
              "Version: {version}\n" \
              "Profile: {profile}\n" \
              "Link: {link}" \
              "".format(app=build.name, version=hosted_ccz.version, profile=profile_name,
                        link=hosted_ccz.link.identifier)
    send_html_email_async.delay(
        "CCZ Hosting setup failed for app {app} in project {domain}".format(
            app=build.name,
            domain=hosted_ccz.domain,
        ), user_email, linebreaksbr(content))
Ejemplo n.º 29
0
 def send_handoff_email(self):
     partner_contact = self.internal_settings_form.cleaned_data['partner_contact']
     dimagi_contact = self.internal_settings_form.cleaned_data['dimagi_contact']
     recipients = [partner_contact, dimagi_contact]
     params = {'contact_name': CouchUser.get_by_username(dimagi_contact).human_friendly_name}
     send_html_email_async.delay(
         subject="Project Support Transition",
         recipient=recipients,
         html_content=render_to_string(
             "domain/email/support_handoff.html", params),
         text_content=render_to_string(
             "domain/email/support_handoff.txt", params),
         email_from=settings.SUPPORT_EMAIL,
     )
     messages.success(self.request,
                      _("Sent hand-off email to {}.").format(" and ".join(recipients)))
Ejemplo n.º 30
0
def send_domain_registration_email(recipient, domain_name, guid):
    DNS_name = get_site_domain()
    registration_link = 'http://' + DNS_name + reverse(
        'registration_confirm_domain') + guid + '/'

    message_plaintext = u"""
Welcome to CommCareHQ!

Please click this link:
{registration_link}
to activate your new project.  You will not be able to use your project until you have confirmed this email address.

Project name: "{domain}"

Username:  "******"

""" + REGISTRATION_EMAIL_BODY_PLAINTEXT

    message_html = u"""
<h1>Welcome to CommCare HQ!</h1>
<p>Please <a href="{registration_link}">go here to activate your new project</a>.  You will not be able to use your project until you have confirmed this email address.</p>
<p><strong>Project name:</strong> {domain}</p>
<p><strong>Username:</strong> {username}</p>
""" + REGISTRATION_EMAIL_BODY_HTML

    params = {
        "domain": domain_name,
        "pricing_link": PRICING_LINK,
        "registration_link": registration_link,
        "username": recipient,
        "users_link": USERS_LINK,
        "wiki_link": WIKI_LINK,
    }
    message_plaintext = message_plaintext.format(**params)
    message_html = message_html.format(**params)

    subject = 'Welcome to CommCare HQ!'.format(**locals())

    try:
        send_html_email_async.delay(subject,
                                    recipient,
                                    message_html,
                                    text_content=message_plaintext,
                                    email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception:
        logging.warning("Can't send email, but the message was:\n%s" %
                        message_plaintext)
Ejemplo n.º 31
0
    def _get_and_send_report(self, language, emails):
        from corehq.apps.reports.views import get_scheduled_report_response

        with localize(language):
            title = (
                _(DEFAULT_REPORT_NOTIF_SUBJECT)
                if self.email_subject == DEFAULT_REPORT_NOTIF_SUBJECT
                else self.email_subject
            )
            attach_excel = getattr(self, 'attach_excel', False)
            body, excel_files = get_scheduled_report_response(
                self.owner, self.domain, self._id, attach_excel=attach_excel
            )
            for email in emails:
                send_html_email_async.delay(title, email, body.content,
                                            email_from=settings.DEFAULT_FROM_EMAIL,
                                            file_attachments=excel_files)
Ejemplo n.º 32
0
def _email_app_translations_discrepancies(msgs, email, app_name):
    html_content = ghdiff.default_css
    for sheet_name, msg in msgs.items():
        html_content += "<strong>{}</strong>".format(sheet_name) + msg

    subject = _("App Translations Discrepancies for {}").format(app_name)
    text_content = _(
        "Hi, PFA file for discrepancies found for app translations.")
    html_attachment = {
        'title': "{} Discrepancies.html".format(app_name),
        'file_obj': io.StringIO(html_content),
        'mimetype': 'text/html',
    }
    send_html_email_async.delay(subject,
                                email,
                                text_content,
                                file_attachments=[html_attachment])
Ejemplo n.º 33
0
def _notification_email_on_publish(domain, snapshot, published_by):
    params = {"domain": domain, "snapshot": snapshot,
              "published_by": published_by, "url_base": get_site_domain()}
    text_content = render_to_string(
        "domain/email/published_app_notification.txt", params)
    html_content = render_to_string(
        "domain/email/published_app_notification.html", params)
    recipients = settings.EXCHANGE_NOTIFICATION_RECIPIENTS
    subject = "New App on Exchange: %s" % snapshot.title
    try:
        for recipient in recipients:
            send_html_email_async.delay(subject, recipient, html_content,
                                        text_content=text_content,
                                        email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception:
        logging.warning("Can't send notification email, "
                        "but the message was:\n%s" % text_content)
Ejemplo n.º 34
0
def _notification_email_on_publish(domain, snapshot, published_by):
    params = {"domain": domain, "snapshot": snapshot,
              "published_by": published_by, "url_base": get_site_domain()}
    text_content = render_to_string(
        "domain/email/published_app_notification.txt", params)
    html_content = render_to_string(
        "domain/email/published_app_notification.html", params)
    recipients = settings.EXCHANGE_NOTIFICATION_RECIPIENTS
    subject = "New App on Exchange: %s" % snapshot.title
    try:
        for recipient in recipients:
            send_html_email_async.delay(subject, recipient, html_content,
                                        text_content=text_content,
                                        email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception:
        logging.warning("Can't send notification email, "
                        "but the message was:\n%s" % text_content)
Ejemplo n.º 35
0
 def send_activation_email(self):
     url = absolute_reverse("orgs_accept_invitation",
                            args=[self.organization, self.get_id])
     params = {
         "organization": self.organization,
         "url": url,
         "inviter": self.get_inviter().formatted_name
     }
     text_content = render_to_string("orgs/email/org_invite.txt", params)
     html_content = render_to_string("orgs/email/org_invite.html", params)
     subject = 'Invitation from %s to join CommCareHQ' % self.get_inviter(
     ).formatted_name
     send_html_email_async.delay(subject,
                                 self.email,
                                 html_content,
                                 text_content=text_content,
                                 email_from=settings.DEFAULT_FROM_EMAIL)
Ejemplo n.º 36
0
def _send_overdue_notice(invoice, communication_model, context):
    if invoice.is_customer_invoice:
        bcc = None
    else:
        bcc = [settings.GROWTH_EMAIL]
    send_html_email_async.delay(
        _('CommCare Billing Statement 30 days Overdue for {}'.format(context['domain_or_account'])),
        invoice.get_contact_emails(include_domain_admins=True, filter_out_dimagi=True),
        render_to_string('accounting/email/30_days.html', context),
        render_to_string('accounting/email/30_days.txt', context),
        cc=[settings.ACCOUNTS_EMAIL],
        bcc=bcc,
        email_from=get_dimagi_from_email()
    )
    communication_model.objects.create(
        invoice=invoice,
        communication_type=CommunicationType.OVERDUE_INVOICE,
    )
Ejemplo n.º 37
0
def update_linked_app_and_notify(domain, app_id, master_app_id, user_id, email):
    app = get_current_app(domain, app_id)
    subject = _("Update Status for linked app %s") % app.name
    try:
        update_linked_app(app, master_app_id, user_id)
    except (AppLinkError, MultimediaMissingError) as e:
        message = str(e)
    except Exception:
        # Send an email but then crash the process
        # so we know what the error was
        send_html_email_async.delay(subject, email, _(
            "Something went wrong updating your linked app. "
            "Our team has been notified and will monitor the situation. "
            "Please try again, and if the problem persists report it as an issue."))
        raise
    else:
        message = _("Your linked application was successfully updated to the latest version.")
    send_html_email_async.delay(subject, email, message)
Ejemplo n.º 38
0
def pull_missing_multimedia_for_app_and_notify(domain, app_id, email):
    app = get_app(domain, app_id)
    subject = _("Update Status for linked app %s missing multimedia pull") % app.name
    try:
        pull_missing_multimedia_for_app(app)
    except MultimediaMissingError as e:
        message = str(e)
    except Exception:
        # Send an email but then crash the process
        # so we know what the error was
        send_html_email_async.delay(subject, email, _(
            "Something went wrong while pulling multimedia for your linked app. "
            "Our team has been notified and will monitor the situation. "
            "Please try again, and if the problem persists report it as an issue."))
        raise
    else:
        message = _("Multimedia was successfully updated for the linked app.")
    send_html_email_async.delay(subject, email, message)
Ejemplo n.º 39
0
def update_linked_app_and_notify(domain, app_id, user_id, email):
    app = get_current_app(domain, app_id)
    subject = _("Update Status for linked app %s") % app.name
    try:
        update_linked_app(app, user_id)
    except (AppLinkError, MultimediaMissingError) as e:
        message = six.text_type(e)
    except Exception:
        # Send an email but then crash the process
        # so we know what the error was
        send_html_email_async.delay(subject, email, _(
            "Something went wrong updating your linked app. "
            "Our team has been notified and will monitor the situation. "
            "Please try again, and if the problem persists report it as an issue."))
        raise
    else:
        message = _("Your linked application was successfully updated to the latest version.")
    send_html_email_async.delay(subject, email, message)
Ejemplo n.º 40
0
def send_monthly_sms_report():
    subject = _('Monthly SMS report')
    recipients = [
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**'
    ]
    try:
        start_date = date.today().replace(day=1) - relativedelta(months=1)
        first_day, last_day = calendar.monthrange(start_date.year,
                                                  start_date.month)
        end_date = start_date.replace(day=last_day)
        filename = call_command('get_icds_sms_usage', 'icds-cas',
                                str(start_date), str(end_date))
        with open(filename, 'rb') as f:
            cached_download = expose_cached_download(
                f.read(),
                expiry=24 * 60 * 60,
                file_extension=file_extention_from_filename(filename),
                mimetype=Format.from_format(Format.XLS_2007).mimetype,
                content_disposition='attachment; filename="%s"' % filename)
        path = reverse('retrieve_download',
                       kwargs={'download_id': cached_download.download_id})
        link = f"{web.get_url_base()}{path}?get_file"
        message = _("""
        Hi,
        Please download the sms report for last month at {link}.
        The report is available only till midnight today.
        """).format(link=link)
        send_html_email_async.delay(subject,
                                    recipients,
                                    message,
                                    email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception as e:
        message = _("""
            Hi,
            Could not generate the monthly SMS report for ICDS.
            The error has been notified. Please report as an issue for quick followup
        """)
        send_html_email_async.delay(subject,
                                    recipients,
                                    message,
                                    email_from=settings.DEFAULT_FROM_EMAIL)
        raise e
Ejemplo n.º 41
0
def send_domain_registration_email(recipient, domain_name, guid):
    DNS_name = get_site_domain()
    registration_link = 'http://' + DNS_name + reverse('registration_confirm_domain') + guid + '/'

    message_plaintext = u"""
Welcome to CommCareHQ!

Please click this link:
{registration_link}
to activate your new project.  You will not be able to use your project until you have confirmed this email address.

Project name: "{domain}"

Username:  "******"

""" + REGISTRATION_EMAIL_BODY_PLAINTEXT

    message_html = u"""
<h1>Welcome to CommCare HQ!</h1>
<p>Please <a href="{registration_link}">go here to activate your new project</a>.  You will not be able to use your project until you have confirmed this email address.</p>
<p><strong>Project name:</strong> {domain}</p>
<p><strong>Username:</strong> {username}</p>
""" + REGISTRATION_EMAIL_BODY_HTML

    params = {
        "domain": domain_name,
        "pricing_link": PRICING_LINK,
        "registration_link": registration_link,
        "username": recipient,
        "users_link": USERS_LINK,
        "wiki_link": WIKI_LINK,
    }
    message_plaintext = message_plaintext.format(**params)
    message_html = message_html.format(**params)

    subject = 'Welcome to CommCare HQ!'.format(**locals())

    try:
        send_html_email_async.delay(subject, recipient, message_html,
                                    text_content=message_plaintext,
                                    email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception:
        logging.warning("Can't send email, but the message was:\n%s" % message_plaintext)
Ejemplo n.º 42
0
def send_idp_cert_expires_reminder_emails(num_days):
    """
    Sends a reminder email to the enterprise admin email addresses specified on
    the IdP's owner account for any IdPs with certificates that will expire on
    the date `num_days` from today.

    :param num_days: Query IdP certs expiring `num_days` from today.
    """
    today = datetime.datetime.utcnow().date()
    date_in_n_days = today + datetime.timedelta(days=num_days)
    day_after_that = date_in_n_days + datetime.timedelta(days=1)
    queryset = IdentityProvider.objects.filter(
        protocol=IdentityProviderProtocol.SAML,
        is_active=True,
        date_idp_cert_expiration__gte=date_in_n_days,
        date_idp_cert_expiration__lt=day_after_that,
    )
    for idp in queryset.all():
        context = get_idp_cert_expiration_email_context(idp)
        if not context["to"]:
            log.error(f"no admin email addresses for IdP: {idp}")
        try:
            for send_to in context["to"]:
                send_html_email_async.delay(
                    context["subject"],
                    send_to,
                    context["html"],
                    text_content=context["plaintext"],
                    email_from=context["from"],
                    bcc=context["bcc"],
                )
                log.info(
                    "Sent %(num_days)s-day certificate expiration reminder "
                    "email for %(idp_name)s to %(send_to)s." % {
                        "num_days": num_days,
                        "idp_name": idp.name,
                        "send_to": send_to,
                    })
        except Exception as exc:
            log.error(
                f"Failed to send cert reminder email for IdP {idp}: {exc!s}",
                exc_info=True,
            )
Ejemplo n.º 43
0
def send_global_domain_registration_email(requesting_user, domain_name):
    DNS_name = get_site_domain()
    registration_link = 'http://' + DNS_name + reverse("domain_homepage",
                                                       args=[domain_name])

    message_plaintext = u"""
Hello {name},

You have successfully created and activated the project "{domain}" for the CommCare HQ user "{username}".

You may access your project by following this link: {registration_link}

""" + REGISTRATION_EMAIL_BODY_PLAINTEXT

    message_html = u"""
<h1>New project "{domain}" created!</h1>
<p>Hello {name},</p>
<p>You may now <a href="{registration_link}">visit your newly created project</a> with the CommCare HQ User <strong>{username}</strong>.</p>
""" + REGISTRATION_EMAIL_BODY_HTML

    params = {
        "name": requesting_user.first_name,
        "domain": domain_name,
        "pricing_link": PRICING_LINK,
        "registration_link": registration_link,
        "username": requesting_user.email,
        "users_link": USERS_LINK,
        "wiki_link": WIKI_LINK,
    }
    message_plaintext = message_plaintext.format(**params)
    message_html = message_html.format(**params)

    subject = 'CommCare HQ: New project created!'.format(**locals())

    try:
        send_html_email_async.delay(subject,
                                    requesting_user.email,
                                    message_html,
                                    text_content=message_plaintext,
                                    email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception:
        logging.warning("Can't send email, but the message was:\n%s" %
                        message_plaintext)
Ejemplo n.º 44
0
    def transfer_domain(self, by_user, *args, transfer_via=None, **kwargs):

        self.confirm_time = datetime.utcnow()
        if 'ip' in kwargs:
            self.confirm_ip = kwargs['ip']

        self.from_user.transfer_domain_membership(self.domain,
                                                  self.to_user,
                                                  is_admin=True)
        self.from_user.save()
        if by_user:
            log_user_change(by_domain=self.domain,
                            for_domain=self.domain,
                            couch_user=self.from_user,
                            changed_by_user=by_user,
                            changed_via=transfer_via,
                            change_messages=UserChangeMessage.domain_removal(
                                self.domain))
            log_user_change(by_domain=self.domain,
                            for_domain=self.domain,
                            couch_user=self.to_user,
                            changed_by_user=by_user,
                            changed_via=transfer_via,
                            change_messages=UserChangeMessage.domain_addition(
                                self.domain))
        self.to_user.save()
        self.active = False
        self.save()

        html_content = render_to_string(
            "{template}.html".format(template=self.DIMAGI_CONFIRM_EMAIL),
            self.as_dict())
        text_content = render_to_string(
            "{template}.txt".format(template=self.DIMAGI_CONFIRM_EMAIL),
            self.as_dict())

        send_html_email_async.delay(
            _('There has been a transfer of ownership of {domain}').format(
                domain=self.domain),
            settings.SUPPORT_EMAIL,
            html_content,
            text_content=text_content,
        )
Ejemplo n.º 45
0
def send_domain_registration_email(recipient, domain_name, guid, full_name):
    DNS_name = get_site_domain()
    registration_link = 'http://' + DNS_name + reverse(
        'registration_confirm_domain') + guid + '/'

    params = {
        "domain":
        domain_name,
        "pricing_link":
        PRICING_LINK,
        "registration_link":
        registration_link,
        "full_name":
        full_name,
        "forum_link":
        FORUM_LINK,
        "wiki_link":
        WIKI_LINK,
        'url_prefix':
        '' if settings.STATIC_CDN else 'http://' + DNS_name,
        "is_mobile_experience":
        (toggles.MOBILE_SIGNUP_REDIRECT_AB_TEST_CONTROLLER.enabled(
            recipient, toggles.NAMESPACE_USER)
         and toggles.MOBILE_SIGNUP_REDIRECT_AB_TEST.enabled(
             recipient, toggles.NAMESPACE_USER))
    }
    message_plaintext = render_to_string(
        'registration/email/confirm_account.txt', params)
    message_html = render_to_string('registration/email/confirm_account.html',
                                    params)

    subject = ugettext('Activate your CommCare project')

    try:
        send_html_email_async.delay(subject,
                                    recipient,
                                    message_html,
                                    text_content=message_plaintext,
                                    email_from=settings.DEFAULT_FROM_EMAIL,
                                    ga_track=True)
    except Exception:
        logging.warning("Can't send email, but the message was:\n%s" %
                        message_plaintext)
Ejemplo n.º 46
0
def send_custom_sms_report(start_date: str, end_date: str, email: str,
                           domain: str):
    subject = _('Monthly SMS report')
    recipients = [email]

    try:
        filename = call_command('get_icds_sms_usage', 'icds-cas', start_date,
                                end_date)

        with open(filename, 'rb') as f:
            cached_download = expose_cached_download(
                f.read(),
                expiry=24 * 60 * 60,
                file_extension=file_extention_from_filename(filename),
                mimetype=Format.from_format(Format.XLS_2007).mimetype,
                content_disposition='attachment; filename="%s"' % filename)
            path = reverse('retrieve_download',
                           kwargs={'download_id': cached_download.download_id})
            link = f"{web.get_url_base()}{path}?get_file"
            message = _("""
            Hi,
            Please download the sms report for time frame {start_date} to {end_date} (inclusive) at {link}.
            The report is available only for next 24 hours.
            """).format(link=link, start_date=start_date, end_date=end_date)
            send_html_email_async.delay(subject,
                                        recipients,
                                        message,
                                        email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception as e:
        message = _("""
            Hi,
            Could not generate the custom SMS report for ICDS.
            The error has been notified. Please report as an issue for quick followup
        """)
        send_html_email_async.delay(subject,
                                    recipients,
                                    message,
                                    email_from=settings.DEFAULT_FROM_EMAIL)
        raise e
    finally:
        report_tracker = CustomSMSReportTracker(domain)
        report_tracker.remove_report(start_date, end_date)
Ejemplo n.º 47
0
def mass_email(request):
    if not request.couch_user.is_staff:
        raise Http404()

    if request.method == "POST":
        form = EmailForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['email_subject']
            body = form.cleaned_data['email_body']
            real_email = form.cleaned_data['real_email']

            if real_email:
                recipients = WebUser.view(
                    'users/mailing_list_emails',
                    reduce=False,
                    include_docs=True,
                ).all()
            else:
                recipients = [request.couch_user]

            for recipient in recipients:
                params = {
                    'email_body': body,
                    'user_id': recipient.get_id,
                    'unsub_url': get_url_base() +
                                 reverse('unsubscribe', args=[recipient.get_id])
                }
                text_content = render_to_string("hqadmin/email/mass_email_base.txt", params)
                html_content = render_to_string("hqadmin/email/mass_email_base.html", params)

                send_html_email_async.delay(subject, recipient.email, html_content, text_content,
                                email_from=settings.DEFAULT_FROM_EMAIL)

            messages.success(request, 'Your email(s) were sent successfully.')

    else:
        form = EmailForm()

    context = get_hqadmin_base_context(request)
    context['hide_filters'] = True
    context['form'] = form
    return render(request, "hqadmin/mass_email.html", context)
Ejemplo n.º 48
0
    def _get_and_send_report(self, language, emails):
        from corehq.apps.reports.views import get_scheduled_report_response, render_full_report_notification

        with localize(language):
            title = (_(DEFAULT_REPORT_NOTIF_SUBJECT) if self.email_subject
                     == DEFAULT_REPORT_NOTIF_SUBJECT else self.email_subject)

            attach_excel = getattr(self, 'attach_excel', False)
            content, excel_files = get_scheduled_report_response(
                self.owner, self.domain, self._id, attach_excel=attach_excel)
            slugs = [r.report_slug for r in self.configs]

            for email in emails:
                body = render_full_report_notification(None, content, email,
                                                       self).content
                send_html_email_async.delay(
                    title,
                    email,
                    body,
                    email_from=settings.DEFAULT_FROM_EMAIL,
                    file_attachments=excel_files)
Ejemplo n.º 49
0
def send_global_domain_registration_email(requesting_user, domain_name):
    DNS_name = get_site_domain()
    registration_link = 'http://' + DNS_name + reverse("domain_homepage", args=[domain_name])

    message_plaintext = u"""
Hello {name},

You have successfully created and activated the project "{domain}" for the CommCare HQ user "{username}".

You may access your project by following this link: {registration_link}

""" + REGISTRATION_EMAIL_BODY_PLAINTEXT

    message_html = u"""
<h1>New project "{domain}" created!</h1>
<p>Hello {name},</p>
<p>You may now <a href="{registration_link}">visit your newly created project</a> with the CommCare HQ User <strong>{username}</strong>.</p>
""" + REGISTRATION_EMAIL_BODY_HTML

    params = {
        "name": requesting_user.first_name,
        "domain": domain_name,
        "pricing_link": PRICING_LINK,
        "registration_link": registration_link,
        "username": requesting_user.email,
        "users_link": USERS_LINK,
        "wiki_link": WIKI_LINK,
    }
    message_plaintext = message_plaintext.format(**params)
    message_html = message_html.format(**params)

    subject = 'CommCare HQ: New project created!'.format(**locals())

    try:
        send_html_email_async.delay(subject, requesting_user.email, message_html,
                                    text_content=message_plaintext,
                                    email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception:
        logging.warning("Can't send email, but the message was:\n%s" % message_plaintext)
Ejemplo n.º 50
0
def send_mobile_experience_reminder(recipient, full_name):
    url = absolute_reverse("login")

    params = {
        "full_name": full_name,
        "url": url,
        'url_prefix': get_static_url_prefix(),
    }
    message_plaintext = render_to_string(
        'registration/email/mobile_signup_reminder.txt', params)
    message_html = render_to_string(
        'registration/email/mobile_signup_reminder.html', params)

    subject = ugettext('Visit CommCareHQ on your computer!')

    try:
        send_html_email_async.delay(subject, recipient, message_html,
                                    text_content=message_plaintext,
                                    email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception:
        logging.warning(
            "Can't send email, but the message was:\n%s" % message_plaintext)
        raise
Ejemplo n.º 51
0
def send_mobile_experience_reminder(recipient, full_name):
    url = absolute_reverse("login")

    params = {
        "full_name": full_name,
        "url": url,
        'url_prefix': '' if settings.STATIC_CDN else 'http://' + get_site_domain(),
    }
    message_plaintext = render_to_string(
        'registration/email/mobile_signup_reminder.txt', params)
    message_html = render_to_string(
        'registration/email/mobile_signup_reminder.html', params)

    subject = ugettext('Visit CommCareHQ on your computer!')

    try:
        send_html_email_async.delay(subject, recipient, message_html,
                                    text_content=message_plaintext,
                                    email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception:
        logging.warning(
            "Can't send email, but the message was:\n%s" % message_plaintext)
        raise
Ejemplo n.º 52
0
def send_subscription_change_alert(domain, new_subscription, old_subscription, internal_change):

    billing_account = (
        new_subscription.account if new_subscription else
        old_subscription.account if old_subscription else None
    )
    # this can be None, though usually this will be initiated
    # by an http request
    request = get_request()
    email_context = {
        'domain': domain,
        'domain_url': get_default_domain_url(domain),
        'old_plan': old_subscription.plan_version if old_subscription else None,
        'new_plan': new_subscription.plan_version if new_subscription else None,
        'old_subscription': old_subscription,
        'new_subscription': new_subscription,
        'billing_account': billing_account,
        'username': request.couch_user.username if getattr(request, 'couch_user', None) else None,
        'referer': request.META.get('HTTP_REFERER') if request else None,
    }
    email_subject = "{env}Subscription Change Alert: {domain} from {old_plan} to {new_plan}".format(
        env=("[{}] ".format(settings.SERVER_ENVIRONMENT.upper())
             if settings.SERVER_ENVIRONMENT == "staging" else ""),
        domain=email_context['domain'],
        old_plan=email_context['old_plan'],
        new_plan=email_context['new_plan'],
    )

    sub_change_email_address = (settings.INTERNAL_SUBSCRIPTION_CHANGE_EMAIL
                                if internal_change else settings.SUBSCRIPTION_CHANGE_EMAIL)

    send_html_email_async.delay(
        email_subject,
        sub_change_email_address,
        render_to_string('accounting/email/subscription_change.html', email_context),
        text_content=render_to_string('accounting/email/subscription_change.txt', email_context),
    )
Ejemplo n.º 53
0
def send_domain_registration_email(recipient, domain_name, guid, full_name, first_name):
    DNS_name = get_site_domain()
    registration_link = 'http://' + DNS_name + reverse('registration_confirm_domain') + guid + '/'
    params = {
        "domain": domain_name,
        "pricing_link": PRICING_LINK,
        "registration_link": registration_link,
        "full_name": full_name,
        "first_name": first_name,
        "forum_link": FORUM_LINK,
        "wiki_link": WIKI_LINK,
        'url_prefix': '' if settings.STATIC_CDN else 'http://' + DNS_name,
    }
    message_plaintext = render_to_string('registration/email/confirm_account.txt', params)
    message_html = render_to_string('registration/email/confirm_account.html', params)

    subject = ugettext('Activate your CommCare project')

    try:
        send_html_email_async.delay(subject, recipient, message_html,
                                    text_content=message_plaintext,
                                    email_from=settings.DEFAULT_FROM_EMAIL)
    except Exception:
        logging.warning("Can't send email, but the message was:\n%s" % message_plaintext)
Ejemplo n.º 54
0
    def transfer_domain(self, *args, **kwargs):

        self.confirm_time = datetime.utcnow()
        if 'ip' in kwargs:
            self.confirm_ip = kwargs['ip']

        self.from_user.transfer_domain_membership(self.domain, self.to_user, is_admin=True)
        self.from_user.save()
        self.to_user.save()
        self.active = False
        self.save()

        html_content = render_to_string(
            "{template}.html".format(template=self.DIMAGI_CONFIRM_EMAIL),
            self.as_dict())
        text_content = render_to_string(
            "{template}.txt".format(template=self.DIMAGI_CONFIRM_EMAIL),
            self.as_dict())

        send_html_email_async.delay(
            _('There has been a transfer of ownership of {domain}').format(
                domain=self.domain), self.DIMAGI_CONFIRM_ADDRESS,
            html_content, text_content=text_content
        )