def send_autopay_failed(invoice, payment_method): subscription = invoice.subscription auto_payer = subscription.account.auto_pay_user payment_method = StripePaymentMethod.objects.get(web_user=auto_payer) autopay_card = payment_method.get_autopay_card(subscription.account) try: recipient = WebUser.get_by_username(auto_payer).get_email() except ResourceNotFound: recipient = auto_payer domain = invoice.get_domain() context = { 'domain': domain, 'subscription_plan': subscription.plan_version.plan.name, 'billing_date': datetime.date.today(), 'invoice_number': invoice.invoice_number, 'autopay_card': autopay_card, 'domain_url': absolute_reverse('dashboard_default', args=[domain]), 'billing_info_url': absolute_reverse('domain_update_billing_info', args=[domain]), 'support_email': settings.INVOICING_CONTACT_EMAIL, } template_html = 'accounting/autopay_failed_email.html' template_plaintext = 'accounting/autopay_failed_email.txt' send_HTML_email( subject="Subscription Payment for CommCare Invoice %s was declined" % invoice.invoice_number, recipient=recipient, html_content=render_to_string(template_html, context), text_content=render_to_string(template_plaintext, context), email_from=get_dimagi_from_email_by_product(subscription.plan_version.product_rate.product.product_type), )
def send_purchase_receipt(payment_record, core_product, template_html, template_plaintext, additional_context): email = payment_record.payment_method.billing_admin.web_user try: web_user = WebUser.get_by_username(email) name = web_user.first_name except ResourceNotFound: logger.error( "[BILLING] Strange. A payment attempt was made by a user that " "we can't seem to find! %s" % email ) name = email context = { 'name': name, 'amount': fmt_dollar_amount(payment_record.amount), 'project': payment_record.payment_method.billing_admin.domain, 'date_paid': payment_record.date_created.strftime('%d %B %Y'), 'product': core_product, 'transaction_id': payment_record.public_transaction_id, } context.update(additional_context) email_html = render_to_string(template_html, context) email_plaintext = render_to_string(template_plaintext, context) send_HTML_email( ugettext("Payment Received - Thank You!"), email, email_html, text_content=email_plaintext, email_from=get_dimagi_from_email_by_product(core_product), )
def send_report(scheduled_report, user): if isinstance(user, dict): user = CouchUser.wrap_correctly(user) try: report = ScheduledReportFactory.get_report(scheduled_report.report_slug) body = report.get_response(user, scheduled_report.domain) email = user.get_email() if email: send_HTML_email("%s [%s]" % (report.title, scheduled_report.domain), email, html2text(body), body) else: raise SMTPRecipientsRefused(None) except Http404: # Scenario: user has been removed from the domain that they have scheduled reports for. # Do a scheduled report cleanup user_id = unicode(user.get_id) domain = Domain.get_by_name(scheduled_report.domain) user_ids = [user.get_id for user in domain.all_users()] if user_id not in user_ids: # remove the offending user from the scheduled report scheduled_report.user_ids.remove(user_id) if len(scheduled_report.user_ids) == 0: # there are no users with appropriate permissions left in the scheduled report, # so remove it scheduled_report.delete() else: scheduled_report.save()
def send_bookkeeper_email(month=None, year=None, emails=None): today = datetime.date.today() # now, make sure that we send out LAST month's invoices if we did # not specify a month or year. today = utils.get_previous_month_date_range(today)[0] month = month or today.month year = year or today.year from corehq.apps.accounting.interface import InvoiceInterface request = HttpRequest() params = urlencode(( ('report_filter_statement_period_use_filter', 'on'), ('report_filter_statement_period_month', month), ('report_filter_statement_period_year', year), )) request.GET = QueryDict(params) request.couch_user = FakeUser( domain="hqadmin", username="******", ) invoice = InvoiceInterface(request) invoice.is_rendered_as_email = True first_of_month = datetime.date(year, month, 1) email_context = { 'month': first_of_month.strftime("%B"), } email_content = render_to_string( 'accounting/bookkeeper_email.html', email_context) email_content_plaintext = render_to_string( 'accounting/bookkeeper_email_plaintext.html', email_context) format_dict = Format.FORMAT_DICT[Format.CSV] excel_attachment = { 'title': 'Invoices_%(period)s.%(extension)s' % { 'period': first_of_month.strftime('%B_%Y'), 'extension': format_dict['extension'], }, 'mimetype': format_dict['mimetype'], 'file_obj': invoice.excel_response, } emails = emails or settings.BOOKKEEPER_CONTACT_EMAILS for email in emails: send_HTML_email( "Invoices for %s" % datetime.date(year, month, 1).strftime("%B %Y"), email, email_content, email_from=settings.DEFAULT_FROM_EMAIL, text_content=email_content_plaintext, file_attachments=[excel_attachment], ) logger.info( "[BILLING] Sent Bookkeeper Invoice Summary for %(month)s " "to %(emails)s." % { 'month': first_of_month.strftime("%B %Y"), 'emails': ", ".join(emails) })
def send_purchase_receipt(payment_record, domain, template_html, template_plaintext, additional_context): username = payment_record.payment_method.web_user try: web_user = WebUser.get_by_username(username) email = web_user.get_email() name = web_user.first_name except ResourceNotFound: log_accounting_error( "Strange. A payment attempt was made by a user that " "we can't seem to find! %s" % username, show_stack_trace=True, ) name = email = username context = { 'name': name, 'amount': fmt_dollar_amount(payment_record.amount), 'project': domain, 'date_paid': payment_record.date_created.strftime(USER_DATE_FORMAT), 'transaction_id': payment_record.public_transaction_id, } context.update(additional_context) email_html = render_to_string(template_html, context) email_plaintext = render_to_string(template_plaintext, context) send_HTML_email( ugettext("Payment Received - Thank You!"), email, email_html, text_content=email_plaintext, email_from=get_dimagi_from_email(), )
def ensure_full_coverage(self, subscriptions): plan_version = DefaultProductPlan.get_default_plan_by_domain( self.domain, edition=SoftwarePlanEdition.COMMUNITY ).plan.get_version() if not plan_version.feature_charges_exist_for_domain(self.domain): return community_ranges = self.get_community_ranges(subscriptions) if not community_ranges: return do_not_invoice = any([s.do_not_invoice for s in subscriptions]) account = BillingAccount.get_or_create_account_by_domain( self.domain.name, created_by=self.__class__.__name__, created_by_invoicing=True)[0] if account.date_confirmed_extra_charges is None: if self.domain.is_active: subject = "[%s] Invoice Generation Issue" % self.domain.name email_content = render_to_string( 'accounting/invoice_error_email.html', { 'project': self.domain.name, 'error_msg': "This project is incurring charges on their " "Community subscription, but they haven't " "agreed to the charges yet. Someone should " "follow up with this project to see if everything " "is configured correctly or if communication " "needs to happen between Dimagi and the project's" "admins. For now, the invoices generated are " "marked as Do Not Invoice.", } ) send_HTML_email( subject, settings.BILLING_EMAIL, email_content, email_from="Dimagi Billing Bot <%s>" % settings.DEFAULT_FROM_EMAIL ) do_not_invoice = True if not BillingContactInfo.objects.filter(account=account).exists(): # No contact information exists for this account. # This shouldn't happen, but if it does, we can't continue # with the invoice generation. raise BillingContactInfoError( "Project %s has incurred charges, but does not have their " "Billing Contact Info filled out. Someone should follow up " "on this." % self.domain.name ) # First check to make sure none of the existing subscriptions is set # to do not invoice. Let's be on the safe side and not send a # community invoice out, if that's the case. for c in community_ranges: # create a new community subscription for each # date range that the domain did not have a subscription community_subscription = Subscription( account=account, plan_version=plan_version, subscriber=self.subscriber, date_start=c[0], date_end=c[1], do_not_invoice=do_not_invoice, ) community_subscription.save() subscriptions.append(community_subscription)
def send_activation_email(self): url = "http://%s%s" % (Site.objects.get_current().domain, 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(subject, self.email, html_content, text_content=text_content)
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(subject, recipient, html_content, text_content=text_content)
def generate_invoices(based_on_date=None, check_existing=False, is_test=False): """ Generates all invoices for the past month. """ today = based_on_date or datetime.date.today() invoice_start, invoice_end = utils.get_previous_month_date_range(today) logger.info("[Billing] Starting up invoices for %(start)s - %(end)s" % { 'start': invoice_start.strftime("%d %B %Y"), 'end': invoice_end.strftime("%d %B %Y"), }) all_domain_ids = [d['id'] for d in Domain.get_all(include_docs=False)] for domain_doc in iter_docs(Domain.get_db(), all_domain_ids): domain = Domain.wrap(domain_doc) if (check_existing and Invoice.objects.filter( subscription__subscriber__domain=domain, date_created__gte=today).count() != 0): pass elif is_test: logger.info("[Billing] Ready to create invoice for domain %s" % domain.name) else: try: invoice_factory = DomainInvoiceFactory( invoice_start, invoice_end, domain) invoice_factory.create_invoices() logger.info("[BILLING] Sent invoices for domain %s" % domain.name) except CreditLineError as e: logger.error( "[BILLING] There was an error utilizing credits for " "domain %s: %s" % (domain.name, e) ) except BillingContactInfoError as e: subject = "[%s] Invoice Generation Issue" % domain.name email_content = render_to_string( 'accounting/invoice_error_email.html', { 'project': domain.name, 'error_msg': 'BillingContactInfoError: %s' % e, } ) send_HTML_email( subject, settings.BILLING_EMAIL, email_content, email_from="Dimagi Billing Bot <%s>" % settings.DEFAULT_FROM_EMAIL ) except InvoiceError as e: logger.error( "[BILLING] Could not create invoice for domain %s: %s" % ( domain.name, e )) except Exception as e: logger.error( "[BILLING] Error occurred while creating invoice for " "domain %s: %s" % (domain.name, e) ) # And finally... if not is_test: send_bookkeeper_email()
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(subject, self.email, html_content, text_content=text_content, email_from=settings.DEFAULT_FROM_EMAIL)
def bulk_archive_forms(domain, user, uploaded_data): response = archive_forms(domain, user, uploaded_data) for msg in response['success']: logger.info("[Data interfaces] %s", msg) for msg in response['errors']: logger.info("[Data interfaces] %s", msg) html_content = render_to_string('data_interfaces/archive_email.html', response) send_HTML_email(_('Your archived forms'), user.email, html_content)
def send_domain_registration_email(recipient, domain_name, guid): DNS_name = Site.objects.get(id = settings.SITE_ID).domain activation_link = 'http://' + DNS_name + reverse('registration_confirm_domain') + guid + '/' wiki_link = 'http://wiki.commcarehq.org/display/commcarepublic/Home' users_link = 'http://groups.google.com/group/commcare-users' message_plaintext = """ Welcome to CommCareHQ! Please click this link: {activation_link} to activate your new domain. You will not be able to use your domain until you have confirmed this email address. Project name: "{domain}" Username: "******" For help getting started, you can visit the CommCare Wiki, the home of all CommCare documentation. Click this link to go directly to the guide to CommCare HQ: {wiki_link} We also encourage you to join the "commcare-users" google group, where CommCare users from all over the world ask each other questions and share information over the commcare-users mailing list: {users_link} If you encounter any technical problems while using CommCareHQ, look for a "Report an Issue" link at the bottom of every page. Our developers will look into the problem and communicate with you about a solution. Thank you, The CommCareHQ Team """ message_html = """ <h1>Welcome to CommCare HQ!</h1> <p>Please <a href="{activation_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> <p>For help getting started, you can visit the <a href="{wiki_link}">CommCare Wiki</a>, the home of all CommCare documentation.</p> <p>We also encourage you to join the <a href="{users_link}">commcare-users google group</a>, where CommCare users from all over the world ask each other questions and share information over the commcare-users mailing list.</p> <p>If you encounter any technical problems while using CommCareHQ, look for a "Report an Issue" link at the bottom of every page. Our developers will look into the problem and communicate with you about a solution.</p> <p style="margin-top:1em">Thank you,</p> <p><strong>The CommCareHQ Team</strong></p> <p>If your email viewer won't permit you to click on the registration link above, cut and paste the following link into your web browser:</p> {activation_link} """ params = {"domain": domain_name, "activation_link": activation_link, "username": recipient, "wiki_link": wiki_link, "users_link": users_link} message_plaintext = message_plaintext.format(**params) message_html = message_html.format(**params) subject = 'Welcome to CommCare HQ!'.format(**locals()) try: send_HTML_email(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)
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( _(u'Transfer of ownership for CommCare project space.'), self.to_user.email, html_content, text_content=text_content)
def _send_email(to, report, hash_id): domain = Site.objects.get_current().domain link = "http://%s%s" % (domain, reverse("export_report", args=[report.domain, str(hash_id)])) title = "%s: Requested export excel data" body = "The export you requested for the '%s' report is ready.<br>" \ "You can download the data at the following link: %s<br><br>" \ "Please remember that this link will only be active for 24 hours." send_HTML_email(_(title) % report.name, to, _(body) % (report.name, "<a href='%s'>%s</a>" % (link, link)), email_from=settings.DEFAULT_FROM_EMAIL)
def _send_request_notification_email(request, org, dom): url_base = Site.objects.get_current().domain params = {"org": org, "dom": dom, "requestee": request.couch_user, "url_base": url_base} text_content = render_to_string("domain/email/org_request_notification.txt", params) html_content = render_to_string("domain/email/org_request_notification.html", params) recipients = [member.email for member in org.get_members() if member.is_org_admin(org.name)] subject = "New request to add a project to your organization! -- CommcareHQ" try: for recipient in recipients: send_HTML_email(subject, recipient, html_content, text_content=text_content) except Exception: logging.warning("Can't send notification email, but the message was:\n%s" % text_content)
def _notification_email_on_publish(domain, snapshot, published_by): url_base = Site.objects.get_current().domain params = {"domain": domain, "snapshot": snapshot, "published_by": published_by, "url_base": url_base} 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(subject, recipient, html_content, text_content=text_content) except Exception: logging.warning("Can't send notification email, but the message was:\n%s" % text_content)
def weekly_digest(): today = datetime.date.today() in_forty_days = today + datetime.timedelta(days=40) from corehq.apps.accounting.interface import SubscriptionInterface request = HttpRequest() params = urlencode(( ('report_filter_end_date_use_filter', 'on'), ('end_date_startdate', today.isoformat()), ('end_date_enddate', in_forty_days.isoformat()), ('active_status', 'Active'), (filters.TrialStatusFilter.slug, filters.TrialStatusFilter.NON_TRIAL), )) request.GET = QueryDict(params) request.couch_user = FakeUser( domain="hqadmin", username="******", ) subs = SubscriptionInterface(request) subs.is_rendered_as_email = True email_context = { 'today': today.isoformat(), 'forty_days': in_forty_days.isoformat(), } email_content = render_to_string( 'accounting/digest_email.html', email_context) email_content_plaintext = render_to_string( 'accounting/digest_email.txt', email_context) format_dict = Format.FORMAT_DICT[Format.CSV] excel_attachment = { 'title': 'Subscriptions_%(start)s_%(end)s.csv' % { 'start': today.isoformat(), 'end': in_forty_days.isoformat(), }, 'mimetype': format_dict['mimetype'], 'file_obj': subs.excel_response, } from_email = "Dimagi Accounting <%s>" % settings.DEFAULT_FROM_EMAIL send_HTML_email( "Subscriptions ending in 40 Days from %s" % today.isoformat(), settings.INVOICING_CONTACT_EMAIL, email_content, email_from=from_email, text_content=email_content_plaintext, file_attachments=[excel_attachment], ) logger.info( "[BILLING] Sent summary of ending subscriptions from %(today)s" % { 'today': today.isoformat(), })
def send_global_domain_registration_email(requesting_user, domain_name): DNS_name = Site.objects.get(id = settings.SITE_ID).domain domain_link = 'http://' + DNS_name + reverse("domain_homepage", args=[domain_name]) wiki_link = 'http://wiki.commcarehq.org/display/commcarepublic/Home' users_link = 'http://groups.google.com/group/commcare-users' message_plaintext = """ 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: {domain_link} Please remember, if you need help you can visit the CommCare Wiki, the home of all CommCare documentation. Click this link to go directly to the guide to CommCare HQ: {wiki_link} If you haven't yet, we also encourage you to join the "commcare-users" google group, where CommCare users from all over the world ask each other questions and share information over the commcare-users mailing list: {users_link} If you encounter any technical problems while using CommCareHQ, look for a "Report an Issue" link at the bottom of every page. Our developers will look into the problem and communicate with you about a solution. Thank you, The CommCareHQ Team """ message_html = """ <h1>New project "{domain}" created!</h1> <p>Hello {name},</p> <p>You may now <a href="{domain_link}">visit your newly created project</a> with the CommCare HQ User <strong>{username}</strong>.</p> <p>Please remember, if you need help you can visit the <a href="{wiki_link}">CommCare Help Site</a>, the home of all CommCare documentation.</p> <p>We also encourage you to join the <a href="{users_link}">commcare-users google group</a>, where CommCare users from all over the world ask each other questions and share information over the commcare-users mailing list.</p> <p>If you encounter any technical problems while using CommCareHQ, look for a "Report an Issue" link at the bottom of every page. Our developers will look into the problem and communicate with you about a solution.</p> <p style="margin-top:1em">Thank you,</p> <p><strong>The CommCareHQ Team</strong></p> <p>If your email viewer won't permit you to click on the registration link above, cut and paste the following link into your web browser:</p> {domain_link} """ params = {"name": requesting_user.first_name, "domain": domain_name, "domain_link": domain_link, "username": requesting_user.email, "wiki_link": wiki_link, "users_link": users_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(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)
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( _(u'Transfer of ownership for CommCare project space.'), self.from_user.email, html_content, text_content=text_content)
def send_mass_emails(username, real_email, subject, html, text): if real_email: recipients = [{ 'username': h['username'], 'first_name': h['first_name'] or 'CommCare User', } for h in UserES().web_users().run().hits] else: recipients = [{ 'username': username, 'first_name': 'CommCare User', }] successes = [] failures = [] for recipient in recipients: context = recipient context.update({ 'url_prefix': '' if settings.STATIC_CDN else 'http://' + get_site_domain(), }) html_template = Template(html) text_template = Template(text) text_content = render_to_string("hqadmin/email/mass_email_base.txt", { 'email_body': text_template.render(Context(context)), }) html_content = render_to_string("hqadmin/email/mass_email_base.html", { 'email_body': html_template.render(Context(context)), }) try: send_HTML_email(subject, recipient['username'], html_content, text_content=text_content) successes.append((recipient['username'], None)) except Exception as e: failures.append((recipient['username'], e)) message = ( "Subject: {subject},\n" "Total successes: {success_count} \n Total errors: {failure_count} \n" "".format( subject=subject, success_count=len(successes), failure_count=len(failures)) ) send_html_email_async( "Mass email summary", username, message, text_content=message, file_attachments=[ _mass_email_attachment('successes', successes), _mass_email_attachment('failures', failures)] )
def process_submission(self): try: params = { 'pro_bono_form': self, } html_content = render_to_string("domain/email/pro_bono_application.html", params) text_content = render_to_string("domain/email/pro_bono_application.txt", params) recipient = settings.BILLING_EMAIL send_HTML_email("Pro-Bono Application", recipient, html_content, text_content=text_content) send_HTML_email("Pro-Bono Application", recipient, html_content, text_content=text_content) except Exception: logging.error("Couldn't send pro-bono application email. " "Contact: %s" % self.cleaned_data['contact_email'] )
def process_email_request(domain, download_id, email_address): dropbox_url = absolute_reverse('dropbox_upload', args=(download_id,)) download_url = "{}?get_file".format(absolute_reverse('retrieve_download', args=(download_id,))) try: allow_dropbox_sync = get_download_context(download_id).get('allow_dropbox_sync', False) except TaskFailedError: allow_dropbox_sync = False dropbox_message = '' if allow_dropbox_sync: dropbox_message = _('<br/><br/>You can also upload your data to Dropbox with the link below:<br/>' '{}').format(dropbox_url) email_body = _('Your CommCare export for {} is ready! Click on the link below to download your requested data:' '<br/>{}{}').format(domain, download_url, dropbox_message) send_HTML_email(_('CommCare Export Complete'), email_address, email_body)
def email_report(request, domain, report_slug, report_type=ProjectReportDispatcher.prefix): from dimagi.utils.django.email import send_HTML_email from forms import EmailReportForm user_id = request.couch_user._id form = EmailReportForm(request.GET) if not form.is_valid(): return HttpResponseBadRequest() config = ReportConfig() # see ReportConfig.query_string() object.__setattr__(config, '_id', 'dummy') config.name = _("Emailed report") config.report_type = report_type config.report_slug = report_slug config.owner_id = user_id config.domain = domain config.date_range = 'range' config.start_date = request.datespan.computed_startdate.date() config.end_date = request.datespan.computed_enddate.date() GET = dict(request.GET.iterlists()) exclude = ['startdate', 'enddate', 'subject', 'send_to_owner', 'notes', 'recipient_emails'] filters = {} for field in GET: if not field in exclude: filters[field] = GET.get(field) config.filters = filters body = _render_report_configs(request, [config], domain, user_id, request.couch_user, True, notes=form.cleaned_data['notes'])[0].content subject = form.cleaned_data['subject'] or _("Email report from CommCare HQ") if form.cleaned_data['send_to_owner']: send_HTML_email(subject, request.couch_user.get_email(), body, email_from=settings.DEFAULT_FROM_EMAIL) if form.cleaned_data['recipient_emails']: for recipient in form.cleaned_data['recipient_emails']: send_HTML_email(subject, recipient, body, email_from=settings.DEFAULT_FROM_EMAIL) return HttpResponse()
def send(self): from dimagi.utils.django.email import send_HTML_email from corehq.apps.reports.views import get_scheduled_report_response # Scenario: user has been removed from the domain that they # have scheduled reports for. Delete this scheduled report if not self.owner.is_member_of(self.domain): self.delete() return if self.all_recipient_emails: title = "Scheduled report from CommCare HQ" body = get_scheduled_report_response(self.owner, self.domain, self._id).content for email in self.all_recipient_emails: send_HTML_email(title, email, body, email_from=settings.DEFAULT_FROM_EMAIL)
def send_email(to, report, hash_id): link = "http://%s%s" % (Site.objects.get_current().domain, reverse("bihar_export_report", args=[report.domain, str(hash_id)])) title = "%s: Requested export excel data" % report.name body = "You have requested generating excel export file from '%s' report for selected filters '%s': %s <br><br>" \ "If download link is not working, please copy and paste following link in your browse: " \ "<br>" \ "%s" \ "<br>" \ "Please remind that link will be active by 24 hours."\ % (report.name, report.request.GET, "<a href='%s'>%s</a>" % (link, 'download link'), link) send_HTML_email(title, to, body, email_from=settings.DEFAULT_FROM_EMAIL)
def build_last_month_MALT(): def _last_month_datespan(): today = datetime.date.today() first_of_this_month = datetime.date(day=1, month=today.month, year=today.year) last_month = first_of_this_month - datetime.timedelta(days=1) return DateSpan.from_month(last_month.month, last_month.year) last_month = _last_month_datespan() generator = MALTTableGenerator([last_month]) generator.build_table() message = ( "MALT generation for month {} is now ready. To download go to" " http://www.commcarehq.org/hq/admin/download_malt/".format(last_month) ) send_HTML_email("MALT is ready", settings.DATA_EMAIL, message, text_content=message)
def _send_email(user, report, hash_id): domain = report.domain or user.get_domains()[0] link = absolute_reverse("export_report", args=[domain, str(hash_id), report.export_format]) title = "%s: Requested export excel data" body = "The export you requested for the '%s' report is ready.<br>" \ "You can download the data at the following link: %s<br><br>" \ "Please remember that this link will only be active for 24 hours." send_HTML_email( _(title) % report.name, user.get_email(), _(body) % (report.name, "<a href='%s'>%s</a>" % (link, link)), email_from=settings.DEFAULT_FROM_EMAIL )
def process_submission(self): try: params = { 'contact_email': self.cleaned_data['contact_email'], 'organization': self.cleaned_data['organization'], 'project_overview': self.cleaned_data['project_overview'], 'pay_only_features_needed': self.cleaned_data['pay_only_features_needed'], 'duration_of_project': self.cleaned_data['duration_of_project'], } html_content = render_to_string("domain/email/pro_bono_application.html", params) text_content = render_to_string("domain/email/pro_bono_application.txt", params) recipient = "*****@*****.**" send_HTML_email("Pro-Bono Application", recipient, html_content, text_content=text_content) except Exception: logging.error("Couldn't send pro-bono application email. " "Contact: %s" % self.cleaned_data['contact_email'] )
def send_html_to_user(self, user): # because we could have html-email reports (using report-body div's) live alongside # pdf reports, i've left this code as is url = reverse(self.report.view_name, kwargs=self.view_args) func, args, kwargs = resolve(url) report = ReportSchedule(func, title=self.report.display_name) result = report.get_response(user, self.view_args) subject = result['subject'] if not subject: result['body'] try: site_name = Site.objects.get().name except Site.DoesNotExist: pass else: subject = "{0} {1}".format(site_name, report.title) send_HTML_email(subject, user.email, result['body'])
def process_submission(self, domain=None): try: params = { 'pro_bono_form': self, } html_content = render_to_string("domain/email/pro_bono_application.html", params) text_content = render_to_string("domain/email/pro_bono_application.txt", params) recipient = settings.BILLING_EMAIL subject = "[Pro-Bono Application]" if domain is not None: subject = "%s %s" % (subject, domain) send_HTML_email(subject, recipient, html_content, text_content=text_content, email_from=settings.DEFAULT_FROM_EMAIL) except Exception: logging.error("Couldn't send pro-bono application email. " "Contact: %s" % self.cleaned_data['contact_email'] )
def send_domain_registration_email(recipient, domain_name, guid): DNS_name = Site.objects.get(id=settings.SITE_ID).domain activation_link = 'http://' + DNS_name + reverse( 'registration_confirm_domain') + guid + '/' wiki_link = 'http://wiki.commcarehq.org/display/commcarepublic/Home' users_link = 'http://groups.google.com/group/commcare-users' message_plaintext = """ Welcome to CommCareHQ! Please click this link: {activation_link} to activate your new domain. You will not be able to use your domain until you have confirmed this email address. Project name: "{domain}" Username: "******" For help getting started, you can visit the CommCare Wiki, the home of all CommCare documentation. Click this link to go directly to the guide to CommCare HQ: {wiki_link} We also encourage you to join the "commcare-users" google group, where CommCare users from all over the world ask each other questions and share information over the commcare-users mailing list: {users_link} If you encounter any technical problems while using CommCareHQ, look for a "Report an Issue" link at the bottom of every page. Our developers will look into the problem and communicate with you about a solution. Thank you, The CommCareHQ Team """ message_html = """ <h1>Welcome to CommCare HQ!</h1> <p>Please <a href="{activation_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> <p>For help getting started, you can visit the <a href="{wiki_link}">CommCare Wiki</a>, the home of all CommCare documentation.</p> <p>We also encourage you to join the <a href="{users_link}">commcare-users google group</a>, where CommCare users from all over the world ask each other questions and share information over the commcare-users mailing list.</p> <p>If you encounter any technical problems while using CommCareHQ, look for a "Report an Issue" link at the bottom of every page. Our developers will look into the problem and communicate with you about a solution.</p> <p style="margin-top:1em">Thank you,</p> <p><strong>The CommCareHQ Team</strong></p> <p>If your email viewer won't permit you to click on the registration link above, cut and paste the following link into your web browser:</p> {activation_link} """ params = { "domain": domain_name, "activation_link": activation_link, "username": recipient, "wiki_link": wiki_link, "users_link": users_link } message_plaintext = message_plaintext.format(**params) message_html = message_html.format(**params) subject = 'Welcome to CommCare HQ!'.format(**locals()) try: send_HTML_email(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)
def send_global_domain_registration_email(requesting_user, domain_name): DNS_name = Site.objects.get(id=settings.SITE_ID).domain domain_link = 'http://' + DNS_name + reverse("domain_homepage", args=[domain_name]) wiki_link = 'http://wiki.commcarehq.org/display/commcarepublic/Home' users_link = 'http://groups.google.com/group/commcare-users' message_plaintext = """ 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: {domain_link} Please remember, if you need help you can visit the CommCare Wiki, the home of all CommCare documentation. Click this link to go directly to the guide to CommCare HQ: {wiki_link} If you haven't yet, we also encourage you to join the "commcare-users" google group, where CommCare users from all over the world ask each other questions and share information over the commcare-users mailing list: {users_link} If you encounter any technical problems while using CommCareHQ, look for a "Report an Issue" link at the bottom of every page. Our developers will look into the problem and communicate with you about a solution. Thank you, The CommCareHQ Team """ message_html = """ <h1>New project "{domain}" created!</h1> <p>Hello {name},</p> <p>You may now <a href="{domain_link}">visit your newly created project</a> with the CommCare HQ User <strong>{username}</strong>.</p> <p>Please remember, if you need help you can visit the <a href="{wiki_link}">CommCare Help Site</a>, the home of all CommCare documentation.</p> <p>We also encourage you to join the <a href="{users_link}">commcare-users google group</a>, where CommCare users from all over the world ask each other questions and share information over the commcare-users mailing list.</p> <p>If you encounter any technical problems while using CommCareHQ, look for a "Report an Issue" link at the bottom of every page. Our developers will look into the problem and communicate with you about a solution.</p> <p style="margin-top:1em">Thank you,</p> <p><strong>The CommCareHQ Team</strong></p> <p>If your email viewer won't permit you to click on the registration link above, cut and paste the following link into your web browser:</p> {domain_link} """ params = { "name": requesting_user.first_name, "domain": domain_name, "domain_link": domain_link, "username": requesting_user.email, "wiki_link": wiki_link, "users_link": users_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(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)
share.get('url', None), 'path': u'Apps/{app}{dest}'.format( app=settings.DROPBOX_APP_NAME, dest=upload['path'], ) } with localize(couch_user.get_language_code()): subject = _(u'{} has been uploaded to dropbox!'.format( helper.dest)) html_content = render_to_string( 'dropbox/emails/upload_success.html', context) text_content = render_to_string( 'dropbox/emails/upload_success.txt', context) else: context = {'reason': helper.failure_reason, 'path': helper.dest} with localize(couch_user.get_language_code()): subject = _(u'{} has failed to upload to dropbox'.format( helper.dest)) html_content = render_to_string('dropbox/emails/upload_error.html', context) text_content = render_to_string('dropbox/emails/upload_error.txt', context) send_HTML_email( subject, helper.user.email, html_content, text_content=text_content, )
def handle(self, *args, **options): dryrun = options.pop('dryrun') limit = options.pop('limit') count = 0 if dryrun: print '*** Running in dryrun mode. Will not save any conversion ***' print '*** Migrating {} exports ***'.format(limit or 'ALL') skipped_domains = [] for doc in Domain.get_all(include_docs=False): domain = doc['key'] if not use_new_exports(domain): try: metas = migrate_domain(domain, True) except Exception: print 'Migration raised an exception, skipping.' traceback.print_exc() skipped_domains.append(domain) continue has_skipped_tables = any( map(lambda meta: bool(meta.skipped_tables), metas)) has_skipped_columns = any( map(lambda meta: bool(meta.skipped_columns), metas)) is_remote_app_migration = any( map(lambda meta: bool(meta.is_remote_app_migration), metas)) if has_skipped_tables or has_skipped_columns: print 'Skipping {} because we would have skipped columns'.format( domain) skipped_domains.append(domain) continue if is_remote_app_migration: print 'Skipping {} because it contains remote apps'.format( domain) skipped_domains.append(domain) continue if not dryrun: print 'Migrating {}'.format(domain) try: migrate_domain(domain, False) except Exception: print 'Migration raised an exception, skipping.' skipped_domains.append(domain) continue else: print 'No skipped tables/columns. Not migrating since dryrun is specified' count += 1 if limit is not None and count >= limit: break send_HTML_email( 'Export migration results', '{}@{}'.format('brudolph', 'dimagi.com'), ''' Skipped domains: {} <br /> Successfully migrated: {} '''.format( ', '.join(skipped_domains), count, ))
def weekly_digest(): today = datetime.date.today() in_forty_days = today + datetime.timedelta(days=40) ending_in_forty_days = filter( lambda sub: not sub.is_renewed, Subscription.objects.filter( date_end__lte=in_forty_days, date_end__gte=today, is_active=True, is_trial=False, account__dimagi_contact__isnull=True, )) if not ending_in_forty_days: logger.info( "[Billing] Did not send summary of ending subscriptions because " "there are none." ) return table = [[ "Project Space", "Account", "Plan", "Salesforce Contract ID", "Dimagi Contact", "Start Date", "End Date", "Receives Invoice", "Created By", ]] def _fmt_row(sub): try: created_by_adj = SubscriptionAdjustment.objects.filter( subscription=sub, reason=SubscriptionAdjustmentReason.CREATE ).order_by('date_created')[0] created_by = dict(SubscriptionAdjustmentMethod.CHOICES).get( created_by_adj.method, "Unknown") except (IndexError, SubscriptionAdjustment.DoesNotExist): created_by = "Unknown" return [ sub.subscriber.domain, "%s (%s)" % (sub.account.name, sub.account.id), sub.plan_version.plan.name, sub.salesforce_contract_id, sub.account.dimagi_contact, sub.date_start, sub.date_end, "No" if sub.do_not_invoice else "YES", created_by, ] table.extend([_fmt_row(sub) for sub in ending_in_forty_days]) file_to_attach = StringIO() export_from_tables( [['End in 40 Days', table]], file_to_attach, Format.XLS_2007 ) email_context = { 'today': today.isoformat(), 'forty_days': in_forty_days.isoformat(), } email_content = render_to_string( 'accounting/digest_email.html', email_context) email_content_plaintext = render_to_string( 'accounting/digest_email.txt', email_context) format_dict = Format.FORMAT_DICT[Format.XLS_2007] file_attachment = { 'title': 'Subscriptions_%(start)s_%(end)s.xls' % { 'start': today.isoformat(), 'end': in_forty_days.isoformat(), }, 'mimetype': format_dict['mimetype'], 'file_obj': file_to_attach, } from_email = "Dimagi Accounting <%s>" % settings.DEFAULT_FROM_EMAIL env = ("[{}] ".format(settings.SERVER_ENVIRONMENT.upper()) if settings.SERVER_ENVIRONMENT != "production" else "") email_subject = "{}Subscriptions ending in 40 Days from {}".format(env, today.isoformat()) send_HTML_email( email_subject, settings.ACCOUNTS_EMAIL, email_content, email_from=from_email, text_content=email_content_plaintext, file_attachments=[file_attachment], ) logger.info( "[BILLING] Sent summary of ending subscriptions from %(today)s" % { 'today': today.isoformat(), })
def send_bookkeeper_email(month=None, year=None, emails=None): today = datetime.date.today() # now, make sure that we send out LAST month's invoices if we did # not specify a month or year. today = get_previous_month_date_range(today)[0] month = month or today.month year = year or today.year from corehq.apps.accounting.interface import InvoiceInterface request = HttpRequest() params = urlencode(( ('report_filter_statement_period_use_filter', 'on'), ('report_filter_statement_period_month', month), ('report_filter_statement_period_year', year), )) request.GET = QueryDict(params) request.couch_user = FakeUser( domain="hqadmin", username="******", ) invoice = InvoiceInterface(request) invoice.is_rendered_as_email = True first_of_month = datetime.date(year, month, 1) email_context = { 'month': first_of_month.strftime("%B"), } email_content = render_to_string('accounting/bookkeeper_email.html', email_context) email_content_plaintext = render_to_string( 'accounting/bookkeeper_email_plaintext.html', email_context) format_dict = Format.FORMAT_DICT[Format.CSV] excel_attachment = { 'title': 'Invoices_%(period)s.%(extension)s' % { 'period': first_of_month.strftime('%B_%Y'), 'extension': format_dict['extension'], }, 'mimetype': format_dict['mimetype'], 'file_obj': invoice.excel_response, } emails = emails or settings.BOOKKEEPER_CONTACT_EMAILS for email in emails: send_HTML_email( "Invoices for %s" % datetime.date(year, month, 1).strftime(USER_MONTH_FORMAT), email, email_content, email_from=settings.DEFAULT_FROM_EMAIL, text_content=email_content_plaintext, file_attachments=[excel_attachment], ) log_accounting_info( "Sent Bookkeeper Invoice Summary for %(month)s " "to %(emails)s." % { 'month': first_of_month.strftime(USER_MONTH_FORMAT), 'emails': ", ".join(emails) })
def email_result(download_url): send_HTML_email( 'Bulk Payload generated for %s' % repeater_type, email_id, 'This email is to just let you know that there is a ' 'download waiting for you at %s. It will expire in 24 hours' % download_url)
def email_report(request, domain, report_slug, report_type=ProjectReportDispatcher.prefix): from dimagi.utils.django.email import send_HTML_email from forms import EmailReportForm user_id = request.couch_user._id form = EmailReportForm(request.GET) if not form.is_valid(): return HttpResponseBadRequest() config = ReportConfig() # see ReportConfig.query_string() object.__setattr__(config, '_id', 'dummy') config.name = _("Emailed report") config.report_type = report_type config.report_slug = report_slug config.owner_id = user_id config.domain = domain config.date_range = 'range' config.start_date = request.datespan.computed_startdate.date() config.end_date = request.datespan.computed_enddate.date() GET = dict(request.GET.iterlists()) exclude = [ 'startdate', 'enddate', 'subject', 'send_to_owner', 'notes', 'recipient_emails' ] filters = {} for field in GET: if not field in exclude: filters[field] = GET.get(field) config.filters = filters body = _render_report_configs(request, [config], domain, user_id, request.couch_user, True, notes=form.cleaned_data['notes']).content subject = form.cleaned_data['subject'] or _( "Email report from CommCare HQ") if form.cleaned_data['send_to_owner']: send_HTML_email(subject, request.couch_user.get_email(), body, email_from=settings.DEFAULT_FROM_EMAIL) if form.cleaned_data['recipient_emails']: for recipient in form.cleaned_data['recipient_emails']: send_HTML_email(subject, recipient, body, email_from=settings.DEFAULT_FROM_EMAIL) return HttpResponse()