def post(self, request, *args, **kwargs): params = json.loads(request.body.decode()) mail_managers( 'Новая заявка на кредит', str(params), ) return HttpResponse('OK')
def process_response(self, request, response): "Send broken link emails and calculate the Etag, if needed." if response.status_code == 404: if settings.SEND_BROKEN_LINK_EMAILS and not settings.DEBUG: # If the referrer was from an internal link or a non-search-engine site, # send a note to the managers. domain = request.get_host() referer = request.META.get('HTTP_REFERER', None) is_internal = _is_internal_request(domain, referer) path = request.get_full_path() if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer): ua = request.META.get('HTTP_USER_AGENT', '<none>') ip = request.META.get('REMOTE_ADDR', '<none>') mail_managers("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain), "Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" \ % (referer, request.get_full_path(), ua, ip), fail_silently=True) return response # Use ETags, if requested. if settings.USE_ETAGS: if response.has_header('ETag'): etag = response['ETag'] else: etag = '"%s"' % hashlib.md5(response.content).hexdigest() if response.status_code >= 200 and response.status_code < 300 and request.META.get('HTTP_IF_NONE_MATCH') == etag: cookies = response.cookies response = http.HttpResponseNotModified() response.cookies = cookies else: response['ETag'] = etag return response
def save(self, new_data): today = datetime.date.today() c = self.get_comment(new_data) for old in Comment.objects.filter(content_type__id__exact=new_data["content_type_id"], object_id__exact=new_data["object_id"], user__id__exact=self.get_user_id()): # Check that this comment isn't duplicate. (Sometimes people post # comments twice by mistake.) If it is, fail silently by pretending # the comment was posted successfully. if old.submit_date.date() == today and old.comment == c.comment \ and old.rating1 == c.rating1 and old.rating2 == c.rating2 \ and old.rating3 == c.rating3 and old.rating4 == c.rating4 \ and old.rating5 == c.rating5 and old.rating6 == c.rating6 \ and old.rating7 == c.rating7 and old.rating8 == c.rating8: return old # If the user is leaving a rating, invalidate all old ratings. if c.rating1 is not None: old.valid_rating = False old.save() c.save() # If the commentor has posted fewer than COMMENTS_FIRST_FEW comments, # send the comment to the managers. if self.user_cache.comment_set.count() <= settings.COMMENTS_FIRST_FEW: message = ngettext('This comment was posted by a user who has posted fewer than %(count)s comment:\n\n%(text)s', 'This comment was posted by a user who has posted fewer than %(count)s comments:\n\n%(text)s', settings.COMMENTS_FIRST_FEW) % \ {'count': settings.COMMENTS_FIRST_FEW, 'text': c.get_as_text()} mail_managers("Comment posted by rookie user", message) if settings.COMMENTS_SKETCHY_USERS_GROUP and settings.COMMENTS_SKETCHY_USERS_GROUP in [g.id for g in self.user_cache.get_group_list()]: message = _('This comment was posted by a sketchy user:\n\n%(text)s') % {'text': c.get_as_text()} mail_managers("Comment posted by sketchy user (%s)" % self.user_cache.username, c.get_as_text()) return c
def sendbotserrorreport(subject,reporttext): if botsglobal.ini.getboolean('settings','sendreportiferror',False): from django.core.mail import mail_managers try: mail_managers(subject, reporttext) except: botsglobal.logger.debug(u'Error in sending error report: %s',txtexc())
def suggest_content(request): if request.method == 'POST': form = SubmissionForm(request.POST) if form.is_valid(): #do something coords, types, formats, updates ="", "", "", "" for c in request.POST.getlist("coord_system"): coords = coords + " EPSG:" + CoordSystem.objects.get(pk=c).EPSG_code.__str__() for t in request.POST.getlist("types"): types = types + " " + UrlType.objects.get(pk=t).url_type for f in request.POST.getlist("formats"): formats = formats + " " + DataType.objects.get(pk=f).data_type for u in request.POST.getlist("update_frequency"): if u: updates = updates + " " + UpdateFrequency.objects.get(pk=u).update_frequency data = { "submitter": request.user.username, "submit_date": datetime.now(), "dataset_name": request.POST.get("dataset_name"), "organization": request.POST.get("organization"), "copyright_holder": request.POST.get("copyright_holder"), "contact_email": request.POST.get("contact_email"), "contact_phone": request.POST.get("contact_phone"), "url": request.POST.get("url"), "time_period": request.POST.get("time_period"), "release_date": request.POST.get("release_date"), "area_of_interest": request.POST.get("area_of_interest"), "update_frequency": updates, "coord_system": coords, "types": types, "formats": formats, "usage_limitations": request.POST.get("usage_limitations"), "collection_process": request.POST.get("collection_process"), "data_purpose": request.POST.get("data_purpose"), "intended_audience": request.POST.get("intended_audience"), "why": request.POST.get("why"), } subject, user_email = 'OpenDataPhilly - Data Submission', (request.user.first_name + " " + request.user.last_name, request.user.email) text_content = render_to_string('submit_email.txt', data) text_content_copy = render_to_string('submit_email_copy.txt', data) mail_managers(subject, text_content) msg = EmailMessage(subject, text_content_copy, to=user_email) msg.send() sug_object = Submission() sug_object.user = request.user sug_object.email_text = text_content sug_object.save() return render_to_response('thanks.html', context_instance=RequestContext(request)) else: form = SubmissionForm() return render_to_response('submit.html', {'form': form}, context_instance=RequestContext(request))
def _get_page_by_untyped_arg(page_lookup, request, site_id): """ The `page_lookup` argument can be of any of the following types: - Integer: interpreted as `pk` of the desired page - String: interpreted as `reverse_id` of the desired page - `dict`: a dictionary containing keyword arguments to find the desired page (for instance: `{'pk': 1}`) - `Page`: you can also pass a Page object directly, in which case there will be no database lookup. - `None`: the current page will be used """ if page_lookup is None: return request.current_page if isinstance(page_lookup, Page): return page_lookup if isinstance(page_lookup, basestring): page_lookup = {'reverse_id': page_lookup} elif isinstance(page_lookup, (int, long)): page_lookup = {'pk': page_lookup} elif not isinstance(page_lookup, dict): raise TypeError('The page_lookup argument can be either a Dictionary, Integer, Page, or String.') page_lookup.update({'site': site_id}) try: return get_page_queryset(request).get(**page_lookup) except Page.DoesNotExist: site = Site.objects.get_current() subject = _('Page not found on %(domain)s') % {'domain':site.domain} body = _("A template tag couldn't find the page with lookup arguments `%(page_lookup)s\n`. " "The URL of the request was: http://%(host)s%(path)s") \ % {'page_lookup': repr(page_lookup), 'host': site.domain, 'path': request.path} if settings.DEBUG: raise Page.DoesNotExist(body) else: mail_managers(subject, body, fail_silently=True) return None
def test_connection_arg(self): """Test connection argument to send_mail(), et. al.""" mail.outbox = [] # Send using non-default connection connection = mail.get_connection('mail.custombackend.EmailBackend') send_mail('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, 'Subject') connection = mail.get_connection('mail.custombackend.EmailBackend') send_mass_mail([ ('Subject1', 'Content1', '*****@*****.**', ['*****@*****.**']), ('Subject2', 'Content2', '*****@*****.**', ['*****@*****.**']), ], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 2) self.assertEqual(connection.test_outbox[0].subject, 'Subject1') self.assertEqual(connection.test_outbox[1].subject, 'Subject2') connection = mail.get_connection('mail.custombackend.EmailBackend') mail_admins('Admin message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Admin message') connection = mail.get_connection('mail.custombackend.EmailBackend') mail_managers('Manager message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Manager message')
def handle_valid(self, *args, **kwargs): """ Send the email. """ recipients = [recipient.email for recipient in \ preferences.ContactPreferences.email_recipients.all()] if not recipients: mail_managers( 'Error: No email address specified', 'Users are trying to contact the site for which no \ email address could be found.', fail_silently=False ) return None else: name = self.cleaned_data['name'] email = self.cleaned_data['email_address'] current_site = Site.objects.get_current() message = self.cleaned_data['message'] subject = "Contact Message from %s" % current_site.name from_address = "%s <%s>" % (name, email) mail = EmailMessage( subject, message, from_address, recipients, headers={'From': from_address, 'Reply-To': from_address} ) mail.send(fail_silently=False)
def send(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): msg = Message() msg.username = form.cleaned_data['username'] msg.email = form.cleaned_data['email'] msg.phone = form.cleaned_data['phone'] msg.location = form.cleaned_data['location'] msg.job = form.cleaned_data['job'] msg.description = form.cleaned_data['description'] msg.area = form.cleaned_data['area'] try: msg.save() mail_managers('ZUBIRD webpage - new message received', 'Otrzymałeś nową wiadomość.') except Exception as e: import traceback logger.error(str(e)) logger.error(traceback.format_exc()) return render_to_response('error.html', {}) return render_to_response('thanks.html', {}) else: return render_to_response('base.html', Context({'form':form})) else: return index(request)
def pre_register_user(user_data, home_url): mail_managers( subject = u'[Estelcon Admin] Nueva preinscripción en la Estelcon: %s %s' % ( user_data['first_name'], user_data['last_name'] ), message = u''' Se ha preinscrito un nuevo usuario con nombre %s %s. - Alias: %s - Smial: %s - Email: %s - Teléfono: %s - Población: %s - Edad: %s - Viernes / sábado: %s - Sábado / domingo: %s - Domingo / lunes + cena de gala: %s Notas: %s ''' % (user_data['first_name'], user_data['last_name'], user_data['alias'], user_data['smial'], user_data['email'], user_data['phone'], user_data['city'], user_data['age'], u'Sí' if user_data['day_1'] else u'No', u'Sí' if user_data['day_2'] else u'No', u'Sí' if user_data['day_3'] else u'No', user_data['notes']), )
def contact(request): mail_sent = None if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): url = request.build_absolute_uri() name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] subject = u'Contato de ' + name message = form.cleaned_data['message'] message = u'Mensagem enviada por %s <%s> %s \n\n%s \n\n\nMensagem enviada através da página:\n%s' % (name, email, phone, message, url) try: mail_managers(subject, message, fail_silently = False) mail_sent = True except Exception as e: mail_sent = False if settings.DEBUG: raise # reraises the exception else: form = ContactForm() template = loader.get_template('contact/contact.html') context = RequestContext(request, { 'form' : form, 'mail_sent' : mail_sent, }) return HttpResponse(template.render(context))
def send_missing_mail(reverse_id, request): site = Site.objects.get_current() mail_managers(_('Reverse ID not found on %(domain)s') % {'domain':site.domain}, _("A page_id_url template tag didn't found a page with the reverse_id %(reverse_id)s\n" "The url of the page was: http://%(host)s%(path)s") % {'reverse_id':reverse_id, 'host':site.domain, 'path':request.path}, fail_silently=True)
def _missing_image(self, source): """ Handles what happens in case of a missing image """ if settings.THUMBNAIL_SEND_MISSING_IMAGE_EMAIL: mail_managers('Missing image', 'The following image is missing: %s' % source.url, fail_silently=True) return self.dummy_image(800, 600)
def add_post(request): """Submit a new post. """ if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): # Save the submission post = form.save(commit=False) post.created_by = request.user post.save() # Notify managers of new submission c = Context({'post': post}) t = loader.get_template('posts/post_email.txt') text_message = t.render(c) t = loader.get_template('posts/post_email.html') html_message = t.render(c) mail_managers('New post submission', text_message, fail_silently=True, html_message=html_message) # Confirm submission messages.success(request, 'Thank you. Your post has been submitted.') return HttpResponseRedirect(reverse('post_list_view')) else: form = PostForm() return render_to_response('posts/post_add.html', {'form': form}, context_instance=RequestContext(request))
def notify_managers(backend, details, user=None, *args, is_new=False, **kwargs): if not is_new: return title = "New {} User: {}".format(backend.name, user.email) mail_managers(title, title)
def send_email(user, data): """ Sends an email with a new data submission, and stores the submission as a suggestion """ subject, user_email = 'OpenDataCincy - Data Submission', (user.get_full_name(), user.email) text_content = render_to_string('submit_email.txt', data) text_content_copy = render_to_string('submit_email_copy.txt', data) mail_managers(subject, text_content) msg = EmailMessage(subject, text_content_copy, to=user_email) msg.send() # Create new user submission object. sug_object = Submission() sug_object.user = user sug_object.email_text = text_content # Prep data for serialization data['submit_date'] = str(data.get('submit_date', '')) data['release_date'] = str(data.get('release_date', '')) try: sug_object.json_text = json.dumps(data) except TypeError as ex: print data raise TypeError(ex) # Something was not consumed by the json serializer.. # sug_object.json_text = '' # Save the submission sug_object.save() return sug_object
def _process(self, *args, **kwargs): output = u"%s\n" % self.job_data job_url = reverse('fwjob-detail', kwargs={'pk': self.pk}) domain = Site.objects.all()[0].domain for command in self.job_data["commands"]: output += command + "\n" p = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output += p.communicate()[0].decode("utf-8") if p.returncode != 0: email_msg = "Cook failed for job http://%s%s" % (domain, job_url) mail_managers("[Chef] Cook failed", email_msg, fail_silently=True) send_mail("[Chef] Cook failed", email_msg, settings.DEFAULT_FROM_EMAIL, [self.user.email], fail_silently=True) self.status = "FAILED" self.build_log = output self.save() return email_msg = "Cook finished: http://%s%s" % (domain, job_url) send_mail("[Chef] Cook finished", email_msg, settings.DEFAULT_FROM_EMAIL, [self.user.email], fail_silently=True) self.status = "FINISHED" self.save()
def handle(self, *args, **options): result = 0 subject = "Deployment Test Message" message = "Deployment Test Message Body. This was sent using" \ " django_deployment to test the email configuration of a" \ " deployed project." sent_msg = False if options["verbosity"] > "1": print "Using %s" % settings.EMAIL_BACKEND if options['admins']: mail_admins(subject, message, fail_silently=False) sent_msg = True if options['managers']: mail_managers(subject, message, fail_silently=False) sent_msg = True if args: send_mail(subject, message, options["from"], args, fail_silently=False) elif not sent_msg: raise CommandError("No recipient addresses were specified on the" " command line") return result
def create_deferred(secret_mail, mail_bytes, spam=False, sender_email=None, subject=unknown_foimail_subject, body=unknown_foimail_message, request=None): from .models import DeferredMessage mail_string = '' if mail_bytes is not None: mail_string = base64.b64encode(mail_bytes).decode("utf-8") DeferredMessage.objects.create( recipient=secret_mail, sender=sender_email or '', mail=mail_string, spam=spam, request=request ) if spam: # Do not notify on identified spam return with override(settings.LANGUAGE_CODE): url = reverse('admin:foirequest_deferredmessage_changelist') mail_managers( subject, body % { 'address': secret_mail, 'url': settings.SITE_URL + url } )
def handle_comment_form(self): form = self.get_comment_form(self.request.POST) if not form.is_valid(): return False form.instance.user = self.request.user form.instance.project = self.object form.save() form.instance.new = True url = self.request.build_absolute_uri(form.instance.get_absolute_url()) subject = "{}: {} -> {}".format( _("Comment posted"), self.request.user, self.object, ) message = "{}\n\n{}\n{}\n\n{} ({})".format( url, form.instance.get_scope_display(), form.instance.content, self.request.user, self.request.user.email, ) mail_managers(subject, message) response = render_to_string("projects/_project_comment.html", {'c': form.instance, }, request=self.request) return response
def submit_game(request): form = GameForm(request.POST or None, request.FILES or None) if request.method == "POST" and form.is_valid(): game = form.save() submission = GameSubmission(user=request.user, game=game) submission.save() # Notify managers a game has been submitted subject = u"New game submitted: {0}".format(game.name) admin_url = reverse("admin:games_game_change", args=(game.id, )) body = u""" The game {0} has been added by {1}. It can be modified and published at https://lutris.net{2} """.format(game.name, request.user, admin_url) mail_managers(subject, body) redirect_url = request.build_absolute_uri(reverse("game-submitted")) # Enforce https if not settings.DEBUG: redirect_url = redirect_url.replace('http:', 'https:') LOGGER.info('Game submitted, redirecting to %s', redirect_url) return redirect(redirect_url) return render(request, 'games/submit.html', {'form': form})
def get(self, request, code, *args, **kwargs): try: o = models.Code.objects.get(code=code) if (timezone.now() - o.created_at).days > settings.VALIDATE_LINK_DAYS: o.delete() messages.error(request, _("validation code too old. Please generate a new code")) return redirect("users:login") except models.Code.DoesNotExist: messages.error(request, _("Invalid validation code.")) return redirect("users:login") try: user = models.User.objects.get(email=o.email) if not user.is_active: messages.error(request, _("Inactive user.")) return redirect("users:login") messages.success(request, _("Welcome back!")) except models.User.DoesNotExist: user = models.User.objects.create_user(o.email) title = "New email User: {}".format(o.email) mail_managers(title, title) messages.success(request, _("Welcome! You can set your password any time from the menu above.")) user.backend = "django.contrib.auth.backends.ModelBackend" login(request, user) o.delete() return redirect(settings.LOGIN_REDIRECT_URL)
def send_message(request): """ On a get request, show a form to allow visitors to send me a message. On a post request, save the message in the database and send me an email. """ if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): message = Message(sender_name=form.cleaned_data['sender_name'], sender_email=form.cleaned_data['sender_email'], body=form.cleaned_data['body']) if form.cleaned_data['ham_trap']: message.is_spam = True else: message_body = "%s (%s) said:\n\n%s\n" % ( form.cleaned_data['sender_name'], form.cleaned_data['sender_email'], form.cleaned_data['body']) mail_managers('photosbymonika.com contact message', message_body) message.save() return HttpResponseRedirect('%s?sent' % reverse(send_message)) else: form = MessageForm() context = { 'form': form, 'sent': request.GET.has_key('sent'), } context.update(csrf(request)) return render_to_response('contact/send_message.html', context, context_instance=RequestContext(request))
def test_empty_admins(self): """ Test that mail_admins/mail_managers doesn't connect to the mail server if there are no recipients (#9383) """ old_admins = settings.ADMINS old_managers = settings.MANAGERS settings.ADMINS = settings.MANAGERS = [('nobody','*****@*****.**')] mail.outbox = [] mail_admins('hi', 'there') self.assertEqual(len(mail.outbox), 1) mail.outbox = [] mail_managers('hi', 'there') self.assertEqual(len(mail.outbox), 1) settings.ADMINS = settings.MANAGERS = [] mail.outbox = [] mail_admins('hi', 'there') self.assertEqual(len(mail.outbox), 0) mail.outbox = [] mail_managers('hi', 'there') self.assertEqual(len(mail.outbox), 0) settings.ADMINS = old_admins settings.MANAGERS = old_managers
def feedback(request): if request.user.is_authenticated(): form_cls = FeedbackForm else: form_cls = FeedbackAnonymousForm if request.POST: form = form_cls(request.POST) if form.is_valid(): instance = form.save(commit=False) if request.user.is_authenticated(): instance.user = request.user instance.save() mail_context = { 'instance': instance, } manager_text = render_to_string('home/mail/feedback.txt', mail_context) manager_html = render_to_string('home/mail/feedback.html', mail_context) mail_managers(u'Новый вопрос на сайте «Томат»', manager_text, html_message=manager_html) return HttpResponseRedirect('.?thank=you') else: form = form_cls() context = { 'form': form, 'is_sended': 'thank' in request.GET, } return render(request, 'home/feedback.html', context)
def _post_create_email_notify_managers(sender, instance, created, **kwargs): """ Sends a new flag notification email to the managers. """ if created: accused = instance.flagged_content.creator accusation = instance.comment informant = instance.flagged_content.creator flagged_object = instance.flagged_content.content_object flagged_object_url = None if hasattr(flagged_object, "get_absolute_url"): flagged_object_url = flagged_object.get_absolute_url() subject = """"%s" got flagged as inappropriate""" % unicode(flagged_object) message = """ Content: "%s" Content URL: "%s" Informant: "%s" Accused: "%s" Accusation: "%s" """ % ( unicode(flagged_object), flagged_object_url, informant, accused, accusation, ) mail_managers(subject, message)
def comment_notification(sender, comment, request, **kwargs): subject = 'New comment on %s' % str(comment.content_object) msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR']) msg += u'Comment text:\n\n%s\n' % comment.comment mail_managers(subject, msg, fail_silently=True)
def form_valid(self, form): u = self.request.user data = form.cleaned_data form_name = get_user_next_form(u) logger.info("User %s filled %s" % (u, form_name)) Answer.objects.create(user=u, q13e_slug=form_name, data=data) # Save personal information if form_name == FORM_NAMES[0]: dirty = False if not u.first_name: u.first_name = data['hebrew_first_name'] dirty = True if not u.last_name: u.last_name = data['hebrew_last_name'] dirty = True if dirty: u.save() message = "\n".join(u"{label}: {html}".format(**fld) for fld in get_pretty_answer(form, data)['fields']) mail_managers(u"{}: {hebrew_last_name} {hebrew_first_name}".format( _("New User"), **data), message) if get_user_next_form(u) is None: messages.success(self.request, _("Registration completed! Thank you very much!")) mail_managers(_("User registered: %s") % u, ":-)") return redirect('dashboard') messages.success(self.request, _("'%s' was saved.") % form.form_title) return redirect('register')
def process_response(self, request, response): "Check for a flat page (for 404s) and calculate the Etag, if needed." if response.status_code == 404: if settings.SEND_BROKEN_LINK_EMAILS: # If the referrer was from an internal link or a non-search-engine site, # send a note to the managers. domain = http.get_host(request) referer = request.META.get('HTTP_REFERER', None) is_internal = _is_internal_request(domain, referer) path = request.get_full_path() if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer): ua = request.META.get('HTTP_USER_AGENT', '<none>') mail_managers("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain), "Referrer: %s\nRequested URL: %s\nUser agent: %s\n" % (referer, request.get_full_path(), ua)) return response # Use ETags, if requested. if settings.USE_ETAGS: etag = md5(response.content).hexdigest() if request.META.get('HTTP_IF_NONE_MATCH') == etag: response = http.HttpResponseNotModified() else: response['ETag'] = etag return response
def test_connection_arg(self): """Test connection argument to send_mail(), et. al.""" mail.outbox = [] # Send using non-default connection connection = mail.get_connection("regressiontests.mail.custombackend.EmailBackend") send_mail("Subject", "Content", "*****@*****.**", ["*****@*****.**"], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, "Subject") connection = mail.get_connection("regressiontests.mail.custombackend.EmailBackend") send_mass_mail( [ ("Subject1", "Content1", "*****@*****.**", ["*****@*****.**"]), ("Subject2", "Content2", "*****@*****.**", ["*****@*****.**"]), ], connection=connection, ) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 2) self.assertEqual(connection.test_outbox[0].subject, "Subject1") self.assertEqual(connection.test_outbox[1].subject, "Subject2") connection = mail.get_connection("regressiontests.mail.custombackend.EmailBackend") mail_admins("Admin message", "Content", connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, "[Django] Admin message") connection = mail.get_connection("regressiontests.mail.custombackend.EmailBackend") mail_managers("Manager message", "Content", connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, "[Django] Manager message")
def form_valid(self, form): subject = _('[{title}] {subject}').format( title=self.object.title, subject=form.cleaned_data['subject'] ) message = _( 'Reporter: {email}\n' \ 'Collection: {title}\n' \ 'Message:\n{message}' ).format( email=form.cleaned_data['email'], title=self.object.title, message=form.cleaned_data['message'] ) mail_managers(subject, message, fail_silently=False) messages.success(self.request, _('Your report has been sent to administrators.')) return super(Complain, self).form_valid(form)
def check_throttle(user, klass): if user.is_authenticated and not user.trusted(): throttle_settings = settings.FROIDE_CONFIG.get('request_throttle', None) qs, date_param = klass.objects.get_throttle_filter(user) throttle_kind = throttle(qs, throttle_settings, date_param=date_param) if throttle_kind: if settings.FROIDE_CONFIG.get('request_throttle_mail'): mail_managers(_('User exceeded request limit'), str(user.pk)) message = _('You exceeded your request limit of %(count)s requests in %(time)s.') return forms.ValidationError( message, params={ 'count': throttle_kind[0], 'time': format_seconds(throttle_kind[1]) }, code='throttled' )
def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() new_user.refresh_from_db() raw_password = form.cleaned_data.get('password1') user = authenticate(email=new_user.email, password=raw_password) login(request, user) mail_managers("Ny brukar %s" % new_user.email, "Sjekk database for ny brukar\n" + json.dumps(UserSerializer(new_user).data), fail_silently=True) return HttpResponseRedirect("/") else: form = UserCreationForm() return render(request, "registration/register.html", {'form': form})
def post(request, slug): competition = get_object_or_404(Competition, slug=slug) if competition.is_payment_valid(request, request.POST.get('razorpay_order_id'), request.POST.get('razorpay_payment_id'), request.POST.get('razorpay_signature')): grant_access_to_competition(request.user, competition) mail_managers( '[eSorobrain.com] New Competition Registered', f'{request.user.username}: {request.user.name} with email: {request.user.email} has bought competition: {competition.title} at {timezone.now()}.', fail_silently=True ) invoice = Invoice(user=request.user, description=f"Competition bought - {competition.title}", amount=competition.sub_total) invoice.save() msg = render_to_string('mails/txt/product_bought.txt', {'user': request.user, 'content_type': 'competition', 'product': competition}) msg_html = render_to_string('mails/html/invoice.html', {'invoice': invoice}) invoice.invoice_html = msg_html invoice.save() send_product_bought_mail('[Sorobrain] New Competition Registered', msg, msg_html, to=[request.user.email]) return JsonResponse({'status': True, 'redirect': competition.get_compete_url()})
def post(request, slug): w = get_object_or_404(Workshop, slug=slug) if request.user.points >= w.sub_total: request.user.points -= w.sub_total request.user.save() grant_access_to_workshop(request.user, w) add_ledger_debit(request.user, w.sub_total, f"Bought workshop {w.title}") mail_managers( '[eSorobrain.com] New Workshop Registered with Soromoney', f'{request.user.username}: {request.user.name} with email: {request.user.email} has bought workshop: {w.title} at {timezone.now()} with Soromoney.', fail_silently=True ) else: messages.add_message(request, messages.WARNING, "You don't have enough points to register for this workshop!") return redirect(reverse('workshops:workshop_store', args=[slug])) messages.add_message(request, messages.SUCCESS, "Success! You now have access to the workshop!") return redirect(reverse('workshops:workshop_access', args=[slug]))
def handle(self, *args: Any, **kwargs: str) -> None: if settings.WARN_NO_EMAIL: raise CommandError("Outgoing email not yet configured, see\n " "https://zulip.readthedocs.io/en/latest/production/email.html") message = ("Success! If you receive this message, you've " "successfully configured sending email from your " "Zulip server. Remember that you need to restart " "the Zulip server with /home/zulip/deployments/current/scripts/restart-server " "after changing the settings in /etc/zulip before your changes will take effect.") send_mail("Zulip email test", message, FromAddress.SUPPORT, kwargs['email']) send_mail("Zulip noreply email test", message, FromAddress.tokenized_no_reply_address(), kwargs['email']) if kwargs['managers']: mail_managers("Zulip manager email test", "This email was sent to the site managers.") if kwargs['admins']: mail_admins("Zulip admins email test", "This email was sent to the site admins.")
def upload_file(request): """ Displays and validates the upload form, and redirects to a confirmation page after the upload completes. """ message = None if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] path = handle_uploaded_file(file) # send mail to staff t = loader.get_template('emails/file_uploaded.txt') subject = "File Upload" c = Context({ 'file': file, 'path': path, 'file_url': request.build_absolute_uri(path), 'form': request.POST, }) body = t.render(c) mail_managers(subject, body, fail_silently=False) if request.user.is_authenticated() or form.cleaned_data['email']: if request.user.is_authenticated(): recipient = request.user.email else: recipient = form.cleaned_data['email'] t = loader.get_template('emails/user_file_uploaded.txt') subject = "[Mimic OOS] File Upload Confirmed" body = t.render(c) send_mail(subject, body, '*****@*****.**', [recipient], fail_silently=False) return HttpResponseRedirect(reverse('upload_ok')) else: message = "Error: There was a problem with your submission. Refer to the messages below and try again." else: form = UploadFileForm() return render_to_response('uploads/upload.html', { 'form': form, 'message': message, }, context_instance=RequestContext(request))
def send_email(self): """Send email if form is valid.""" name = self.cleaned_data['name'] subject = self.cleaned_data['subject'] from_email = self.cleaned_data['from_email'] message = MESSAGE_TEMPLATE.format(message=self.cleaned_data['message'], user=name, email=from_email), mail_managers(subject, message) if self.cleaned_data.get('cc_sender'): send_mail( subject, message, settings.DEFAULT_FROM_EMAIL, [from_email], fail_silently=False, )
def post(request, slug): w = get_object_or_404(Workshop, slug=slug) if w.is_payment_valid(request, request.POST.get('razorpay_order_id'), request.POST.get('razorpay_payment_id'), request.POST.get('razorpay_signature')): grant_access_to_workshop(request.user, w) mail_managers( '[eSorobrain.com] New Workshop Registered', f'{request.user.username}: {request.user.name} with email: {request.user.email} has bought workshop: {w.title} at {timezone.now()}.', fail_silently=True ) invoice = Invoice(user=request.user, description=f"Workshop bought - {w.title}", amount=w.sub_total) invoice.save() msg = render_to_string('mails/txt/product_bought.txt', {'user': request.user, 'content_type': 'workshop', 'product': w}) msg_html = render_to_string('mails/html/invoice.html', {'invoice': invoice}) invoice.invoice_html = msg_html invoice.save() send_product_bought_mail('[Sorobrain] New Workshop Registered', msg, msg_html, to=[request.user.email]) return JsonResponse({'status': True, 'redirect': reverse('workshops:workshop_store', args=[slug])})
def clean(self): email = self.data.get('email').strip() if email: try: user = User.objects.get(email__iexact=email) except MultipleObjectsReturned: mail_managers("Multiple email in users", email) raise ValidationError(u'Error, comunicate con nosotros.') except User.DoesNotExist: raise ValidationError( u'No hay usuarios registrados con ese email.') if user.is_active: raise ValidationError( u'El usuario correspondiente a ese email ya está activo.') else: raise ValidationError(u'Tenés que ingresar un email válido') return self.data
def send_confirmation_mail(self, request, emailconfirmation, signup): """ Do not just fail for typo in recipient email. """ try: super().send_confirmation_mail(request, emailconfirmation, signup) except smtplib.SMTPRecipientsRefused as e: error_msg = ugettext( 'Confirmation email has NOT been sent to {} (recipient refused).' ).format(emailconfirmation.email_address.email) logger.error(error_msg) self.add_message( request, messages.constants.ERROR, error_msg + ugettext('\nAdministrators have been notified.'), ) mail_managers(error_msg, str(e))
def save(self, request): contact = self.cleaned_data['contact'] description = self.cleaned_data['description'] suggestion = Suggestion(contact=contact, description=description, ip=request.META['REMOTE_ADDR']) if request.user.is_authenticated(): suggestion.user = request.user suggestion.save() mail_managers( u'Nowa sugestia na stronie WolneLektury.pl', u'''\ Zgłoszono nową sugestię w serwisie WolneLektury.pl. http://%(site)s%(url)s Użytkownik: %(user)s Kontakt: %(contact)s %(description)s''' % { 'site': Site.objects.get_current().domain, 'url': reverse('admin:suggest_suggestion_change', args=[suggestion.id]), 'user': str(request.user) if request.user.is_authenticated() else '', 'contact': contact, 'description': description, }, fail_silently=True) if email_re.match(contact): send_mail(u'[WolneLektury] ' + ugettext(u'Thank you for your suggestion.'), ugettext(u"""\ Thank you for your comment on WolneLektury.pl. The suggestion has been referred to the project coordinator.""") + u""" -- """ + ugettext(u'''Message sent automatically. Please do not reply.'''), '*****@*****.**', [contact], fail_silently=True)
def custom_signup(self, request, user): # send a notification email; not doing this as part of the adapter # b/c sometimes registration forms/serializers have additional checks # to make before _actually_ saving the user - this fn runs after those if app_settings.ASTROSAT_USERS_NOTIFY_SIGNUPS: adapter = get_adapter(request) subject = adapter.format_email_subject(f"new user signup: {user}") message = f"User {user.email} signed up for an account." mail_managers(subject, message, fail_silently=True) customer_name = self.validated_data.get("customer_name") if customer_name: # create a customer and customer-user as part of the signup process # (this bypasses creating them via separate DRF Views) (customer, _) = Customer.objects.get_or_create(name=customer_name) customer.add_user(user, type="MANAGER", status="PENDING") return super().custom_signup(request, user)
def handle(self, *args: Any, **kwargs: str) -> None: subject = "Zulip Test email" message = ( "Success! If you receive this message, you've " "successfully configured sending email from your " "Zulip server. Remember that you need to restart " "the Zulip server with /home/zulip/deployments/current/scripts/restart-server " "after changing the settings in /etc/zulip before your changes will take effect." ) sender = FromAddress.SUPPORT send_mail(subject, message, sender, kwargs['email']) if kwargs['managers']: mail_managers(subject, "This email was sent to the site managers.") if kwargs['admins']: mail_admins(subject, "This email was sent to the site admins.")
def project_approval(request, slug, action): project = get_object_or_404(Project, slug=slug) project.is_awaiting_approval = action == 'request' project.approval_request_datetime = datetime.now() project.save() if action == 'request': mail_managers( escape('New project added by @{} awaiting approval - {}'.format( project.draft_added_by.username, project.name)), 'Project: {}'.format( request.build_absolute_uri( reverse('package', kwargs={'slug': project.slug})))) return HttpResponseRedirect( reverse("package", kwargs={"slug": project.slug}))
def form_valid(self, form): q = form.cleaned_data q.pop('captcha', None) item = Item.objects.create(**q) domain = Site.objects.get_current().domain subject = u'Новый вопрос на сайте %s' % domain t = get_template('mail/question.html') message = t.render(Context({'item': item, 'domain': domain})) mail_managers(subject, message, html_message=message) messages.add_message(self.request, messages.INFO, u'Спасибо! Ваш вопрос отправлен!') return HttpResponseRedirect(self.get_success_url())
def send_mail(self): email = self.cleaned_data.get('email') subject = self.cleaned_data.get('subject') text = self.cleaned_data.get('text') body = 'Message From: {}\n\n{}'.format(email, text) try: mail_managers(subject, body) except BadHeaderError: self.add_error( None, ValidationError( 'Could not send the Email.' 'Extra headers not allowed in email body.', code='badheader')) return False return True
def save(self, request): super(PublishingSuggestForm, self).save() contact = self.cleaned_data['contact'] suggestion_text = self.cleaned_data['books'].strip(', \n\r') books = suggestion_text if self.cleaned_data['ebook'] else '' audiobooks = suggestion_text if self.cleaned_data['audiobook'] else '' suggestion = PublishingSuggestion( contact=contact, books=books, audiobooks=audiobooks, ip=request.META['REMOTE_ADDR']) if request.user.is_authenticated(): suggestion.user = request.user suggestion.save() if not suggestion.is_spam(): mail_managers(u'Konsultacja planu wydawniczego na WolneLektury.pl', u'''\ Zgłoszono nową sugestię nt. planu wydawniczego w serwisie WolneLektury.pl. %(url)s Użytkownik: %(user)s Kontakt: %(contact)s Książki: %(books)s Audiobooki: %(audiobooks)s''' % { 'url': request.build_absolute_uri(reverse('admin:suggest_suggestion_change', args=[suggestion.id])), 'user': str(request.user) if request.user.is_authenticated() else '', 'contact': contact, 'books': books, 'audiobooks': audiobooks, }, fail_silently=True) try: validate_email(contact) except ValidationError: pass else: send_mail( ugettext(u'Thank you for your suggestion.'), ugettext(u"""\ Thank you for your comment on WolneLektury.pl. The suggestion has been referred to the project coordinator."""), [contact], fail_silently=True)
def form_valid(self, form): # By assigning the User to a property on the view, we allow subclasses # of SignupView to access the newly created User instance self.user = form.save(self.request) mail_managers( 'New user registration at deepex.com', 'A new user %s (%s), has registered on the web site\n\n%s\n\nBusiness type:%s\n\nInterested in: %s' % (self.user.get_full_name(), self.user.email, self.user.email_address_details, self.user.business_type, self.user.interested), fail_silently=True) try: return complete_signup(self.request, self.user, app_settings.EMAIL_VERIFICATION, self.get_success_url()) except ImmediateHttpResponse as e: return e.response
def handle_noargs(self, *args, **options): def spawn(url, pool=None): if pool is not None: return pool.spawn(self.validate_url, url) return gevent.spawn(self.validate_url, url) urls = list(ShortURL.objects.all()) if gevent: size = getattr(settings, 'DEFLECT_ASYNC_CONCURRENCY', None) pool = Pool(size) if size else None requests = [spawn(u, pool=pool) for u in urls] gevent.joinall(requests) else: for url in urls: self.validate_url(url) mail_managers('URL report for %s' % self.domain, self.message)
def invite(request): success = False if request.method == 'POST': formset = InviteForm(request.POST) if formset.is_valid(): formset.save() messages.success(request, 'Ваше приглашение отправлено') success = True formset = None mail_managers("Invite", 'check admin') else: fromset = formset context = {'formset': formset, 'success': success} else: formset = InviteForm context = {'formset': formset} return render(request, 'events/invite.html', context)
def process_response(self, request, response): """Send broken link emails for relevant 404 NOT FOUND responses.""" if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = request.META.get('HTTP_REFERER', '') if not self.is_ignorable_request(request, path, domain, referer): ua = request.META.get('HTTP_USER_AGENT', '<none>') ip = request.META.get('REMOTE_ADDR', '<none>') mail_managers( "Broken %slink on %s" % (('INTERNAL ' if self.is_internal_request(domain, referer) else ''), domain), "Referrer: %s\nRequested URL: %s\nUser agent: %s\n" "IP address: %s\n" % (referer, path, ua, ip), fail_silently=True) return response
def send_email(user, data): subject, user_email = 'OpenDataPhilly - Data Submission', ( user.first_name + " " + user.last_name, user.email) text_content = render_to_string('submit_email.txt', data) text_content_copy = render_to_string('submit_email_copy.txt', data) mail_managers(subject, text_content) msg = EmailMessage(subject, text_content_copy, to=user_email) msg.send() sug_object = Submission() sug_object.user = user sug_object.email_text = text_content sug_object.save() return sug_object
def notify_managers_of_registration(sender, instance, created, raw, **kwargs): if raw or not created: return context = Context({'object': instance}) subject = select_template([ 'chance/registration_email_manager_subject.txt', 'chance/registration_email_subject.txt' ]).render(context) subject = ''.join(subject.splitlines()) message = select_template([ 'chance/registration_email_manager.txt', 'chance/registration_email.txt' ]).render(context) mail_managers( subject, message, getattr(settings, 'CHANCE_FROM_EMAIL', settings.SERVER_EMAIL))
def comment_flagged(sender, **kwargs): """ Signal handler """ flag = kwargs['flag'] if flag.flag == flag.SUGGEST_REMOVAL: current_site = Site.objects.get_current() domain = current_site.domain subject = _('A comment was flagged') message = _( "A comment was flagged as inappropiate. Check out http://%(domain)s" ) % dict(domain=domain + reverse('fo.goal', args=[flag.comment.object_pk ])) #Hardcoded goal. Maybe change? mail_managers(subject, message, fail_silently=False)
def save(self, user): obj = super(AddExampleForm, self).save(False) obj.approved = False obj.author = user obj.save() subject = _(u'New recipe has been added on djbook.ru') message = _( u'User %(author)s added a new recipe on djbook.ru.\n\n' 'Please check and approve it. URL: %(link)s') % { 'link': 'https://%s%s' % (Site.objects.get_current().domain, obj.get_edit_url()), 'author': obj.author } mail_managers(subject, message, True) return obj
def send_campaign_task(campaign_id): Campaign = apps.get_model('campaigns', 'Campaign') try: campaign = Campaign.objects.get(pk=campaign_id) if campaign.status == CampaignStatus.QUEUED: send_campaign(campaign) mail_managers( 'Mailing campaign has been sent', 'Your campaign "%s" is on its way to your subscribers!' % campaign.email.subject) else: logger.warning( 'Campaign "%s" was placed in a queue with status "%s".' % (campaign_id, campaign.get_status_display())) except Campaign.DoesNotExist: logger.exception( 'Campaign "%s" was placed in a queue but it does not exist.' % campaign_id)
def send_activation_email(self, **kwargs): kwargs['activation_key'] = self.activation_key kwargs['expiration_days'] = settings.ACCOUNT_ACTIVATION_DAYS subject = render_to_string(self.activation_subject_template_name, kwargs).splitlines() subject = "".join(subject) text_message = render_to_string(self.activation_text_template_name, kwargs) html_message = render_to_string(self.activation_html_template_name, kwargs) msg = EmailMultiAlternatives(subject, text_message, settings.DEFAULT_FROM_EMAIL,[self.user.email]) msg.attach_alternative(html_message, "text/html") msg.send() # Let administrators know.. if 'test' not in sys.argv: requester = kwargs.get('requesting_user') mail_managers("New User {} from {} was Added".format(self.user, requester), "Hey\n {} just added {}\n\nBig Brother..".format(requester, self.user))
def send_mail(self): reason = self.cleaned_data['reason'] reason_dict = dict(self.REASON_CHOICES) full_reason = reason_dict.get(reason) email = self.cleaned_data['email'] text = self.cleaned_data['text'] body = 'Message From: {0}\n\n{1}\n'.format(email, text) try: mail_managers(full_reason, body) except BadHeaderError: self.add_error( None, ValidationError( 'Could Not Send Email.\nExtra Headers not allowed in email body.', code='badheader')) return False else: return True
def notify_on_failure(**kwargs): traceback_text = traceback.format_exc() current_site = Site.objects.get_current() url = "https://{}{}".format( current_site.domain, reverse("admin:background_task_task_change", args=(kwargs.get("task").id, ))) template = loader.get_template("admin/failed_background_task_email.html") html_content = template.render(context={ "traceback": traceback_text, "task": kwargs.get("task"), "url": url }) plain_text_content = strip_tags(html_content) mail_managers("Error in background task {}".format(kwargs.get("task")), plain_text_content, html_message=html_content)