def handle(self, *args, **options): """ Bulk send reminder emails. """ today = datetime.date.today().weekday() all_dashboard = Dashboard.objects.all() all_emails = [] for d in all_dashboard: # Advisory period completed. So skip it if d.advisory_end_date < datetime.date.today(): continue url = 'http://ashoka-dashboard.herokuapp.com' \ + d.consultant_form_url all_teams = d.teams.filter( reminder_emails_day=today).select_related() for team in all_teams: # Add automatic reminder only if automatic_reminder is true if not team.team_status.automatic_reminder: continue # Get all Pulse Checkers and LRPs recipients = team.members.filter( Q(secondary_role__short_name="PC") or Q(role__short_name="LRP") ).distinct() if recipients: to = [r['email'] for r in recipients.values('email').all()] all_emails.append({ 'recipients': to, 'template': 'reminder_email', 'context': {'data': url}, }) # Queue all reminder emails at once mail.send_many(all_emails) # Send all queued emails mail.send_queued()
def send_mail(self, request, to_list): mail_form = AdHocEmailForm(request.POST) mail_form.fields['to'].choices = to_list if not request.user.is_superuser: mail_form.fields['sender'].widget = HiddenInput() if mail_form.is_valid(): email_batch = [] recipient_string = "" if request.user.is_superuser: sender = mail_form.cleaned_data['sender'] else: sender = request.user.email for email in mail_form.cleaned_data['to']: email_batch += [{ 'sender': sender, 'recipients': [email], 'subject': mail_form.cleaned_data['subject'], 'html_message': mail_form.cleaned_data['html_message'], }] if len(recipient_string) > 0: recipient_string = "%s, %s" % (recipient_string, email) else: recipient_string = email mail.send_many(email_batch) user_message = UserMessage.objects.get_or_create( view=self.__class__.__name__, code="SEND_SUCCESS", defaults={ 'summary': "Email Sent to Bidders", 'description': send_email_success_msg}) messages.success( request, user_message[0].description + recipient_string) return mail_form
def send_notif(self, notif_list=None): # Had to do this because signals refuse to work. if isinstance(self, Post): post = self notif_verb = "has posted on" elif isinstance(self, Comment): post = self.parent_post.all()[0] # There is only one parent_post notif_verb = "has commented on" wall = post.wall if not notif_list: # Get my wall and posts which I am to get notifs for notif_list = User.objects.filter(post.notify_users_query() | wall.notify_users_query()).distinct() mail_list = [] notif_list=list(notif_list) notif_list.remove(self.by) message={} # to send push notifications message['title']= self.by.first_name + " " + notif_verb + " " + post.wall.name + "'s Wall" message['message']=self.description.strip()[:50] send_push(notif_list, message) for recipient in notif_list: # Check if receipient already has notif on this post curr_notif = get_object_or_None(recipient.notifications.unread(), target_object_id=post.id) if curr_notif: curr_notif.mark_as_read() by = self.by # Now create a new unread notif if recipient != by: notifications.notify.send( sender=by, # The model who wrote the post - USER recipient=recipient, # The model who sees the post - USER verb=notif_verb, # verb action_object=self, # the model on which something happened - POST target=post, # The model which got affected - POST # In case you wish to get the wall on which it hapened, use target.wall (this is to ensure uniformity in all notifications) description = 'wall:' + str(wall.pk), ) notification = Bunch( actor = by, verb = notif_verb, target = post, action_object = self, timestamp = datetime.datetime.now() ) if recipient.profile.send_mails: unsubscribe_link = recipient.profile.create_unsubscribe_link() mail_list.append({ 'sender': settings.DEFAULT_FROM_EMAIL, 'recipients': [recipient.email], 'template': 'notification.email', 'context': {'subject': post.subject.strip(), 'user': recipient, 'notification': notification, 'FEST_NAME': settings.FEST_NAME, 'SITE_URL': settings.SITE_URL, 'unsubscribe_link': unsubscribe_link}, 'headers': {'List-Unsubscribe': unsubscribe_link}, }) if settings.SEND_NOTIF_EMAILS: mail.send_many(mail_list)
def send_mail(self, request, to_list): mail_form = AdHocEmailForm(request.POST) mail_form.fields['to'].choices = to_list if not request.user.is_superuser: mail_form.fields['sender'].widget = HiddenInput() if mail_form.is_valid(): email_batch = [] recipient_string = "" if request.user.is_superuser: sender = mail_form.cleaned_data['sender'] else: sender = request.user.email for email in mail_form.cleaned_data['to']: if self.email_type != "individual": footer = unsubscribe_text % ( Site.objects.get_current().domain, create_unsubscribe_link(email, "send_%s" % self.email_type)) message = mail_form.cleaned_data['html_message'] + footer else: message = mail_form.cleaned_data['html_message'] # if we're in DEBUG mode, let the sender send to only self subject = mail_form.cleaned_data['subject'] target = email if DEBUG: subject = "TO: %s - %s" % (email, subject) target = sender email_batch += [{ 'sender': DEFAULT_FROM_EMAIL, 'recipients': [target], 'subject': subject, 'html_message': message, 'headers': { 'Reply-to': sender }, }] if len(recipient_string) > 0: recipient_string = "%s, %s" % (recipient_string, email) else: recipient_string = email mail.send_many(email_batch) user_message = UserMessage.objects.get_or_create( view=self.__class__.__name__, code="SEND_SUCCESS", defaults={ 'summary': "Email Sent to Bidders", 'description': send_email_success_msg }) messages.success(request, user_message[0].description + recipient_string) return mail_form
def enviar_notificação_de_email(self): """Notifica inscritos no boletim de notícias a respeito da criação de um novo artigo.""" def construir_email(email): """Controe um email para ser enviado por mail.send_many.""" return { 'recipients': [email], 'template': 'artigo_criado', 'context': {'artigo': self, 'site': Site.objects.get_current()} } emails = map(lambda inscrito: construir_email(inscrito.email), Inscrito.objects.filter(ativo=True)) mail.send_many(emails) mail.send_queued()
def handle(self, *args, **options): pending_messages = Message.objects.filter(status="PENDING") for message in pending_messages: print("Processing message #{}...".format(message.pk)) # Change status message.status = 'PROCESSING' message.save() # Create post-office EmailTemplate template_name = "mailer_{}".format(message.pk) while EmailTemplate.objects.filter(name=template_name).exists(): template_name = template_name + "_" template = EmailTemplate.objects.create(name=template_name, subject=message.subject, description="Automatically generated template for Message #{}".format(message.pk), content=strip_tags(message.body), html_content=message.body) from_address = "Fudul <{}>".format(message.from_address) # Generate list of receipts user_pool = User.objects.filter(is_active=True).exclude(email="").distinct() if message.target == 'ALL': receipts = user_pool elif message.target == 'COLLEGES': receipts = user_pool.filter(profile__group__in=message.groups.all()) elif message.target == 'INSTITUTIONS': receipts = user_pool.filter(profile__group__institution__in=message.institutions.all()) elif message.target == 'BATCHES': receipts = user_pool.filter(profile__level__in=message.levels.all()) # Aaand send! email_addresses = receipts.values_list('email', 'profile__alternative_email') messages = [] for email, alternative_email in email_addresses: msg = {'sender': from_address, 'recipients': email, 'cc': alternative_email or None, 'render_on_delivery': True, 'template': template_name} messages.append(msg) mail.send_many(messages) message.status = 'SENT' message.save()
def send_mail(self, request, to_list): mail_form = AdHocEmailForm(request.POST) mail_form.fields['to'].choices = to_list if not request.user.is_superuser: mail_form.fields['sender'].widget = HiddenInput() if mail_form.is_valid(): email_batch = [] recipient_string = "" if request.user.is_superuser: sender = mail_form.cleaned_data['sender'] else: sender = request.user.email for email in mail_form.cleaned_data['to']: email_batch += [{ 'sender': sender, 'recipients': [email], 'subject': mail_form.cleaned_data['subject'], 'html_message': mail_form.cleaned_data['html_message'], }] if len(recipient_string) > 0: recipient_string = "%s, %s" % (recipient_string, email) else: recipient_string = email mail.send_many(email_batch) user_message = UserMessage.objects.get_or_create( view=self.__class__.__name__, code="SEND_SUCCESS", defaults={ 'summary': "Email Sent to Bidders", 'description': send_email_success_msg }) messages.success(request, user_message[0].description + recipient_string) return mail_form
def send_reminder_email(): LOGGER.debug("Processing operator reminder emails...") expiry_date_begin = datetime.datetime.combine( datetime.datetime.now( pytz.utc), datetime.time(), tzinfo=pytz.utc) + relativedelta( months=int(settings.REMINDER_EMAIL_NOTICE_MONTHS)) expiry_date_end = datetime.datetime.combine(expiry_date_begin, datetime.time( 23, 59, 59, 999999), tzinfo=pytz.utc) LOGGER.debug("Processing registrations expiring between {} and {}".format( expiry_date_begin, expiry_date_end)) expiring_operators = Operator.objects.filter( registration_number__expiry_date__gt=expiry_date_begin, registration_number__expiry_date__lte=expiry_date_end, ) email_list = [] for operator in expiring_operators: reminder_email = { "sender": settings.AGRI_EMAIL, "recipients": [operator.email_address], "template": "reminder_email", "context": operator, } email_list.append(reminder_email) if len(email_list) > 0: LOGGER.info("Sending remider emails to {} operators".format( len(email_list))) mail.send_many(email_list) else: LOGGER.debug("No reminder emails to send this time.")
def send(self): for msgs in self.generate_messages(): mail.send_many(msgs)
def send_notif(self, notif_list=None): # Had to do this because signals refuse to work. if isinstance(self, Post): post = self notif_verb = "has posted on" elif isinstance(self, Comment): post = self.parent_post.all()[0] # There is only one parent_post notif_verb = "has commented on" wall = post.wall if not notif_list: # Get my wall and posts which I am to get notifs for notif_list = User.objects.filter( post.notify_users_query() | wall.notify_users_query()).distinct() mail_list = [] notif_list = list(notif_list) notif_list.remove(self.by) message = {} # to send push notifications message[ 'title'] = self.by.first_name + " " + notif_verb + " " + post.wall.name + "'s Wall" message['message'] = self.description.strip()[:50] send_push(notif_list, message) for recipient in notif_list: # Check if receipient already has notif on this post curr_notif = get_object_or_None(recipient.notifications.unread(), target_object_id=post.id) if curr_notif: curr_notif.mark_as_read() by = self.by # Now create a new unread notif if recipient != by: notifications.notify.send( sender=by, # The model who wrote the post - USER recipient=recipient, # The model who sees the post - USER verb=notif_verb, # verb action_object= self, # the model on which something happened - POST target=post, # The model which got affected - POST # In case you wish to get the wall on which it hapened, use target.wall (this is to ensure uniformity in all notifications) description='wall:' + str(wall.pk), ) notification = Bunch(actor=by, verb=notif_verb, target=post, action_object=self, timestamp=datetime.datetime.now()) if recipient.profile.send_mails: unsubscribe_link = recipient.profile.create_unsubscribe_link( ) mail_list.append({ 'sender': settings.DEFAULT_FROM_EMAIL, 'recipients': [recipient.email], 'template': 'notification.email', 'context': { 'subject': post.subject.strip(), 'user': recipient, 'notification': notification, 'FEST_NAME': settings.FEST_NAME, 'SITE_URL': settings.SITE_URL, 'unsubscribe_link': unsubscribe_link }, 'headers': { 'List-Unsubscribe': unsubscribe_link }, }) if settings.SEND_NOTIF_EMAILS: mail.send_many(mail_list)