def send_notification_email(self, document, request, template): if document.uploader and document.uploader != request.user: # If there's no uploader then there's nobody to notify. # We also don't notify a user when they modify their own document. # # Documents being created by add_view don't have an uploader, # so they don't end up sending an email either, which is what # we want. We could also check for change=True. # Load a copy of the document, so that it still has an ID # if the caller delete()s it later document = models.Document.objects.get(id=document.id) from django.conf import settings context = { 'document': document, 'user': request.user, 'settings': settings, } from mail_templated import EmailMessage email = EmailMessage(template, context, to=[document.uploader.email]) email.send()
def send_email(template, to, **kwargs): message = EmailMessage() message.template_name = template message.context = kwargs message.from_email = '*****@*****.**' message.to = [to] if isinstance(to, str) else to message.send()
def send_submission_email(response, institution_id_max, total_submission, agency_email): from_email = getattr(settings, "EMAIL_FROM", "*****@*****.**") cc = getattr(settings, "EMAIL_CC", "") total_accepted = len(response) total_rejected = total_submission - total_accepted institution_existing = 0 institution_new = 0 for resp in response: for inst in resp['submitted_report']['institutions']: if inst['id'] > institution_id_max: institution_new += 1 else: institution_existing += 1 context = { 'response': response, 'total_submission': total_submission, 'total_accepted': total_accepted, 'total_rejected': total_rejected, 'institution_total': institution_new + institution_existing, 'institution_new': institution_new, 'institution_existing': institution_existing, 'max_inst_id': institution_id_max, 'date': datetime.date.today().strftime("%Y-%m-%d"), 'agency_email': agency_email } message = EmailMessage('email/submission.tpl', context=context, from_email=from_email, to=[agency_email], cc=cc) message.send()
def send(self, to): """ Sends this email to the list of the users in TO, with additional BCC and CC arguments. """ to = [to] if isinstance(to, User) else to connection = get_connection() for user in to: email = EmailMessage(template_name='api/email.html', context={ 'subject': Email._parse_text(self.subject, user), 'content': Email._parse_text(self.content, user), 'footer': Email._parse_text(self.footer, user) }, from_email=self.from_email, to=[user.email], connection=connection, reply_to=self.reply_to) for attachment in self.attachments.all(): email.attach(attachment.name, attachment.datafile, attachment.mimetype) email.send() self.times_sent += 1 self.save()
def get_success_url(self): message = EmailMessage('usuario/email/validacao_email.html', {'usuario': self.object}, settings.EMAIL_HOST_USER, to=[self.object.email]) message.send() return reverse('usuario_register_success')
def send_email(template_name, context, email_to): message = EmailMessage() message.template_name = template_name message.context = context message.from_email = settings.SERVER_EMAIL message.to = [email_to] message.send()
def mutate_and_get_payload(root, info, **input): model = UserModel if graph_auth_settings.ONLY_ADMIN_REGISTRATION and not ( info.context.user.id and info.context.user.is_staff): return RegisterUser(ok=False, user=None) if 'clientMutationId' in input: input.pop('clientMutationId') email = input.pop('email') username = input.pop(UserModel.USERNAME_FIELD, email) password = input.pop( 'password' ) if 'password' in input else model.objects.make_random_password() user = model.objects.create_user(username, email, password, **input) user.is_current_user = True if graph_auth_settings.WELCOME_EMAIL_TEMPLATE is not None and graph_auth_settings.EMAIL_FROM is not None: from mail_templated import EmailMessage input_data = user.__dict__ input_data['password'] = password message = EmailMessage(graph_auth_settings.WELCOME_EMAIL_TEMPLATE, input_data, graph_auth_settings.EMAIL_FROM, [user.email]) message.send() return RegisterUser(ok=True, user=user)
def send_invoice(invoice): # Initialize message on creation. message = EmailMessage('base/mail/invoice.html', {'invoice': invoice}, invoice.seller.email, to=[invoice.buyer.email]) message.attach_file(invoice.document.path) # Send message when ready. It will be rendered automatically if needed. message.send()
def not_created_email(unsubscribe_link, send_to): from_email = settings.DEFAULT_FROM_EMAIL message = EmailMessage('mail/account_not_created.tpl', { 'unsubscribe_link': unsubscribe_link, }, from_email, to=[send_to]) message.send()
def EnviarEmail(nome, estado, emailCliente): message = EmailMessage('paginas/email.html', { 'usuario': nome, 'agendamento': estado }, '*****@*****.**', to=[emailCliente]) # TODO: Add more useful commands here. message.send()
def profile_created_email(profile_type, send_to): from_email = settings.DEFAULT_FROM_EMAIL message = EmailMessage( 'mail/profile_created.tpl', { 'profile_type': profile_type, 'unsubscribe_link': 'https://dapp.os.university/#/settings', }, from_email, to=[send_to]) message.send()
def verification_email(verification_link, send_to): from_email = settings.DEFAULT_FROM_EMAIL message = EmailMessage( 'mail/email_verification.tpl', { 'verification_link': verification_link, 'unsubscribe_link': 'https://dapp.os.university/#/settings', }, from_email, to=[send_to]) message.send()
def inviting_email(connection, unsubscribe_link, owner_name): from_email = settings.DEFAULT_FROM_EMAIL message = EmailMessage('mail/linkedin_connection.tpl', { 'full_name': connection['full_name'], 'unsubscribe_link': unsubscribe_link, 'owner_name': owner_name, }, from_email, to=[connection['email']]) message.send()
def rejected_certificate_email(certificate_title, issuer_name, send_to): from_email = settings.DEFAULT_FROM_EMAIL message = EmailMessage( 'mail/certificate_rejected.tpl', { 'issuer_name': issuer_name, 'certificate_title': certificate_title, 'unsubscribe_link': 'https://dapp.os.university/#/settings', }, from_email, to=[send_to]) message.send()
def approved_job_application_email(job_title, issuer_name, send_to): from_email = settings.DEFAULT_FROM_EMAIL message = EmailMessage( 'mail/job_application_approved.tpl', { 'issuer_name': issuer_name, 'job_title': job_title, 'unsubscribe_link': 'https://dapp.os.university/#/settings', }, from_email, to=[send_to]) message.send()
def solicita(request): if request.method == 'POST': form = UserCreationForm(request.POST) form1 = New_Solic_cad(request.POST) print(form.errors) if form.is_valid(): post1 = form.save(commit=False) post1.first_name = 'first_access' post1.save() if request.POST.get('Contato'): if form1.is_valid(): Contato = request.POST.get('Contato') Obs = request.POST.get('Obs') post = form1.save(commit=False) post.Solicitante = request.user post.save() print(request.POST.get('username')) context = { 'contato': Contato, 'emp': 'rrrr', 'solicitante': request.user.username, 'obs': Obs, 'rec': request.POST.get('username') } message = EmailMessage('SOLICTA_EMP_MAIL.html', context, settings.EMAIL_HOST_USER, [ '*****@*****.**', '*****@*****.**', ], render=True) f = '/SIG_1.png' fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) message.attach(msg_img) message.send() return render(request, 'success.html', { 'Usmail': request.user.email, 'Solmail': post1.username }) else: form = UserCreationForm() form1 = New_Solic_cad() return render(request, 'Nsuccess.html') else: form = UserCreationForm() form1 = New_Solic_cad() return render(request, 'Nsuccess.html') else: form = UserCreationForm() form1 = New_Solic_cad() return render(request, 'solicita.html', {'form': form, 'form1': form1})
def send_new_song_emails_for_user(user_id): with transaction.atomic(): user = User.objects.get(id=user_id) orders = models.Order.objects.select_for_update().filter(email_notified=False, delivered=True, refunded=False, purchaser=user).select_related("song__snippet") if orders.count() == 0: logger.info("No orders to notify user #%s about" % (user_id,)) return logger.debug("Notify user #%s about new deliveries" % (user_id, )) playlist_url = settings.BASE_URL + reverse("personal-playlist") message = EmailMessage( 'spawnsong/email/new-songs.tpl', {'orders': orders, "playlist_url": playlist_url}, to=[user.email]) message.send() orders.update(email_notified=True)
def deliver_full_song_to_order(order_id, redeliver=False): """ Complete charge for order """ logger.debug("Deliver order #%s" % (order_id, )) with transaction.atomic(): order_qs = models.Order.objects.select_for_update().filter( refunded=False, pk=order_id) if not redeliver: order_qs = order_qs.filter(delivered=False) order = order_qs.get() song = order.song if not song.is_complete(): logger.warn( "Song #%s is not complete so there is no full song to deliver to order #%s" % (song.id, order_id)) return # logger.info("Delivering song #%s to order #%s" % (song.id, order_id)) # message = EmailMessage('spawnsong/email/full-song-delivery.tpl', {'order': order, 'song': order.song}, to=[order.purchaser_email]) # message.send() try: logger.info("Charge for song #%s to order #%s" % (song.id, order_id)) if not order.charged: charge = stripe.Charge.create( customer=order.stripe_customer_id, description="Pre-order of '%s' (id %s) by %s" % (song.title, song.id, song.artist.get_display_name()), amount=order.price, currency=settings.CURRENCY) order.stripe_transaction_id = charge.id order.charged = True order.delivered = True except Exception, e: logger.exception("Failed to charge order #%s" % (order_id)) order.charge_failed = True order.charge_error = repr(e) message = EmailMessage('spawnsong/email/charge-failed.tpl', { 'order': order, 'song': order.song }, to=[order.purchaser_email]) message.send() order.save()
def send_artist_sales_emails_for_arist(artist_id): yesterday = datetime.date.today() - datetime.timedelta(1) artist = models.Artist.objects.get(id=artist_id) orders = models.Order.objects.filter( song__artist=artist, created_at__range=(datetime.datetime.combine(yesterday, datetime.time.min), datetime.datetime.combine(yesterday, datetime.time.max))).order_by("song") grouped = list((x,list(y)) for (x,y) in itertools.groupby(orders, lambda o: o.song)) for song,song_orders in grouped: song_orders = list(song_orders) song.order_count = len(list(song_orders)) logger.debug("Send artist sales email send for Artist #%s (%s songs)" % (artist_id,len(grouped))) message = EmailMessage( 'spawnsong/email/artist-daily-report.tpl', {'songs': [song for (song,song_orders) in grouped]}, to=[artist.user.email]) message.send()
def mutate_and_get_payload(cls, input, context, info): if graph_auth_settings.CUSTOM_PASSWORD_RESET_TEMPLATE is not None\ and graph_auth_settings.EMAIL_FROM is not None and\ graph_auth_settings.PASSWORD_RESET_URL_TEMPLATE is not None: from mail_templated import EmailMessage for user in UserModel.objects.filter(email=input.get('email')): uid = urlsafe_base64_encode(force_bytes(user.pk)).decode() token = token_generator.make_token(user) link = graph_auth_settings.PASSWORD_RESET_URL_TEMPLATE\ .format(token=token, uid=uid) input_data = { "email": user.email, "first_name": user.first_name, "last_name": user.last_name, "link": link } message = EmailMessage( graph_auth_settings.CUSTOM_PASSWORD_RESET_TEMPLATE, input_data, graph_auth_settings.EMAIL_FROM, [user.email]) message.send() else: data = { 'email': input.get('email'), } reset_form = PasswordResetForm(data=data) if not reset_form.is_valid(): raise Exception("The email is not valid") options = { 'use_https': context.is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': context } reset_form.save(**options) return ResetPasswordRequest(ok=True)
def send_upn(request, event_name=False): event_instance = get_event_by_name_no_rights(event_name) profile = get_object_or_404(EventProfile, event=event_instance, user=request.user) context = { 'event': event_instance, 'profile': profile, 'date': datetime.now(), 'date_to': date.today() + timedelta(days=10) } for payment in event_instance.payment.all(): t_payment = payment.get_payments() if t_payment[0] == 'UPN': context['payment'] = t_payment[1] break print(context) return_file = "tmp/" + 'upn_' + event_instance.name + '_' + str( profile.id) + '.pdf' t = loader.get_template('Visitor/email/upn.html') #DEBUG FOR UPN #return render(request, 'Visitor/email/upn.html', context) response = render_pdf_from_template( request=request, context=context, input_template=t, header_template='', footer_template='', ) message = EmailMessage( 'Visitor/email/base_email.html', {'user': profile}, '*****@*****.**', #event_instance.sent_mail, to=[profile.user.email]) message.attach('invoice.pdf', response, 'application/pdf') message.send() return render(request, 'Visitor/mail_redirect.html', {})
def send_new_song_emails_for_user(user_id): with transaction.atomic(): user = User.objects.get(id=user_id) orders = models.Order.objects.select_for_update().filter( email_notified=False, delivered=True, refunded=False, purchaser=user).select_related("song__snippet") if orders.count() == 0: logger.info("No orders to notify user #%s about" % (user_id, )) return logger.debug("Notify user #%s about new deliveries" % (user_id, )) playlist_url = settings.BASE_URL + reverse("personal-playlist") message = EmailMessage('spawnsong/email/new-songs.tpl', { 'orders': orders, "playlist_url": playlist_url }, to=[user.email]) message.send() orders.update(email_notified=True)
def post(self, request): form = ProfileUserForm(request.POST, request.FILES) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.set_password(form.cleaned_data['password']) user.save() current_site = get_current_site(request) message = render_to_string( "components/acc_activate_email.html", { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes( user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data['email'] message = EmailMessage( 'components/acc_activate.tpl', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes( user.pk)).decode(), 'token': account_activation_token.make_token(user) }, settings.EMAIL_HOST_USER, to=[ to_email, ]) # email sending message.send() return render(request, "users/conf_email.html", {'user': user}) else: return self.get(request, errors=form.errors)
def deliver_full_song_to_order(order_id, redeliver=False): """ Complete charge for order """ logger.debug("Deliver order #%s" % (order_id,)) with transaction.atomic(): order_qs = models.Order.objects.select_for_update().filter(refunded=False, pk=order_id) if not redeliver: order_qs = order_qs.filter(delivered=False) order = order_qs.get() song = order.song if not song.is_complete(): logger.warn("Song #%s is not complete so there is no full song to deliver to order #%s" % (song.id, order_id)) return # logger.info("Delivering song #%s to order #%s" % (song.id, order_id)) # message = EmailMessage('spawnsong/email/full-song-delivery.tpl', {'order': order, 'song': order.song}, to=[order.purchaser_email]) # message.send() try: logger.info("Charge for song #%s to order #%s" % (song.id, order_id)) if not order.charged: charge = stripe.Charge.create( customer=order.stripe_customer_id, description="Pre-order of '%s' (id %s) by %s" % (song.title, song.id, song.artist.get_display_name()), amount=order.price, currency=settings.CURRENCY ) order.stripe_transaction_id = charge.id order.charged = True order.delivered = True except Exception, e: logger.exception("Failed to charge order #%s" % (order_id)) order.charge_failed = True order.charge_error = repr(e) message = EmailMessage('spawnsong/email/charge-failed.tpl', {'order': order, 'song': order.song}, to=[order.purchaser_email]) message.send() order.save()
def mutate_and_get_payload(cls, input, context, info): model = UserModel if graph_auth_settings.ONLY_ADMIN_REGISTRATION and not (context.user.id and context.user.is_staff): return RegisterUser(ok=False, user=None) if 'clientMutationId' in input: input.pop('clientMutationId') email = input.pop('email') username = input.pop(UserModel.USERNAME_FIELD, email) password = input.pop('password') if 'password' in input else model.objects.make_random_password() user = model.objects.create_user(username, email, password, **input) user.is_current_user = True django.contrib.auth.login(context, user) if graph_auth_settings.WELCOME_EMAIL_TEMPLATE is not None and graph_auth_settings.EMAIL_FROM is not None: from mail_templated import EmailMessage input_data = user.__dict__ input_data['password'] = password message = EmailMessage(graph_auth_settings.WELCOME_EMAIL_TEMPLATE, input_data, graph_auth_settings.EMAIL_FROM, [user.email]) message.send() return RegisterUser(ok=True, user=user)
def notify_user(): print("TASK") # lookup user by id and send them a message user = User.objects.all() today = pytz.utc.localize(datetime.datetime.utcnow()) for u in user: last_login = u.last_login if last_login is None: continue else: offline = today - u.last_login if offline > timedelta(days=5): from_email = '*****@*****.**' link = "http://127.0.0.1:8000/" from mail_templated import EmailMessage message = EmailMessage('email\\reminder.tpl', {'u': u, 'link': link}, to=[u.email]) # TODO: Add more useful commands here. message.send()
def send_artist_sales_emails_for_arist(artist_id): yesterday = datetime.date.today() - datetime.timedelta(1) artist = models.Artist.objects.get(id=artist_id) orders = models.Order.objects.filter( song__artist=artist, created_at__range=(datetime.datetime.combine(yesterday, datetime.time.min), datetime.datetime.combine( yesterday, datetime.time.max))).order_by("song") grouped = list( (x, list(y)) for (x, y) in itertools.groupby(orders, lambda o: o.song)) for song, song_orders in grouped: song_orders = list(song_orders) song.order_count = len(list(song_orders)) logger.debug("Send artist sales email send for Artist #%s (%s songs)" % (artist_id, len(grouped))) message = EmailMessage( 'spawnsong/email/artist-daily-report.tpl', {'songs': [song for (song, song_orders) in grouped]}, to=[artist.user.email]) message.send()
def mutate_and_get_payload(cls, input, context, info): if graph_auth_settings.CUSTOM_PASSWORD_RESET_TEMPLATE is not None and graph_auth_settings.EMAIL_FROM is not None and graph_auth_settings.PASSWORD_RESET_URL_TEMPLATE is not None: from mail_templated import EmailMessage for user in UserModel.objects.filter(email=input.get('email')): uid = urlsafe_base64_encode(force_bytes(user.pk)).decode() token = token_generator.make_token(user) link = graph_auth_settings.PASSWORD_RESET_URL_TEMPLATE.format(token=token, uid=uid) input_data = { "email": user.email, "first_name": user.first_name, "last_name": user.last_name, "link": link } message = EmailMessage(graph_auth_settings.CUSTOM_PASSWORD_RESET_TEMPLATE, input_data, graph_auth_settings.EMAIL_FROM, [user.email]) message.send() else: data = { 'email': input.get('email'), } reset_form = PasswordResetForm(data=data) if not reset_form.is_valid(): raise Exception("The email is not valid") options = { 'use_https': context.is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': context } reset_form.save(**options) return ResetPasswordRequest(ok=True)
order.maybe_queue_delivery() except: logger.exception("Failed to capture charge") return HttpResponseRedirect( snippet.get_absolute_url() + "?paymenterror=" + urllib.quote("Sorry, there was an error processing your card")) # Send email to purchaser try: message = EmailMessage('spawnsong/email/order-song.tpl', { 'order': order, 'song': snippet.song, 'is_preorder': not snippet.is_complete() }, to=[order.purchaser_email]) message.send() except: logger.exception("Failed to send email receipt") # # Send email to artist # message = EmailMessage('spawnsong/email/song-purchased.tpl', {'order': order, 'song': snippet.song, 'is_preorder': not snippet.is_complete()}, to=[snippet.song.artist.user.email]) # message.send() snippet.update_ordering_score() return HttpResponseRedirect(snippet.get_absolute_url() + "?paymentsuccess") class RegistrationView(DefaultRegistrationView): pass
def home(request): if request.method =="POST": firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') profile = request.FILES['image'] password = request.POST.get('password') pin = request.POST.get('pin') email = request.POST.get('email') address = request.POST.get('address') patientdob = request.POST.get('dob') repassword = request.POST.get('repassword') number = request.POST.get('number') citizennumber = request.POST.get('cnumber') try: validate_email(email) if patient.objects.filter(patientemail=email).exists() or hospital.objects.filter(hospitalemail=email).exists(): messages.add_message(request, messages.INFO, 'Invalid! Email or Email exists already please Enter Correctly !') return render(request, 'Patient/patientlogin.html') elif patient.objects.filter(citizennumber=citizennumber).exists(): messages.add_message(request, messages.INFO, 'Invalid! Citizenship number please Enter Correctly !') return render(request, 'Patient/patientlogin.html') elif password != repassword: messages.add_message(request, messages.INFO, 'Password donot match please Enter Correctly !') return render(request, 'Patient/patientlogin.html') else: patientdata = patient(patientfirstname=firstname, patientlastname=lastname, patientaddress=address, patientemail=email, patientpassword=password, patientnumber=number, citizennumber=citizennumber,patientdob=patientdob, patientprofile=profile, patientpin=pin) patientdata.save() help = patient.objects.get(patientemail=email) nam1= help.patientfirstname nam2 = help.patientlastname num=help.citizennumber nam=nam1+' '+nam2 hid = help.id profile = help.patientprofile user = hospitalactivity.objects.all().order_by('?')[:10] user2 = patientactivity.objects.all().order_by('?')[:10] try: request.session['logged']=nam from django.core.mail import send_mail # send_mail('New account Register', 'Hey there,' # '\n We have received a request that you are Register New account.' # '\n If you did not initiate this request,Inform us Immediately.' # '\n Greetings,\n Team Digital Report', # '*****@*****.**', [email], # fail_silently=False) from mail_templated import EmailMessage message = EmailMessage('Patient/regis_email.tpl', {'user': nam},'*****@*****.**',[email]) message.send() return render(request, 'Patient/patienthome.html',{"name": nam, 'id': hid,'number':num, 'profile': profile, 'activity': user,'activity2':user2}) except: return render(request, 'Patient/patientlogin.html') except ValidationError: messages.add_message(request, messages.INFO, 'Invalid! Email or Email exists already please Enter Correctly !') return render(request, 'home.html') else: return render(request, 'home.html')
def sendemail(emailtemplate, username, toemail): from mail_templated import EmailMessage message = EmailMessage(emailtemplate, {'user': username}, 'your email', to=[toemail]) message.send()
class Owl(): """ Owl is an email agent. It utilizes default send_mail() as a message-backend, hoping you have configured it properly. On the production host it tries to queue your message via the Celery daemon. For usage examples please see tests. """ timezone = None def __init__(self, template, ctx, from_email=None, timezone=None, to=[]): if from_email is None: from_email = settings.EMAIL_NOTIFICATIONS_FROM self.template = template self.ctx = ctx self.to = to self.from_email = from_email if timezone is not None: if isinstance(timezone, str): self.timezone = pytz.timezone(timezone) else: self.timezone = timezone self.headers = { 'X-ELK-Timezone': str(self.timezone), } self.EmailMessage() @user_tz @disable_i18n def EmailMessage(self): """ This method preventively renders a message to catch possible errors in the main flow. """ self.msg = EmailMessage( self.template, self.ctx, self.from_email, self.to, headers=self.headers, reply_to=[settings.REPLY_TO], ) self.msg.render() @user_tz @disable_i18n def send(self): """ Send message On the production host uses celery, on dev — django configured backend. """ if not self.clean(): logger.warning('Trying to send invalid message!') return if not settings.EMAIL_ASYNC: self.msg.send() else: self.queue() @user_tz @disable_i18n def queue(self): self.headers['X-ELK-Queued'] = 'True' send_email.delay(owl=self) def attach(self, filename=None, content=None, mimetype=None): """ Add an attachment to the message See http://django-mail-templated.readthedocs.io/en/master/api.html?highlight=attach#mail_templated.EmailMessage.attach """ return self.msg.attach(filename, content, mimetype) def clean(self): if not self.to or not self.to[0]: return False return True
class Owl(): """ Owl is an email agent. It utilizes default send_mail() as a message-backend, hoping you have configured it properly. On the production host it tries to queue your message via the Celery daemon. For usage examples please see tests. """ timezone = None def __init__(self, template, ctx, from_email=None, reply_to=None, timezone=None, to=None): if to is None: to = [] if from_email is None: from_email = settings.EMAIL_NOTIFICATIONS_FROM if reply_to is None: reply_to = settings.REPLY_TO self.template = template self.ctx = ctx self.to = to self.reply_to = reply_to self.from_email = from_email if timezone is not None: if isinstance(timezone, str): self.timezone = pytz.timezone(timezone) else: self.timezone = timezone self.headers = { 'X-GM-Timezone': str(self.timezone), } self.EmailMessage() def EmailMessage(self): """ This method preventively renders a message to catch possible errors in the main flow. """ self.msg = EmailMessage( self.template, self.ctx, self.from_email, self.to, headers=self.headers, reply_to=[self.reply_to], ) self.msg.render() def send(self): """ Send message """ if not self.clean(): return if not settings.DISABLE_NOTIFICATIONS and settings.EMAIL_ENABLED: self.msg.send() def add_cc(self, *args): """ Add a list of recipients """ self.msg.cc += args def attach(self, filename=None, content=None, mimetype=None): """ Add an attachment to the message See http://django-mail-templated.readthedocs.io/en/master/api.html?highlight=attach#mail_templated.EmailMessage.attach """ return self.msg.attach(filename, content, mimetype) def clean(self) -> bool: if not self.to or not self.to[0]: return False return True
def home(request): if request.method == "POST": fullname = request.POST.get('name') profile = request.FILES['image'] password = request.POST.get('passd') email = request.POST.get('email') address = request.POST.get('address') repassword = request.POST.get('repassd') number = request.POST.get('number') pan = request.POST.get('pan') try: validate_email(email) if hospital.objects.filter( hospitalemail=email).exists() or patient.objects.filter( patientemail=email).exists(): messages.add_message( request, messages.INFO, 'Invalid! Email or Email exists already please Enter Correctly' ) return render(request, 'Hospital/hospitallogin.html') elif hospital.objects.filter(hospitalpan=pan).exists(): messages.add_message( request, messages.INFO, 'Invalid! PAN number please Enter Correctly') return render(request, 'Hospital/hospitallogin.html') elif password != repassword: messages.add_message( request, messages.INFO, 'Password do not match please Enter Correctly') return render(request, 'Hospital/hospitallogin.html') else: course_hospitaldata = hospital(hospitalname=fullname, hospitaladdress=address, hospitalemail=email, hospitalpassword=password, hospitalnumber=number, hospitalpan=pan, hospitalprofile=profile) course_hospitaldata.save() help = hospital.objects.get(hospitalemail=email) nam = help.hospitalname hid = help.id profile = help.hospitalprofile user = hospitalactivity.objects.all().order_by('?')[:10] user2 = patientactivity.objects.all().order_by('?')[:10] try: request.session['logged'] = nam from django.core.mail import send_mail from mail_templated import EmailMessage message = EmailMessage('Patient/regis_email.tpl', {'user': nam}, '*****@*****.**', [email]) message.send() return render( request, 'Hospital/hospitalhome.html', { "name": nam, 'id': hid, 'profile': profile, 'activity': user, 'activity2': user2 }) except: return render(request, 'Hospital/hospitallogin.html') except ValidationError: messages.add_message( request, messages.INFO, 'Invalid! Email or Email exists already please Enter Correctly' ) return render(request, 'Hospital/hospitallogin.html') else: return render(request, 'Hospital/hospitallogin.html')
def send_email(template, context, from_email, to, thread=None): to = [to] if isinstance(to, str) else to headers = thread and {'In-Reply-To': thread} or {} msg = EmailMessage(template, context, from_email=from_email, to=to, headers=headers) msg.send() print('sending email: %s -> %s' % (from_email, to))
song=snippet.song, artist_payment=artistpayment, purchaser=request.user if request.user.is_authenticated() else None, purchaser_email=email, price=snippet.price, stripe_customer_id=customer.id) order.maybe_queue_delivery() except: logger.exception("Failed to capture charge") return HttpResponseRedirect(snippet.get_absolute_url() + "?paymenterror=" + urllib.quote("Sorry, there was an error processing your card")) # Send email to purchaser try: message = EmailMessage('spawnsong/email/order-song.tpl', {'order': order, 'song': snippet.song, 'is_preorder': not snippet.is_complete()}, to=[order.purchaser_email]) message.send() except: logger.exception("Failed to send email receipt") # # Send email to artist # message = EmailMessage('spawnsong/email/song-purchased.tpl', {'order': order, 'song': snippet.song, 'is_preorder': not snippet.is_complete()}, to=[snippet.song.artist.user.email]) # message.send() snippet.update_ordering_score() return HttpResponseRedirect(snippet.get_absolute_url() + "?paymentsuccess") class RegistrationView(DefaultRegistrationView): pass @login_required