def check_account(request, email): # return render(request, 'main/activated.html', {}) try: user = get_object_or_404(SaarangUser, email=base64.b64decode(email)) if user.activate_status == 0: user.activate_status = 2 user.save() messages.success(request, 'Your account has been activated') messages.info(request, 'Your Saarang ID is '+user.saarang_id) messages.error(request, 'Check you email for exciting Saarang Goodies !!!') messages.warning(request, 'Please login to Saarang Website by clicking on the Saarang logo') last = get_object_or_404(LastCoupon, pk=1) last_coupon = int(last.coupon_id) coupon = get_object_or_404(Coupon, pk=last_coupon, sent=False) coupon_code_link = 'https://www.komparify.com/recharge?couponcode='+coupon.code mail.send( [user.email], template='email/main/activate_confirm', context={'saarang_id':user.saarang_id, 'coupon_code_link': coupon_code_link, } ) coupon.sent = True coupon.sent_to = user coupon.save() last.coupon_id += 1 last.save() else: messages.warning(request, 'Your account has already been activated') except Exception, e: raise e messages.error(request, 'Error')
def generate_emails(self): # Emails are gona be send to all applicants that have # interview date and didn't receive an email yet recipients = [student for student in Student.objects.filter( has_received_email=False, has_interview_date=True)] for student in recipients: mail.send( recipients=[student.email], template=self.template, context={ 'name': student.name, 'applied_course': student.applied_course, 'interview_date': student.interviewslot.teacher_time_slot.date, 'interview_start_time': student.interviewslot.start_time, 'confirm_interview_url': self.confirm_interview_url + student.uuid, 'choose_interview_url': self.choose_interview_url + student.uuid, }) try: self.__inc_generated_emails() student.has_received_email = True student.save() except Exception as e: self.__inc_errors() student.has_received_email = False student.save() print(e) pass
def delete_member(request, team_id, member_id): team = get_object_or_404(HospiTeam, pk=team_id) user = get_object_or_404(SaarangUser, pk=member_id) team.members.remove(user) mail.send([user.email], template="email/hospi/member_deleted", context={"team": team}) return redirect("hospi_home")
def release_dev(id, currentuser): device = Device.objects.get(id=id) if device.owner != currentuser: return "Your are not the owner of this device." else: device.owner = None subject = "[Labsmith]%s is released." % ( device.name) html_msg = r'You can reserve it now.<br><br><a href="http://10.62.34.99:8010/labsmith/">http://10.62.34.99:8010/labsmith/</a>' if device.wanted != None: mailto = device.wanted.email mail.send( [mailto], '*****@*****.**', subject=subject, html_message= html_msg, # priority='now', ) device.wanted = None device.user = "" device.save(); msg = "%s is free now." % (device.name) log=Log(device=device,user=currentuser,timestamp=timezone.now(),msg="release") log.save() return msg
def send_html_email_with_dj_template(recipients, subject, dj_template, context={}, sender=None, template=None, message='', headers=None, priority=None, backend=''): """ Arguments: - `recipients`: - `subject`: - `sender`: - `template`: - `context`: """ base_context = { 'url_base': get_site_scheme_and_netloc(), 'site_name': SITE_NAME, 'media_url': MEDIA_URL, 'logo_path': LOGO_PATH, } context.update(base_context) t = loader.get_template(dj_template) html_message = t.render(Context(context)) mail.send(recipients, sender=sender, template=template, context=context, subject=subject, message=message, html_message=html_message, headers=headers, priority=priority, backend=backend)
def handle(self, *args, **options): translation.activate(settings.LANGUAGE_CODE) event = Event.objects.get(code_name=options['event_code_name']) from_email = event.get_notification_email() # Skip abstracts that already have certificates generated_pks = Certificate.objects.values_list('abstracts__pk', flat=True) abstracts = Abstract.objects.filter(event=event, user__isnull=False, did_presenter_attend=True, accepted_presentaion_preference__in=["O", "P"])\ .exclude(pk__in=generated_pks) domain = Site.objects.get_current().domain url = "https://{}{}".format(domain, reverse('certificates:list_certificates_per_user')) for abstract in abstracts: if abstract.accepted_presentaion_preference == 'O': template = abstract.event.oral_certificate_template elif abstract.accepted_presentaion_preference == 'P': template = abstract.event.poster_certificate_template template.generate_certificate(abstract.user, [abstract.presenting_author, abstract.title]) if options['send_emails']: contxt = {'title': abstract.title, 'user': abstract.user, 'event': event, 'url': url} mail.send(abstract.email, from_email, template='event_abstract_certificate', context=context)
def send_email(request, pk): supervisor = get_object_or_404(Supervisor, pk=pk) if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): email_context = {'user': request.user, 'supervisor': supervisor, 'data': form.cleaned_data} mail.send([request.user.email], "*****@*****.**", template="researchhub_send_email_to_student", context=email_context) mail.send([supervisor.user.email], "*****@*****.**", bcc="*****@*****.**", template="researchhub_send_email_to_supervisor", context=email_context, headers={'Reply-to': request.user.email}) return {"message": "success"} elif request.method == 'GET': form = EmailForm() context = {'form': form, 'supervisor': supervisor} return render(request, 'researchhub/send_email_form.html', context)
def add_request(request, guide_pk): guide = get_object_or_404(GuideProfile, pk=guide_pk, is_deleted=False) if request.method == 'POST': instance = Request(user=request.user, guide=guide) form = RequestForm(request.POST, instance=instance) if form.is_valid(): guide_request = form.save() list_guide_requests_url = reverse('studentguide:list_guide_requests', args=(guide.pk,)) email_full_url = request.build_absolute_uri(list_guide_requests_url) email_context = {'guide': guide, 'guide_request': guide_request, 'full_url': email_full_url} mail.send([guide.user.email], template="guide_request_created_to_guide", context=email_context) list_my_requests_url = reverse('studentguide:list_my_requests') full_url = request.build_absolute_uri(list_my_requests_url) return {"message": "success", "list_url": full_url} elif request.method == 'GET': form = RequestForm() context = {'form': form, 'guide': guide} return render(request, 'studentguide/edit_request_form.html', context)
def add_report(request, guide_pk): guide = get_object_or_404(GuideProfile, pk=guide_pk) if not utils.can_edit_guide(request.user, guide): raise Exception(u"لا تستطيع رفع تقرير") if request.method == 'POST': current_year = StudentClubYear.objects.get_current() instance = Report(guide=guide) form = ReportForm(request.POST, request.FILES, instance=instance) if form.is_valid(): report = form.save() show_report_url = reverse('studentguide:show_report', args=(guide.pk, report.pk)) full_url = request.build_absolute_uri(show_report_url) if guide.assessor: email_context = {'assessor': guide.assessor, 'guide': guide, 'full_url': full_url} mail.send([guide.assessor.email], template="report_submitted_to_assessor", context=email_context) return {"message": "success", "show_url": full_url} elif request.method == 'GET': form = ReportForm() context = {'form': form, 'guide': guide} return render(request, 'studentguide/edit_report_form.html', context)
def email(recipient, context, template_name, sender=None): if not settings.MANDRILL_API_KEY or settings.MANDRILL_API_KEY == 'None': return current_site = Site.objects.get_current() context['domain'] = current_site.domain User = django.contrib.auth.get_user_model() # The recipient list can be a list of User model instances or Email Address string # Which means you could pass a User model QuerySet as recipient # If a recipient is User model instance then simple convert to Email Address string recipient_email_list = [] for rec in recipient: if isinstance(rec, User): if rec.first_name and rec.last_name: recipient_email_list.append('"%s %s" <%s>' % (rec.first_name, rec.last_name, rec.email)) elif rec.first_name: recipient_email_list.append('"%s" <%s>' % (rec.first_name, rec.email)) else: recipient_email_list.append('%s' % rec.email) else: recipient_email_list.append(rec) mail.send( sender=sender or settings.DEFAULT_FROM_EMAIL, recipients=recipient_email_list, template=template_name, context=context, priority=PRIORITY.now )
def add_guide(request): if request.method == 'POST': current_year = StudentClubYear.objects.get_current() studentguide_club = clubs.utils.get_club_for_user("Student Guide", request.user) random_assessor = studentguide_club.members.order_by('?').first() instance = GuideProfile(user=request.user, year=current_year, assessor=random_assessor) form = GuideForm(request.POST, request.FILES, instance=instance) if form.is_valid() and not utils.has_guide_profile(request.user): guide = form.save() list_supervised_guides_url = reverse('studentguide:list_supervised_guides') full_url = request.build_absolute_uri(list_supervised_guides_url) email_context = {'assessor': random_assessor, 'guide': guide, 'full_url': full_url} # If there are members to pick from, send an email. if random_assessor: mail.send([random_assessor.email], template="guide_assigned_randomly_to_assessor", context=email_context) show_guide_url = reverse('studentguide:show_guide', args=(guide.pk,)) full_url = request.build_absolute_uri(show_guide_url) return {"message": "success", "show_url": full_url} elif request.method == 'GET': form = GuideForm() context = {'form': form} return render(request, 'studentguide/edit_guide_form.html', context)
def contato(request): name = request.POST.get('name', '') parceiro = request.POST.get('parceiro', '') phone = request.POST.get('phone', '') email = request.POST.get('email', '') subject = request.POST.get('subject', '') message = request.POST.get('message', '') if name and message and email: mail.send( ['*****@*****.**'], sender=settings.DEFAULT_FROM_EMAIL, template='contato', context={'name':name,'subject':subject, 'message':message, 'email':email, 'phone':phone}, ) return redirect('http://cdr-port.net') elif parceiro and message and email: mail.send( ['*****@*****.**'], sender=settings.DEFAULT_FROM_EMAIL, template='parceiro', context={'name':parceiro,'subject':subject, 'message':message, 'email':email, 'phone':phone}, ) return redirect('http://parceiros.cdr-port.net') else: return HttpResponse("Preencha todos os campos.")
def student_action(request): supervision_request_id = request.POST.get('supervision_request_id') action = request.POST.get('action') supervision_request = get_object_or_404(SupervisionRequest.objects.current_year(), pk=supervision_request_id) if supervision_request.user != request.user: raise Exception(u'لست أنت مقدم الطلب!') if action == 'delete': if supervision_request.status == 'A': now = datetime.datetime.now() supervision_request.status = 'WN' supervision_request.withdrawal_date = now to_me_url = reverse('arshidni:supervision_requests_to_me') full_url = request.build_absolute_uri(to_me_url) arshidni_coordinator = get_arshidni_club_for_user(request.user).coordinator if arshidni_coordinator: email_context = {'full_url': full_url, 'supervision_request': supervision_request} mail.send([supervision_request.colleague.user.email], cc=[arshidni_coordinator.email], template="supervision_request_withdrawn", context=email_context) elif supervision_request.status == 'P': supervision_request.status = 'D' else: # Just in case raise Exception(u'حدث خطأ غير معروف.') supervision_request.save() else: raise Exception(u'حدث خطأ غير معروف.') return {'current_status': supervision_request.status, 'full_current_status': supervision_request.get_status_display()}
def submit_group(request): if request.method == 'POST': group_object = StudyGroup(coordinator=request.user) form = StudyGroupForm(request.POST, instance=group_object) if form.is_valid(): new_group = form.save() group_url = reverse('arshidni:show_group', args=(new_group.pk,)) group_full_url = request.build_absolute_uri(group_url) admin_url = reverse('arshidni_admin:index') admin_full_url = request.build_absolute_uri(admin_url) arshidni_coordinator = get_arshidni_club_for_user(request.user).coordinator if arshidni_coordinator: email_context = {'arshidni_coordinator': arshidni_coordinator, 'group': new_group, 'full_url': group_full_url, 'admin_full_url': admin_full_url} mail.send([arshidni_coordinator.email], template="study_group_submitted", context=email_context) return HttpResponseRedirect(group_url) else: context = {'form': form} elif request.method == 'GET': form = StudyGroupForm() context = {'form': form} return render(request, 'arshidni/group_edit.html', context)
def register_team(request,eventId,teamId): email = request.session.get('saaranguser_email') try: user = SaarangUser.objects.get(email=email) except: messages.error(request, 'Please login to continue') return render(request, 'main/login.html', {}) event = get_object_or_404(Event,id=eventId) team = get_object_or_404(Team,id=teamId) if EventRegistration.objects.filter(event=event,team=team): if event.id in EVENT_WITH_OPTIONS: return HttpResponseRedirect(reverse('band_details',kwargs={'eventId':eventId,'teamId':teamId})) messages.info(request,'Already registered for the event') else: if not event.registration_open : messages.info(request,'Registration is closed for the event.') else: EventRegistration.objects.create(participant=user,team=team,event=event,options='') mail_list = [member.email for member in team.members.all()] mail_list.append(email) mail.send( mail_list, template='email/main/register_team', context={'event_name':event.long_name, 'team_name':team.name,}, ) if event.id in EVENT_WITH_OPTIONS: return HttpResponseRedirect(reverse('band_details',kwargs={'eventId':eventId,'teamId':teamId})) messages.success(request,'Team registered successfully') return render(request, 'main/register_response.html')
def form_valid(self, form): if form.has_changed(): user = self.get_user() self.storeUser(form, user) user.save() user.mitglied.save() # print ({'user': user.__dict__, # 'mitglied': user.mitglied.__dict__}) # print type(user) # print user.last_name # print type(user.mitglied) # inform the relevant Vorstand in charge of memeberhsip mail.send(['*****@*****.**'], template="updatedProfile", context={'user': user, 'mitglied': user.mitglied, 'changed': form.changed_data}, priority='now', ) messages.success(self.request, format_html( u"Das Profil {} {} ({}) wurde erfolgreich aktualisiert.", user.first_name, user.last_name, user.mitglied.mitgliedsnummer)) else: messages.success(self.request, "Sie haben keine Änderungen vorgenommen." ) return super(AccountEdit, self).form_valid(form)
def handle(self, *args, **options): domain = Site.objects.get_current().domain end_date_target = timezone.now().date() end_time_since = (timezone.now() - datetime.timedelta(minutes=10)).time() end_time_until = timezone.now().time() for activity in Activity.objects.current_year().approved().done().filter(episode__end_date=end_date_target)\ .exclude(assessment__criterionvalue__criterion__category='P')\ .exclude(primary_club__is_assessed=False)\ .distinct(): # If the activity didn't end within the past ten minutes, # skip, because another proccess would have sent a # notification about it. if not activity.episode_set.filter(episode__end_date=end_date_target, episode__end_time__gt=end_time_since, episode__end_time__lte=end_time_until).exists(): continue email_context = {'activity': activity} assessor_club = Club.objects.club_assessing_parents(activity.primary_club).first() if assessor_club.coordinator: full_url = "https://{}{}".format(domain, reverse('activities:assess', args=(activity.pk, 'p'))) email_context['full_url'] = full_url email_context['assessor_club'] = assessor_club email_context['assessor'] = assessor_club.coordinator mail.send([assessor_club.coordinator.email], template="activity_done_to_assessor", context=email_context) self.stdout.write(u'Assigned {0} to {1}. Emailing {1}.'.format(activity.name, assessor_club))
def user_create(request, template_name='vnoiusers/user_create.html'): form = UserCreateForm() if request.user.is_authenticated(): messages.warning(request, 'Invalid request') return HttpResponseRedirect(reverse('main:index')) if request.POST: form = UserCreateForm(request.POST) if form.is_valid(): form.save() # save user to database if form is valid username = form.cleaned_data['username'] email = form.cleaned_data['email'] salt = hashlib.sha1(str(random.random())).hexdigest()[:8] activation_key = hashlib.sha1(salt+email).hexdigest() # Get user by username user = User.objects.get(username=username) user.profile.activation_key = activation_key user.profile.save() # Send email with activation key if not DEBUG: email_subject = 'Đăng ký tài khoản VNOI' email_body = "Hi %s, chào mừng bạn đã đến với VNOI. Để kích hoạt tài khoản, hãy click vào link: %s/user/confirm/%s" % (username, ROOT_URL, activation_key) mail.send(email, subject=email_subject, message=email_body, priority="now") return HttpResponse('Một email đã được gửi đến tài khoản email mà bạn đăng ký. Hãy kiểm tra hòm thư của bạn và làm theo hướng dẫn để kích hoạt tài khoản.') else: return HttpResponse('Bạn đã đăng ký thành công. Bạn có thể trở về trang chủ để đăng nhập') else: return render(request, template_name, {'form': form, 'message': form.errors}) else: return render(request, template_name, {'form': form, 'message': ''})
def order_event_notification(sender, instance=None, target=None, **kwargs): from shop.rest import serializers if not isinstance(instance, OrderModel): return for notification in Notification.objects.filter(transition_target=target): recipient = notification.get_recipient(instance) if recipient is None: continue # emulate a request object which behaves similar to that one, when the customer submitted its order emulated_request = EmulateHttpRequest(instance.customer, instance.stored_request) order_serializer = serializers.OrderDetailSerializer(instance, context={'request': emulated_request}) language = instance.stored_request.get('language') context = { 'customer': serializers.CustomerSerializer(instance.customer).data, 'data': order_serializer.data, 'ABSOLUTE_BASE_URI': emulated_request.build_absolute_uri().rstrip('/'), 'render_language': language, } try: template = notification.mail_template.translated_templates.get(language=language) except EmailTemplate.DoesNotExist: template = notification.mail_template attachments = {} for notiatt in notification.notificationattachment_set.all(): attachments[notiatt.attachment.original_filename] = notiatt.attachment.file.file mail.send(recipient, template=notification.mail_template, context=context, attachments=attachments, render_on_delivery=True)
def handle(self, *args, **options): # set the locale right, to get the dates represented correctly translation.activate(settings.LANGUAGE_CODE) offeneLeistungen = (models.Leistung.objects. filter( erstellt__lte=datetime.date.today()-datetime.timedelta(days=7)). exclude( status=models.Leistung.ACK). exclude( status=models.Leistung.NEG) ) print offeneLeistungen kontakte = set([l.aufgabe.kontakt() for l in offeneLeistungen]) print kontakte for k in kontakte: mail.send( [k.email], # to address template="leistungReminder", ) call_command('send_queued_mail') translation.deactivate()
def send_mass_mail(request): allowed = ['webops', 'events', 'publicity'] if not request.user.userprofile.dept.name in allowed: to_return={ 'msg':'You dont have permission to send mass mail', } return render(request, 'alert.html', to_return) data = request.POST.copy() new_mail = MailLog.objects.create(from_email=data['from_email'], \ to_email='*****@*****.**', subject=data['subject'], \ body=data['body'], created_by=request.user) email_list=[] EL = EmailList.objects.all() for eml in EL: email_list.append(eml.email) mail.send( email_list,data['from_email'], subject=data['subject'], html_message=data['body'], ) to_return ={ 'mail': new_mail, } messages.success(request, 'Email has been sent') return render(request, 'alert.html', to_return)
def home(request): if request.method == 'POST': userform =SaarangUserForm(request.POST) data=request.POST.copy() if userform.is_valid(): user = userform.save() user.saarang_id = auto_id(user.pk) characters = string.ascii_letters + string.punctuation + string.digits password = "".join(choice(characters) for x in range(randint(8, 16))) user.password = password user.activate_status = 2 user.save() mail.send( [user.email], template='email/main/activate_confirm', context={'saarang_id':user.saarang_id, 'password':user.password} ) userform = SaarangUserForm() messages.success(request, data['desk_id'] +' Successfully saved') else: userform = SaarangUserForm(request.POST) else: userform = SaarangUserForm() to_return={ 'form':userform, 'action': "", 'title': "Add a new User" } return render(request, 'user_registration/qms.html', to_return)
def user_create(request, template_name='vnoiusers/user_create.html'): form = UserCreateForm() if request.user.is_authenticated(): messages.warning(request, 'Invalid request') return HttpResponseRedirect(reverse('main:index')) if request.POST: form = UserCreateForm(request.POST) if form.is_valid(): form.save() # save user to database if form is valid username = form.cleaned_data['username'] email = form.cleaned_data['email'] salt = hashlib.sha1(str(random.random())).hexdigest()[:8] activation_key = hashlib.sha1(salt+email).hexdigest() # Get user by username user = User.objects.get(username=username) user.profile.activation_key = activation_key user.profile.save() # Send email with activation key email_subject = 'Vnoiwebsite Account confirmation' email_body = "Hey %s, thanks for signing up. To activate your account, click this link http://127.0.0.1:8000/user/confirm/%s" % (username, activation_key) mail.send(email, subject=email_subject, message=email_body, priority="now") return HttpResponse('You have successfully register a new account. An email will be sent to your email shortly. Please click the confirmation link in the email') else: return render(request, template_name, {'form': form, 'message': form.errors}) else: return render(request, template_name, {'form': form, 'message': ''})
def handle(self, *args, **options): translation.activate(settings.LANGUAGE_CODE) event = Event.objects.get(code_name=options['event_code_name']) event_users = (User.objects.filter(certificate__sessions__event=event) | \ User.objects.filter(certificate__abstracts__event=event)).distinct() count = 1 self.stdout.write("We got {} users to handle!".format(event_users.count())) domain = Site.objects.get_current().domain url = "https://{}{}".format(domain, reverse('certificates:list_certificates_per_user')) for user in event_users.iterator(): email_context = {'user': user, 'url': url, 'event': event} notification_email = event.get_notification_email() cc = accounts.utils.get_user_cc(user) mail.send([user.email], u"بوابة إنجاز <{}>".format(notification_email), cc=cc, template="event_certificates", context=email_context) self.stdout.write("{:06d}: Sent to {}!".format(count, user.email)) count +=1 if options['sleep_time']: time.sleep(options['sleep_time'])
def handle(self, *args, **options): # set the locale right, to get the dates represented correctly translation.activate(settings.LANGUAGE_CODE) t = loader.get_template("boote/email_booking.html") # get records for booking in models.Booking.objects.filter(notified = False).order_by('-date'): c = Context({ 'booking': booking}) payload = t.render(c) sbj = '[SVPB] Reservation (' + booking.date.strftime('%d, %b %Y') + ') - ' + booking.boat.type.name + " \"" + booking.boat.name + "\"" self.stdout.write('From: ' + settings.DEFAULT_FROM_EMAIL) self.stdout.write('To: ' + booking.user.email) self.stdout.write('Subject: ' + sbj) self.stdout.write('Content:\n\r' + payload) mail.send( [booking.user.email], settings.DEFAULT_FROM_EMAIL, subject=sbj, html_message=payload, ) booking.notified = True booking.save() call_command('send_queued_mail') translation.deactivate()
def handle(self, *args, **options): translation.activate(settings.LANGUAGE_CODE) domain = Site.objects.get_current().domain end_date_target = timezone.now().date() end_time_since = (timezone.now() - timedelta(minutes=10)).time() end_time_until = timezone.now().time() for episode in Episode.objects.filter(activity__is_approved=True, requires_report=True, end_date=end_date_target, end_time__gt=end_time_since, end_time__lte=end_time_until)\ .exclude(followupreport__isnull=False, employeereport__isnull=False): print episode email_context = {'episode': episode} if not episode.employee_report_is_submitted() and \ episode.activity.primary_club.employee: full_url = "https://{}{}".format(domain, reverse('media:submit_employee_report', args=(episode.pk,))) email_context['full_url'] = full_url mail.send([episode.activity.primary_club.employee.email], template="due_report_to_report_submitter", context=email_context) if not episode.report_is_submitted(): emails = episode.activity.primary_club.media_representatives.values_list('email', flat=True) if emails: full_url = "https://{}{}".format(domain, reverse('media:submit_report', args=(episode.pk,))) email_context['full_url'] = full_url mail.send(list(emails), template="due_report_to_report_submitter", context=email_context)
def handle(self, *args, **options): translation.activate(settings.LANGUAGE_CODE) wb = load_workbook(options['excel_file'], read_only=True) domain = Site.objects.get_current().domain event = Event.objects.get(code_name=options['event_code_name']) from_email = event.get_notification_email() url = "https://{}{}".format(domain, reverse('certificates:list_certificates_per_user')) generated_pks = Certificate.objects.values_list('abstracts__pk', flat=True) for sheet_name in wb.get_sheet_names(): sheet = wb[sheet_name] print "Reading sheet '{}'".format(sheet_name) for row in sheet: pk = row[0].value # If pk is empty, we are done from this sheet. if not pk: break try: pk = int(pk) except ValueError: # If pk cannot be turned into intger # (i.e. header), skip! continue if pk in generated_pks: print "Skipping {} as previously generated.".format(pk) continue authors = [cell.value.strip() for cell in row[3:12] if cell.value] abstract = Abstract.objects.get(pk=pk) # Let's make sure that the abstract deserves a # certificate if abstract.accepted_presentaion_preference in ['O', 'P'] and \ abstract.did_presenter_attend: if abstract.accepted_presentaion_preference == 'O': template = abstract.event.oral_certificate_template elif abstract.accepted_presentaion_preference == 'P': template = abstract.event.poster_certificate_template for author in authors: description = "شهادة {} لتقديم {}".format(author, abstract.title) print 'Generating {}\'s "{}"'.format(author, abstract.title) template.generate_certificate(user=abstract.user, texts=[author, abstract.title], description=description, content_object=abstract) # Other than the first author, we are going to # use the co_author certificate template template = abstract.event.coauthor_certificate_template if options['send_emails']: contxt = {'title': abstract.title, 'user': abstract.user, 'event': event, 'url': url} mail.send(abstract.email, from_email, template='event_abstract_certificate', context=context)
def send_templated_email(template_name, user_list): for u in user_list: mail.send( recipients=[u.email], sender='*****@*****.**', template=template_name, context={'user': u}, priority=3 )
def send_my_lockers_mail(email, lockers, user): template = 'lockers_mine_skap' mail.send( email, # List of email addresses also accepted DEFAULT_FROM_EMAIL, template=template, # Could be an EmailTemplate instance or name context={'user': user, 'email': email, 'lockers': lockers}, )
def send_user_contact_email(name, from_address, message): subject = "EMAIL FROM GBE SITE USER %s" % name to_addresses = settings.USER_CONTACT_RECIPIENT_ADDRESSES mail.send(to_addresses, from_address, subject=subject, message=message, priority='now', )
def submit_supervision_request(request, colleague_profile_id): colleague_profile = get_object_or_404( ColleagueProfile.objects.current_year(), pk=colleague_profile_id, is_published=True) context = {'colleague_profile': colleague_profile} if request.method == 'POST': request_object = SupervisionRequest(user=request.user, colleague=colleague_profile) form = SupervisionRequestForm(request.POST, instance=request_object) if form.is_valid(): new_request = form.save() to_me_url = reverse('arshidni:supervision_requests_to_me') full_url = request.build_absolute_uri(to_me_url) email_context = { 'full_url': full_url, 'supervision_request': new_request, 'colleague_profile': colleague_profile } mail.send([colleague_profile.user.email], template="supervision_request_submitted", context=email_context) after_url = reverse('arshidni:my_supervision_requests' ) + '#request-' + str(new_request.pk) return HttpResponseRedirect(after_url) else: context['form'] = form elif request.method == 'GET': # Check if the user has any pending or accepted supervision # requests accepted_student_requests = SupervisionRequest.objects.filter( user=request.user, status='A') pending_student_requests = SupervisionRequest.objects.filter( user=request.user, status='P') # Check if the colleague has exceeded the supervision limit. colleague_supervisions = colleague_profile.supervision_requests.accepted( ) if colleague_supervisions.filter(user=request.user).exists(): context['error'] = 'already_supervisor' elif accepted_student_requests.exists(): context['error'] = 'accepted_supervision_requests' elif pending_student_requests.exists(): context['error'] = 'pending_supervision_requests' elif colleague_supervisions.count() >= COLLEAGUE_SUPERVISION_LIMIT: context['error'] = 'colleague_supervision_limit' elif get_user_gender(request.user) != get_user_gender( colleague_profile.user): context['error'] = 'gender' else: form = SupervisionRequestForm() context['form'] = form return render(request, 'arshidni/colleague_choose.html', context)
def test_mail(request): mail.send( ['*****@*****.**', '*****@*****.**' ], # List of email addresses also accepted '*****@*****.**', subject='My email', message='Hi there!', html_message='Hi <strong>there</strong>!', ) return HttpResponse("SENT")
def send_password_recovery_code(user: User): token = user_activation_token.make_token(user=user) link = f'{BASE_URL}users/new_password/{user.pk}/{token}' context = {'token': token, 'link': link, 'user': user} mail.send([user.email], NOREPLY_EMAIL, template='user_password_recovery', context=context) return context
def send_mail(self): from post_office import mail mail.send( recipients=[self.user.email], template= 'decima_question', # Could be an EmailTemplate instance or name context={'decima': self}, priority='now', ) # print "Send mail implementation" return
def diagnostics(request): from django.conf import settings from post_office import mail ping_socket_url = ( request.build_absolute_uri(f'{reverse("tracker:index_all")}ws/ping/') .replace('https:', 'wss:') .replace('http:', 'ws:') ) celery_socket_url = ( request.build_absolute_uri(f'{reverse("tracker:index_all")}ws/celery/') .replace('https:', 'wss:') .replace('http:', 'ws:') ) if request.method == 'POST': test_email_form = TestEmailForm(data=request.POST) if test_email_form.is_valid(): mail.send( [test_email_form.cleaned_data['email']], f'webmaster@{request.get_host().split(":")[0]}', subject='Test Email', message='If you got this, email is set up correctly.', ) messages.info( request, 'Test email queued. Check Post Office models for status.' ) else: test_email_form = TestEmailForm() try: storage = DefaultStorage() output = storage.save(f'testfile_{int(time.time())}', BytesIO(b'test file')) storage.open(output).read() assert storage.exists(output) storage.delete(output) storage_works = True except Exception as e: storage_works = e return render( request, 'admin/tracker/diagnostics.html', { 'is_secure': request.is_secure(), 'test_email_form': test_email_form, 'ping_socket_url': ping_socket_url, 'celery_socket_url': celery_socket_url, 'storage_works': storage_works, 'HAS_CELERY': getattr(settings, 'HAS_CELERY', False), }, )
def save(self, request=None): ''' send mail and so ''' email = self.cleaned_data['email'] subject = self.cleaned_data['subject'] body = self.cleaned_data['body'] mail.send(settings.WELTLADEN_EMAIL_ADDRESS, email, subject=subject, message=body) email_queued()
def export(target_id): target = Export.objects.get(id=target_id) response = target.run() if settings.EXPORT_NOTIFICATIONS_ENABLED and target.notify and target.as_user.email: mail.send( target.as_user.email, # List of email addresses also accepted '*****@*****.**', template='export_ready', context={'target': target, 'user': target.as_user, 'download_url': reverse('urf:export-fetch', args=[target.id])} ) return response.status_code
def send_tour_operator_reject_email(self, tour_operator): email_to = tour_operator.email if not settings.REAL_EMAILS: email_to = settings.TESTING_EMAILS from post_office import mail URL = settings.BASE_URL context = {'tour_operator': tour_operator.name} mail.send( email_to, 'Your African Safari <*****@*****.**>', template='tour_operator_rejected', context=context, )
def test_extends(self): post_office_mail.send( '*****@*****.**', '*****@*****.**', template='template1', context={}, ) self.assertEqual(len(mail.outbox), 1) content = mail.outbox[0].alternatives[0] self.assertEqual(content[1], 'text/html') self.assertIn('Base template', content[0]) self.assertIn('Template1', content[0])
def form_valid(self, form): response = super(TestCreateView, self).form_valid(form) mail.send([self.object.epost], settings.SERVER_EMAIL, template=self.testtype, context={'deltager': self.object}, priority='now') mail.send([settings.TEST_NOTIFY_EMAIL], settings.SERVER_EMAIL, template='%s_notify' % self.testtype, context={'deltager': self.object}, priority='now') return response
def send(self): kwargs = { 'subject': self.subject, 'html_message': self.html_message, 'message': self.text_message, 'language': self.language, 'attachments': self.attachments, } if self.from_email: mail.send(self.recipient, self.from_email, **kwargs) else: mail.send(self.recipient, **kwargs)
def _send_mail_template(request, plaintext_template, html_template, subject, recipient, context=None): msg_plain = render_to_string(plaintext_template, context, request) msg_html = render_to_string(html_template, context, request) mail.send(recipients=[recipient], sender=settings.DEFAULT_FROM_EMAIL, subject=subject, message=msg_plain, html_message=msg_html)
def send_locker_email(user, token, activation_type): mail.send( user.user.email, settings.DEFAULT_FROM_EMAIL, template=activation_type, context={ "user": user, "email": user.user.email, "ownership": token.ownership, "token": token, "root_url": get_current_site(None), }, )
def send_confirmed(self): logger.debug(f'sending confirmation to owner: {self.owner.email}') mail.send( [self.owner.email], '*****@*****.**', 'appointment_confirmed', context={ 'appointment': self, 'confirming_party': self.invitee, 'other_party': self.owner }) self.confirmation_request_time = timezone.now() self.save()
def transition_change_notification(order): """ This function shall be called, after an Order object performed a transition change. """ if not isinstance(order, BaseOrder): raise TypeError("Object order must inherit from class BaseOrder") emails_in_queue = False for notification in Notification.objects.filter( transition_target=order.status): recipient = notification.get_recipient(order) if recipient is None: continue # emulate a request object which behaves similar to that one, when the customer submitted its order emulated_request = EmulateHttpRequest(order.customer, order.stored_request) customer_serializer = app_settings.CUSTOMER_SERIALIZER(order.customer) render_context = {'request': emulated_request, 'render_label': 'email'} order_serializer = OrderDetailSerializer(order, context=render_context) language = order.stored_request.get('language') context = { 'customer': customer_serializer.data, 'order': order_serializer.data, 'ABSOLUTE_BASE_URI': emulated_request.build_absolute_uri().rstrip('/'), 'render_language': language, } try: latest_delivery = order.delivery_set.latest() context['latest_delivery'] = DeliverySerializer( latest_delivery, context=render_context).data except (AttributeError, models.ObjectDoesNotExist): pass try: template = notification.mail_template.translated_templates.get( language=language) except EmailTemplate.DoesNotExist: template = notification.mail_template attachments = {} for notiatt in notification.notificationattachment_set.all(): attachments[notiatt.attachment. original_filename] = notiatt.attachment.file.file mail.send(recipient, template=template, context=context, attachments=attachments, render_on_delivery=True) emails_in_queue = True if emails_in_queue: email_queued()
def handle(self, *args, **options): #test = options['test'] for email, lang in CustomOrder.objects.filter( status__gte=CustomOrder.CONFIRMED, personal_information_consent=False).values_list( 'email', 'language_code').distinct(): if lang != 'cs': # we don't have translated consent, so just skip it continue hash = email_hash(email) text = """Pěkný den, jsme moc rádi, že podporujete náš projekt dračích kalendářů! Aby to tak zůstalo, je potřeba, abychom od Vás měli na základě Obecného nařízení o ochraně osobních údajů (GDPR) Váš jednoznačný souhlas se zpracováním Vašich osobních údajů. Pokud od nás chcete i nadále dostávat informace o nových produktech, slevových akcích a novinkách, potvrďte tento email tlačítkem níže. Tento souhlas bude dán na 20 let a je kdykoli odvolatelný. <a href="{}" style="font-size: 150%;">ANO, souhlasím</a> Pokud souhlas nepotvrdíte, přestanete od nás od 25. května dostávat veškeré novinky a všechny Vaše osobní údaje budou u nás vymazána (s výjimkou dat ze zákona požadovaných pro účetnictví). Jaké Vaše osobní údaje zpracováváme? Jde o jméno, příjmení, adresu, e-mail a IP adresu. Nově máte právo na přístup, opravu a výmaz spravovaných osobních dat, dále právo být zapomenut, právo na omezení zpracování, přenositelnost údajů a v neposlední řadě právo vznést námitku. Kompletní znění souhlasu se zpracováním osobních údajů najdete <a href="https://kalendar.draci.info/souhlas-s-poskytnutim-osobnich-udaju/">na našem webu</a>. Nechť Vás draci provází! Organizační tým projektů Draci.info""".format( "https://kalendar.draci.info/gdpr_consent/?email=%s&hash=%s" % (email, hash)) logger.info('Preparing email for %s', email) mail.send( [email], '*****@*****.**', template='default_%s' % lang, context={ 'domain': 'http://kalendar.draci.info', 'subject': 'Kalendář Draci.info - souhlas s poskytnutím osobních údajů', 'content_html': text.replace('\n', '<br />'), 'content_text': re.sub(r'<a href="([^"]*)"[^>]*>([^<]+)</a>', '\\2 \\1 ', text, flags=re.U), }, )
def send_mail(sender, template, variables, *recipients): """ Single mail send hook that is reused across the project """ try: mail.send( [recp for recp in recipients], sender, template=template, context=variables, ) except Exception as exp: print exp.message print traceback.format_exc()
def post(self, request, *args, **kwargs): email = request.data.get("email", None) if email is not None: code = verifycodegenerator() store = EmailCode.objects.create(code=code) mail.send([email], subject="FleaMddarket验证码", priority="medium", message=code) sendEmail.delay() deleteRow.apply_async((store.pk, ), countdown=600) return Response(data=store.pk, status=200) return Response(status=400)
def send_review_thank_you_email(request, item): email_to = request.user.email if not settings.REAL_EMAILS: email_to = settings.TESTING_EMAILS from post_office import mail context = {} context['member'] = request.user.profile.display_name_for_email() context['item'] = item mail.send( email_to, 'Your African Safari <*****@*****.**>', template='review_thank_you', context=context, )
def sendFeedback(request): if (request.method == 'POST'): parsed_json = json.loads(request.body.decode("utf-8")) description = UserProfile.objects.get(user_id=parsed_json['id']).description mail.send( parsed_json['email'], # List of email addresses also accepted '*****@*****.**', subject=parsed_json['subject'], message=description + "\n" + parsed_json['message'], priority='now' ) return JsonResponse({ 'success': 1 }) else: return redirect('/')
def send(self, to, **data): """ This is the method to be called """ self.data = data self.get_context() if settings.EMAIL_SEND_EMAILS: try: mail.send(to, template=self.template, context=self.context_data) except EmailTemplate.DoesNotExist: msg = 'Trying to use a non existent email template {0}'.format( self.template) logger.error(msg)
def send_email(self, user): data = { 'token': default_token_generator.make_token(user), 'uid': int_to_base36(user.id), 'host': settings.HOST, 'user': user, 'email_title': 'Lupa kata sandi' } mail.send([user.email], settings.DEFAULT_FROM_EMAIL, subject='Lupa Kata Sandi', context=data, html_message=render_to_string('emails/forgot_password.html', context=data))
def activate_user(user, code): """ Checks activation code, activate user and send email notification """ encoder = UserAuthCode(settings.SECRET_KEY) if encoder.is_valid(user, code): user.is_active = True user.save() mail.send([user.email], template="registration complete", context={ 'user': user, 'site': Site.objects.get(), }) return True return False
def post(self, request): email_to = self.request.data.get('receiver') mail.send( email_to, # List of email addresses also accepted '*****@*****.**', subject='hay', message='Welcome home, {{ name }}!', html_message='Welcome home, <b>{{ name }}</b>!', headers={'Reply-to': '*****@*****.**'}, # scheduled_time=date(2014, 1, 1), context={'name': 'Alice'}, priority='now', ) return Response(email_to)
def send_mail(self): User = get_user_model() if isinstance(self.sender, User): sender = self.sender.email elif self.from_address: sender = self.from_address else: sender = settings.DEFAULT_FROM_EMAIL if isinstance(self.template_data, str): template_data = json.loads(self.template_data) else: template_data = self.template_data try: email = mail.send( recipients=self.recipients, cc=self.cc, sender=sender, template=self.template_name, context=template_data, subject=self.subject, # actually template text message=self.text_message, # actually template text html_message=self.html_message, # actually template text ) except Exception: # log an exception, with traceback logger.exception('Failed to send mail.') else: self.sent_recipients = self.recipients + self.cc self.sent_email = email self.save()
def send_normal_email(to_email, from_email, context, subject_template_name, email_template_name, attachments={}, bcc=list(MODS_EMAILS)): subject = render_to_string(subject_template_name, context) subject = ''.join(subject.splitlines()) message = render_to_string(email_template_name, context) mail.send(to_email, from_email, subject=subject, html_message=message, bcc=bcc, attachments=attachments)
def generate_email(sender: str, email_context: RenderedEmailContext, to: Optional[List[str]] = None, cc: Optional[List[str]] = None, bcc: Optional[List[str]] = None, in_reply_to: Optional[InboxMessage] = None) -> post_office_models.Email: msg_id = make_msgid(domain=DNS_NAME) # TODO: try use ZONE from settings or even provider server name headers = { 'Message-ID': msg_id } if in_reply_to: headers['In-Reply-To'] = in_reply_to.message_id headers['References'] = in_reply_to.message_id return mail.send(commit=False, recipients=to, sender=sender, subject=email_context.subject, message=email_context.message, html_message=email_context.html_message, headers=headers, context=None, cc=cc, bcc=bcc, )
def send_verified_email(self): subject, from_email, to = "Verifizierung für naklar.io", "*****@*****.**", self.user.email d = { "user": self.user, "login_url": settings.HOST, } if EmailTemplate.objects.filter(name='tutor_verification').exists(): mail.send(to, from_email, template='tutor_verification', context=d) else: text_content = TUTOR_VERIFICATION_PLAINTEXT.render(d) html_content = TUTOR_VERIFICATION_HTMLY.render(d) mail.send(to, from_email, subject=subject, message=text_content, html_message=html_content)
def mail_send_gbe(to_list, from_address, template, context, priority='now'): if settings.DEBUG: to_list = [] for admin in settings.ADMINS: to_list += [admin[1]] try: mail.send( to_list, from_address, template=template, context=context, priority=priority, ) except: return "EMAIL_SEND_ERROR"
def send_notification(self, now=False): form = self.form ctx = self.get_context() priority = None if now: priority = PRIORITY.now emails = [] for email_template in form.get_email_templates(): to = email_template.to if email_template.is_reply_to_sender: to = [self.email] if not to: continue template_attachments = list(email_template.attachments.all()) if email_template.do_forward_attachments: template_attachments += list(self.attachments.all()) attachments = {} if template_attachments: for a in template_attachments: attachments[a.get_filename()] = a.file email = mail.send(recipients=to, sender=email_template.from_email or None, bcc=email_template.bcc, cc=email_template.cc, template=email_template.email_template, context=ctx, priority=priority, attachments=attachments or {}) emails.append(email) return emails