def send_incomplete_pledge_emails(self): # For every IncompletePledge instance that has not yet been # sent a reminder email, send one. Wait at least some hours # after the user left the page. before = timezone.now() - timedelta(hours=3) for ip in IncompletePledge.objects.filter(created__lt=before, sent_followup_at=None): context = {} context.update(get_branding(ip.via_campaign.brand)) context.update({ "incomplete_pledge": ip, "url": ip.get_return_url(), "trigger": ip.trigger, }) # Send email. send_mail("contrib/mail/incomplete_pledge", get_branding(ip.via_campaign.brand)["MAIL_FROM_EMAIL"], [ip.email], context, headers={ "Reply-To": get_branding(ip.via_campaign.brand)["CONTACT_EMAIL"], }) # Record that it was sent. ip.sent_followup_at = timezone.now() ip.save()
def send_notifications_email(self, user_id): # Get the user. user = User.objects.get(id=user_id) # Get the notifications to email. notifs = self.get_notifications_qs().filter(user=user) # Don't send any notifications that were generated prior to the # most recently emailed notification. most_recent_emailed = Notification.objects.filter(user=user)\ .exclude(mailed_at=None).order_by('-mailed_at').first() if most_recent_emailed: notifs = notifs.filter(created__gte=most_recent_emailed.mailed_at) # Nothing to send after all? if notifs.count() == 0: return # Only send up to the 50 most recent. notifs = notifs.order_by('-created')[0:50] # Prune any Notification objects whose generic object 'source' # is dangling (source object has since been deleted). def filter_and_delete(n): if n.source is None: n.delete() return False return True notifs = list(filter(filter_and_delete, notifs)) # Render. alerts = Notification.render(notifs, for_client=False) if len(alerts) == 0: # Nothing to send after all? return # Get the user's most recent pledge ContributorInfo object # to generate the salutation from. (May be null.) profile = user.get_contributorinfo() # Activate the user's preferred timezone? Not needed since # we aren't displaying notification times in the email, but # maybe we will? #user.active_timezone() # Send email. send_mail( "itfsite/mail/notifications", settings.DEFAULT_FROM_EMAIL, [user.email], { "user": user, "profile": profile, "notifs": alerts, "subject": alerts[0]['title'], "count": len(alerts), }) # Record that these notifications were sent. # Weird because of 'Cannot update a query once a slice has been taken.'. notifs = Notification.objects.filter(id__in=[n.id for n in notifs]) notifs.update(mailed_at=timezone.now())
def send_incomplete_pledge_emails(self): # For every IncompletePledge instance that has not yet been # sent a reminder email, send one. Wait at least some hours # after the user left the page. before = timezone.now() - timedelta(hours=3) for ip in IncompletePledge.objects.filter(created__lt=before, sent_followup_at=None): context = { } context.update(get_branding(ip.via_campaign.brand)) context.update({ "incomplete_pledge": ip, "url": ip.get_return_url(), "trigger": ip.trigger, }) # Send email. send_mail( "contrib/mail/incomplete_pledge", get_branding(ip.via_campaign.brand)["MAIL_FROM_EMAIL"], [ip.email], context, headers={ "Reply-To": get_branding(ip.via_campaign.brand)["CONTACT_EMAIL"], }) # Record that it was sent. ip.sent_followup_at = timezone.now() ip.save()
def send_blast(user_id, is_test): user = User.objects.get(id=user_id) prof = user.userprofile() # from address / return path address emailfromaddr = getattr(settings, 'EMAIL_UPDATES_FROMADDR', getattr(settings, 'SERVER_EMAIL', '*****@*****.**')) emailreturnpath = emailfromaddr if hasattr(settings, 'EMAIL_UPDATES_RETURN_PATH'): emailreturnpath = (settings.EMAIL_UPDATES_RETURN_PATH % user.id) # send! try: print "emailing", user.id, user.email send_mail( "website/email/blast", emailreturnpath, [user.email], { }, headers = { 'From': emailfromaddr, 'X-Auto-Response-Suppress': 'OOF', }, fail_silently=False ) except Exception as e: print user, e return False if not is_test: prof.last_mass_email = blast_id prof.save() return True # success
def send_pledge_email(self, pre_or_post, pledge): # What will happen when the pledge is executed? recipients = get_pledge_recipients(pledge) if len(recipients) == 0: # This pledge will result in nothing happening. There is # no need to email. return recip_contribs, fees, total_charge = compute_charge(pledge, recipients) context = {} context.update(get_branding(pledge.via_campaign.brand)) context.update({ "profile": pledge.profile, # used in salutation in email_template "pledge": pledge, "until": Pledge.current_algorithm()['pre_execution_warn_time'][1], "total_charge": total_charge, }) # Send email. send_mail("contrib/mail/%s_execution" % pre_or_post, context["MAIL_FROM_EMAIL"], [pledge.user.email], context) # Record that it was sent. field_name = "%s_execution_email_sent_at" % pre_or_post setattr(pledge, field_name, timezone.now()) pledge.save(update_fields=[field_name])
def send_pledge_email(self, pre_or_post, pledge): # What will happen when the pledge is executed? recipients = get_pledge_recipients(pledge) if len(recipients) == 0: # This pledge will result in nothing happening. There is # no need to email. return recip_contribs, fees, total_charge = compute_charge(pledge, recipients) context = { } context.update(get_branding(pledge.via_campaign.brand)) context.update({ "profile": pledge.profile, # used in salutation in email_template "pledge": pledge, "until": Pledge.current_algorithm()['pre_execution_warn_time'][1], "total_charge": total_charge, }) # Send email. send_mail( "contrib/mail/%s_execution" % pre_or_post, context["MAIL_FROM_EMAIL"], [pledge.user.email], context) # Record that it was sent. field_name = "%s_execution_email_sent_at" % pre_or_post setattr(pledge, field_name, timezone.now()) pledge.save(update_fields=[field_name])
def send(self): # Send and mark as sent. from htmlemailer import send_mail send_mail("email/invitation", settings.DEFAULT_FROM_EMAIL, [self.to_user.email if self.to_user else self.to_email], { 'invitation': self, }) Invitation.objects.filter(id=self.id).update(sent_at=timezone.now())
def send_it_out(self, notif): # If the Notification's target does not have an 'organization' attribute # and a 'get_absolute_url' attribute, then we can't generate a link back # to the site, so skip it. target = notif.target if not hasattr(target, 'get_absolute_url'): return organization = getattr(notif.target, 'organization', None) if not organization: return # Let the actor render appropriate for the org. notif.actor.localize_to_org(organization) # If the target supports receiving email replies (like replying to an email # about a discussion), then store a secret in the notif.data dictionary so # that we can tell that a user has replied to something we sent them (and # can't reply to something we didn't notify them about). what_reply_does = None if hasattr(target, "post_notification_reply"): notif.data = notif.data or {} notif.data["secret_key"] = uuid.uuid4() notif.save(update_fields=['data']) what_reply_does = "You can reply to this email to post a comment to the discussion. Do not forward this email to others." # Send the email. from htmlemailer import send_mail from email.utils import format_datetime from siteapp.templatetags.notification_helpers import get_notification_link url = get_notification_link(target, notif) if url is None: # Some notifications go stale and can't generate links, # and then we can't email notifications. return send_mail("email/notification", settings.DEFAULT_FROM_EMAIL, [notif.recipient.email], { "notification": notif, "url": organization.get_url(url), "whatreplydoes": what_reply_does, }, headers={ "From": settings.NOTIFICATION_FROM_EMAIL_PATTERN % (str(notif.actor), ), "Reply-To": (settings.NOTIFICATION_REPLY_TO_EMAIL_PATTERN % (organization.name, notif.id, notif.data["secret_key"])) if what_reply_does else "", "Date": format_datetime(notif.timestamp), }) # Mark it as sent. notif.recipient.notifemails_last_notif_id = notif.id notif.recipient.notifemails_last_at = timezone.now() notif.recipient.save( update_fields=['notifemails_last_notif_id', 'notifemails_last_at'])
def handle(self, *args, **options): from htmlemailer import send_mail send_mail( options["templatename"], options["sender"], [options["recipient"]], # example template context { "message": "This is a message containing >>> some HTML characters to test escaping <<<<.", "link": "https://github.com/if-then-fund/django-html-emailer", })
def mailer(context): from itfsite.middleware import get_branding context.update(get_branding(brand_id)) context.update({ "profile": profile, # used in salutation in email_template "pledge": pledge, "first_try": not self.sentConfirmationEmail, }) from htmlemailer import send_mail send_mail( template, context["MAIL_FROM_EMAIL"], [context['email']], context)
def send_blast(user_id, is_test, test_addrs, counter, counter_max): user = User.objects.get(id=user_id) prof = user.userprofile() # skip users that have had a bounced email recorded - avoid getting bad reputation if BouncedEmail.objects.filter(user=user).exists(): return # from address / return path address emailfromaddr = getattr( settings, 'EMAIL_UPDATES_FROMADDR', getattr(settings, 'SERVER_EMAIL', '*****@*****.**')) emailreturnpath = emailfromaddr if hasattr(settings, 'EMAIL_UPDATES_RETURN_PATH'): emailreturnpath = (settings.EMAIL_UPDATES_RETURN_PATH % user.id) # to: address send_to_addr = [user.email] if is_test and test_addrs: send_to_addr = test_addrs # send! try: print "%d/%d" % (counter + 1, counter_max), user.id, ", ".join(send_to_addr) send_mail("website/email/blast", emailreturnpath, send_to_addr, { "unsub_url": settings.SITE_ROOT_URL + "/accounts/unsubscribe/" + prof.get_one_click_unsub_key() }, headers={ 'From': "GovTrack.us <*****@*****.**>", 'Reply-To': "GovTrack.us <*****@*****.**>", 'X-Auto-Response-Suppress': 'OOF', }, fail_silently=False) except Exception as e: print user, e return False if not is_test: prof.last_mass_email = blast_id prof.save() return True # success
def send_blast(user_id, is_test, test_addrs, counter, counter_max): user = User.objects.get(id=user_id) prof = user.userprofile() # skip users that have had a bounced email recorded - avoid getting bad reputation if BouncedEmail.objects.filter(user=user).exists(): return # from address / return path address emailfromaddr = getattr(settings, 'EMAIL_UPDATES_FROMADDR', getattr(settings, 'SERVER_EMAIL', '*****@*****.**')) emailreturnpath = emailfromaddr if hasattr(settings, 'EMAIL_UPDATES_RETURN_PATH'): emailreturnpath = (settings.EMAIL_UPDATES_RETURN_PATH % user.id) # to: address send_to_addr = [user.email] if is_test and test_addrs: send_to_addr = test_addrs # send! try: print("%d/%d" % (counter+1, counter_max), user.id, ", ".join(send_to_addr)) send_mail( "website/email/blast", emailreturnpath, send_to_addr, { "unsub_url": settings.SITE_ROOT_URL + "/accounts/unsubscribe/" + prof.get_one_click_unsub_key() }, headers = { 'From': "GovTrack.us <*****@*****.**>", 'Reply-To': "GovTrack.us <*****@*****.**>", 'X-Auto-Response-Suppress': 'OOF', }, fail_silently=False ) except Exception as e: print(user, e) return False if not is_test: prof.last_mass_email = blast_id prof.save() return True # success
def send_warning(self, user, mail_connection): emailfromaddr = settings.EMAIL_UPDATES_FROMADDR emailreturnpath = settings.EMAIL_UPDATES_RETURN_PATH % user.id send_mail( "email/inactivity_warning", emailreturnpath, [user.email], { "user": user, "last_email": SubscriptionList.objects.filter(user=user).order_by('-last_email_sent').first().last_email_sent, }, headers={ 'Reply-To': emailfromaddr, 'Auto-Submitted': 'auto-generated', 'X-Auto-Response-Suppress': 'OOF', }, connection=mail_connection )
def send_record_email(email, action, r): return_url = r.url() kill_url = r.killurl() fromaddr = getattr(settings, 'EMAILVERIFICATION_FROMADDR', getattr(settings, 'SERVER_EMAIL', '*****@*****.**')) if hasattr(action, "email_from_address"): fromaddr = action.email_from_address() ctx = { "return_url": return_url, "kill_url": kill_url, } if hasattr(action, 'email_template_context'): ctx.update(action.email_template_context()) send_mail(action.email_template, fromaddr, [email], ctx, fail_silently=False)
def send_mail(self, template_prefix, email, context): from htmlemailer import send_mail send_mail(template_prefix, settings.DEFAULT_FROM_EMAIL, [email], context)
def send_it_out(self, notif): # If the Notification's target does not have an 'organization' attribute # and a 'get_absolute_url' attribute, then we can't generate a link back # to the site, so skip it. target = notif.target if not hasattr(target, 'get_absolute_url'): return organization = getattr(notif.target, 'organization', None) if not organization: return # Let the actor render appropriately. notif.actor.preload_profile() # If the target supports receiving email replies (like replying to an email # about a discussion), then store a secret in the notif.data dictionary so # that we can tell that a user has replied to something we sent them (and # can't reply to something we didn't notify them about). what_reply_does = None if hasattr(target, "post_notification_reply"): notif.data = notif.data or {} notif.data["secret_key"] = uuid.uuid4() notif.save(update_fields=['data']) what_reply_does = "You can reply to this email to post a comment to the discussion. Do not forward this email to others." # Send the email. from htmlemailer import send_mail from email.utils import format_datetime from siteapp.templatetags.notification_helpers import get_notification_link url = get_notification_link(target, notif) if url is None: # Some notifications go stale and can't generate links, # and then we can't email notifications. return # Prevent multiple notifications emailed from multiple instances/containers of GovReady-Q # Make this transaction atomic # Re-check the database to make sure the individual notification is still unsent # Lock the notification record in the database while sending the email with transaction.atomic(): notif_latest = (Notification.objects.select_for_update().get( id=notif.id)) if not notif_latest.emailed: send_mail("email/notification", settings.DEFAULT_FROM_EMAIL, [notif_latest.recipient.email], { "notification": notif, "url": settings.SITE_ROOT_URL + url, "whatreplydoes": what_reply_does, }, headers={ "From": settings.NOTIFICATION_FROM_EMAIL_PATTERN % (str(notif.actor), ), "Reply-To": (settings.NOTIFICATION_REPLY_TO_EMAIL_PATTERN % (organization.name, notif.id, notif.data["secret_key"])) if what_reply_does else "", "Date": format_datetime(notif.timestamp), }) # Mark notification as sent. notif_latest.emailed = True notif_latest.save(update_fields=['emailed']) # Update id of last notification sent to user notif.recipient.notifemails_last_notif_id = notif.id notif.recipient.notifemails_last_at = timezone.now() notif.recipient.save(update_fields=[ 'notifemails_last_notif_id', 'notifemails_last_at' ]) else: # Save record with nothing changed to close transaction notif_latest.save()