def get(self, email): if email: person_query = PersonEntityClass.query(PersonEntityClass.email==email) if person_query.count(): person = person_query.fetch()[0] values = { 'name': person.name, 'spouse': person.spouse, 'family': person.family, 'veg': person.veg, 'total_veg_cost': person.total_veg_cost, 'nonveg': person.nonveg, 'total_non_veg_cost': person.total_non_veg_cost, 'total_food_cost': person.total, 'email': person.email } self.response.write(pay_template.render(values)) if not person.email_sent: person.email_sent = True person.put() send_email(**values) else: self.response.write(cancel_template.render()) else: self.redirect('/')
def main(): '''This Job runs every day at noon and should give the list of stocks announcing the next day''' subject = 'Your Companies Earnings Announcements Tomorrow' # 0. get current day day = Time.get_time_for_delta('days', 1) day = Time.time_to_str_time(day) # 1. Get all the list of users users = base.managers.user_manager.get_many() # 2. for each user, get the list of stocks they are following for user in users: announcing_stocks = [] stocks = user.get_stocks_for_user() # 3. for each stock, check if the announcement date matches the day for stock in stocks: announcement_date = stock.get('time') if not announcement_date: continue announcement_date = Time.time_to_str_time(announcement_date) if announcement_date == day: announcing_stocks.append(stock.get('ticker')) # 4. list is not empty, send user a notification email if len(announcing_stocks) > 0: print "-->user, date, stocks: %s:%s:%s" % (user.get('email'), day, announcing_stocks) html_content = print_table(announcing_stocks, 3) email.send_email(user.get('email'), None, subject, '', html_content)
def save(self, *args, **kwargs): result = super().save(*args, **kwargs) subject = "A new testimonial has been created on '{}'".format(settings.SITE_TITLE) for (name, email) in settings.MANAGERS: context = {'testimonial': self, 'name': name, 'site_title': settings.SITE_TITLE} send_email(subject, [email], 'testimonials/email/notification.html', context) return result
def send_mail(self, subject, message, template, **kwargs): """ Sends an email to this User. """ from_email = kwargs.pop('from_email', get_variable_from_settings('SOCIAL_EMAIL_ADDRESS')) from_name = kwargs.pop('from_name', get_variable_from_settings('SOCIAL_EMAIL_NAME')) send_email([self.email], subject, message, template, from_email, from_name, **kwargs)
def send_password_reset(user, uid, token): try: email_subject = 'Django real-time demo password reset' confirm_reset_url = "%s%s" % (settings.SITE_URL, reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token})) return send_email(user.email, email_subject, 'emails/password_reset.html', { 'user': user, 'confirm_reset_url': confirm_reset_url, }) except: logger.exception("Couldn't send password reset to %s (%d)", user.email, user.id)
def main(): mail_list = ['*****@*****.**', '*****@*****.**'] stock_list = ['000905.XSHG'] auth('18516227429', 'Mcgrady1') while True: spare = get_query_count()['spare'] if spare > 10000: df = get_daily_trading_data(stock_list) result = calculating(df) if len(result) > 0: send_email( mail_list, subject='Qualified stocks @[{ts}]'.format( ts=datetime.datetime.now()), contents=['Qualified stocks found are as follows:\n'] + result) else: send_email(mail_list, 'Balance not enough', ['Current balance = {}'.format(spare)]) print('Exit due to lacking of jqData spare') return
def send_password_reset(user, uid, token): try: email_subject = 'H&E Medicinal password reset' confirm_reset_url = "%s%s" % (settings.SITE_URL, reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token})) return send_email(user.email, email_subject, 'emails/password_reset.html', { 'user': user, 'confirm_reset_url': confirm_reset_url, }) except: logger.exception("Couldn't send password reset to %s (%d)", user.email, user.id)
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): username = request.POST.get("email", "") if UserProfile.objects.filter(email=username): return render( request, "register.html", { "msg": "The email address has been registered", "register_form": register_form }) password = request.POST.get("password", "") user = UserProfile() user.username = username user.email = username user.password = make_password(password) user.is_active = False user.save() send_email(username, "r") return render(request, "login.html") else: return render(request, "register.html", {"register_form": register_form})
def send_report(queryset: GameSessionQuerySet): for_update = queryset.reported() timestamp = timezone.now().strftime("%Y-%m-%d") receivers = list(User.objects.filter(is_superuser=True).values_list("email", flat=True)) games = [] for session in for_update: game = { "date": session.date.strftime("%Y-%m-%d"), "players": list( session.gamesessionplayersignup_set.filter(reported=True).values_list("player__dci", flat=True) ), "dm": str(session.dm.dci), "extra_players": session.extra_players if session.extra_players else "", } print(game) games.append(game) send_email(f"Report for the games {timestamp}", "emails/games_report.html", {"games": games}, to=receivers) return for_update.count()
def accept(self): """ When a seller accepts a user's request and agrees to go to the show with them. """ ticket = self.ticket poster = ticket.poster requester = self.requester # Make sure that the ticket and request are updated in tandem with transaction.atomic(): self.status = 'A' self.save() ticket.change_status('S') Message.objects.create_message(poster, requester, ticket, "This is an automated message: Congratulations, the request was accepted! Check your email for next steps.", False) send_email([poster.email, requester.email], REQUEST_ACCEPTED_SUBJECT, '', REQUEST_ACCEPTED_TEMPLATE, ticket=ticket )
def send_files_report(): html_template = 'reporting/email/files_report.html' text_template = 'reporting/email/files_report.txt' for control in Control.objects.all(): logger.info(f'Processing control: {control.id}') if control.depositing_organization: subject = control.depositing_organization else: subject = control.title subject += ' - de nouveaux documents déposés !' files = get_files(control) if not files: logger.info(f'No new documents, aborting.') continue recipients = control.user_profiles.filter(send_files_report=True) recipient_list = recipients.values_list('user__email', flat=True) if not recipient_list: logger.info(f'No recipients, aborting.') continue logger.debug(f'Recipients: {len(recipient_list)}') date_cutoff = get_date_cutoff(control) context = { 'control': control, 'date_cutoff': date_cutoff.strftime("%A %d %B %Y"), 'files': files, } number_of_sent_email = send_email( to=recipient_list, subject=subject, html_template=html_template, text_template=text_template, extra_context=context, ) logger.info(f"Sent {number_of_sent_email} emails") number_of_recipients = len(recipient_list) if number_of_sent_email != number_of_recipients: logger.warning(f'There was {number_of_recipients} recipient(s), ' f'but {number_of_sent_email} email(s) sent.') if number_of_sent_email > 0: logger.info(f'Email sent for control {control.id}') action.send(sender=control, verb=ACTION_LOG_VERB_SENT) else: logger.info(f'No email was sent for control {control.id}') action.send(sender=control, verb=ACTION_LOG_VERB_NOT_SENT) EMAIL_SPACING_TIME_SECONDS = settings.EMAIL_SPACING_TIME_MILLIS / 1000 logger.info( f'Waiting {EMAIL_SPACING_TIME_SECONDS}s after emailing for control {control.id}' ) time.sleep(EMAIL_SPACING_TIME_SECONDS)
def accept(self): """ When a seller accepts a user's request and agrees to go to the show with them. """ ticket = self.ticket poster = ticket.poster requester = self.requester # Make sure that the ticket and request are updated in tandem with transaction.atomic(): self.status = 'A' self.save() ticket.change_status('S') Message.objects.create_message( poster, requester, ticket, "This is an automated message: Congratulations, the request was accepted! Check your email for next steps.", False) send_email([poster.email, requester.email], REQUEST_ACCEPTED_SUBJECT, '', REQUEST_ACCEPTED_TEMPLATE, ticket=ticket)
def forgot(): if request.method == 'POST': stdid = request.form['student_id'] email = request.form['email'] if stdid == "" or email == "": flash("Please do not leave blank!", 'warn') return render_template('forgot.html') stored_pwd = get_attribute_from_member(client, stdid, "password") _object = {'id': stdid, 'pwd': stored_pwd} serialized = serializer.dumps(_object, "forgot-password") recovery_url = "https://ieeesutdweb.herokuapp.com/{}".format( serialized) recovery_msg = ''' Hello, A request to reset your IEEE SUTD Loaning System account password was received. Click on the link below to reset your password and sign into your account. This link is valid for 10 minutes. {} You can safely disregard this email if you didn't request a password reset and your password will not be changed. Thanks. IEEE SUTD Student Branch IEEE Web Development Team Contact us: [email protected] [This is an auto-generated email. Please do not reply.] '''.format(recovery_url) status = send_email(recovery_msg, email) if status == -1: flash( "Email was not sent due to network issue. Please try again later!", 'warn') return render_template('forgot.html') flash( "A recovery link has been sent to your email. The link will be expired in 10 minutes.", 'success') return render_template('forgot.html') else: return render_template('forgot.html')
def send_files_report(): html_template = 'reporting/email/files_report.html' text_template = 'reporting/email/files_report.txt' for control in Control.objects.all(): logger.info(f'Processing control: {control}') if control.depositing_organization: subject = control.depositing_organization else: subject = control.title subject += ' - de nouveaux documents déposés !' logger.debug(f"Email subject: {subject}") files = get_files(control) if not files: continue recipients = control.user_profiles.filter(send_files_report=True) recipient_list = recipients.values_list('user__email', flat=True) logger.info(f'Recipients: {recipient_list}') if not recipient_list: continue date_cutoff = get_date_cutoff(control) context = { 'control': control, 'date_cutoff': date_cutoff.strftime("%A %d %B %Y"), 'files': files, } number_of_sent_email = send_email( to=recipient_list, subject=subject, html_template=html_template, text_template=text_template, extra_context=context, ) logger.info(f"Sent {number_of_sent_email} emails") number_of_recipients = len(recipient_list) if number_of_sent_email != number_of_recipients: logger.warning(f'There was {number_of_recipients} recipient(s), ' f'but {number_of_sent_email} email(s) sent.') if number_of_sent_email > 0: logger.info(f'Email sent for {control}') action.send(sender=control, verb=ACTION_LOG_VERB_SENT) else: logger.info(f'No email was sent for "{control}"') action.send(sender=control, verb=ACTION_LOG_VERB_NOT_SENT)
from utils.email import send_email, checkIfSent from bs4 import BeautifulSoup import requests store_name = "Btgames" if checkIfSent(store_name) is False: notify = False inStock = "" link = "https://www.btgames.co.za/consoles/playstation/ps5-sony-playstation-digital-console-2" r = requests.get(link) soup = BeautifulSoup(r.text, "html.parser") try: inStock = soup.find( "div", class_="product-info-stock-sku").div.span.get_text() except: pass # do nothing if the item doesn't exist if inStock.lower() != "out of stock": notify = True print(f"{store_name} has stock: ", notify) if notify: # Send a notification send_email(store_name, link)
def member_info(student_id): if is_admin(): info = get_loaning_status(client, student_id) name = get_attribute_from_member(client, student_id, 'name') has_expired = False expiry_dates = get_attributes_from_sub_coll(client, student_id, "expiry") now = datetime.datetime.now() for date in expiry_dates: if datetime.datetime.timestamp(now) > datetime.datetime.timestamp( date): has_expired = True break if request.method == "POST": try: remind_btn = request.form['remind'] except: remind_btn = None try: return_one = request.form['return_one'] except: return_one = None try: return_all = request.form['return_all'] except: return_all = None if remind_btn is not None: expired_items_str = "" student_email = get_attribute_from_member( client, student_id, "email") loaned_items = get_loaning_status(client, student_id) now = datetime.datetime.now() for item in loaned_items: expiry = item['expiry'] if datetime.datetime.timestamp( now) > datetime.datetime.timestamp(expiry): expired_items_str += "Item: {} , Item ID: {} , Expiry Date: {}\n".format( item['name'], item['id'], expiry) reminder_email = ''' Dear {}, You have expired item(s) that have yet to be returned! Please return them ASAP otherwise you will not be able to loan any more item. Your expire item is/are: {} Please make an arrangement with any of the exco members via Telegram or Email to return your item. Thank you for your understanding! IEEE SUTD Student Branch IEEE Web Development Team [This is an auto-generated email. Please do not reply.] '''.format(name, expired_items_str) send_email(reminder_email.encode('utf-8'), student_email) flash( "Reminder email has been successfully sent to {}".format( name), 'success') return render_template('member_info.html', info=info, name=name, expired=has_expired) elif return_one is not None: item_id = return_one old_quantity = get_attr_from_sub_doc_x(client, student_id, item_id, "quantity") new_quantity = old_quantity - 1 old_limit = get_attribute_from_member(client, student_id, "limit") if new_quantity == 0: a = delete_sub_doc(item_id, student_id) b = delete_sub_coll_doc(client, student_id, item_id) if a == -1 or b == -1: flash( "Unable to update sub collection loaned item quantity!" ) return redirect(url_for('error_api.error')) else: old_quantity_from_inventory = get_sub_attr_from_member( item_id, student_id, "quantity") new_quantity_from_inventory = old_quantity_from_inventory - 1 status = update_sub_coll_attribute(client, student_id, item_id, "quantity", new_quantity) status_inventory = update_attr_sub_coll( item_id, student_id, "quantity", new_quantity_from_inventory) if status == -1 or status_inventory == -1: flash( "Unable to update sub collection loaned item quantity!" ) return redirect(url_for('error_api.error')) new_limit = old_limit + 1 limit_update = change_attribute_of_member( client, student_id, "limit", new_limit) if limit_update == -1: flash("Failed to update member's limit.") return redirect(url_for('error_api.error')) old_quantity_inventory = get_attribute_value( item_id, "quantity") new_quantity_inventory = old_quantity_inventory + 1 status_update = update_attribute_value(item_id, "quantity", new_quantity_inventory) if status_update == -1: flash( "Failed to update quantity in the main inventory system." ) return redirect(url_for('error_api.error')) info = get_loaning_status(client, student_id) return render_template('member_info.html', info=info, name=name, expired=has_expired) elif return_all is not None: item_id = return_all old_limit = get_attribute_from_member(client, student_id, "limit") old_loaned_quantity = get_attr_from_sub_doc_x( client, student_id, item_id, "quantity") old_quantity_inventory = get_attribute_value( item_id, "quantity") new_quantity_inventory = old_quantity_inventory + old_loaned_quantity new_limit = old_limit + old_loaned_quantity limit_update = change_attribute_of_member( client, student_id, "limit", new_limit) if limit_update == -1: flash("Failed to update member's limit.") return redirect(url_for('error_api.error')) status_update = update_attribute_value(item_id, "quantity", new_quantity_inventory) status_delete = delete_sub_coll_doc(client, student_id, item_id) status_delete_inventory = delete_sub_doc(item_id, student_id) if status_update == -1 or status_delete == -1 or status_delete_inventory == -1: flash( "Failed to update quantity in the main inventory system." ) return redirect(url_for('error_api.error')) info = get_loaning_status(client, student_id) return render_template('member_info.html', info=info, name=name, expired=has_expired) else: return render_template('member_info.html', info=info, name=name, expired=has_expired) else: flash("You are unauthorized!") return redirect(url_for('login_api.login'))
def aircraft(request, aircraftid): if request.method == 'GET': from factory import engine threshold=20 aircrafts = engine.execute( '''select * from flotte where "Nom de l'appareil"=%(aircraftid)s''', {"aircraftid": aircraftid} ).fetchall() query = ''' select RUL,ts from rultrack r where r.aircraftid=%(aircraftid)s order by ts asc ''' aircraft_res = {} for aircraft in aircrafts: aircraftid = aircraft[2] aircraft_type = aircraft[1] res = engine.execute(query, {"aircraftid": aircraftid}).fetchall() ruls = [res[i][0] for i in range(len(res))] ts = [str(res[i][1]) for i in range(len(res))] if(len(res)==0): aircraft_res = {"name": aircraftid, "aircraft_type": aircraft_type, "status" : "undefined", "rul": [], "timeseries" : []} else: status= "healthy" if(ruls[-1]<threshold): status="in danger" aircraft_res = { "status": status, "name": aircraftid, "aircraft_type": aircraft_type, "rul": ruls, "timeseries": ts } return HttpResponse(json.dumps(aircraft_res), content_type='text/json') if request.method == 'POST': threshold=20 from factory import predictive_maintenance_model from factory import engine import pandas as pd payload = json.loads(request.body) sensors = dict(payload) ts = datetime.datetime.strptime(payload["TimeStamp"], "%Y-%m-%d %H:%M:%S.%f") del sensors["TimeStamp"] df = pd.DataFrame([sensors]) print(df) print(ts) RUL = predictive_maintenance_model.predict(df)[0] query=''' INSERT INTO rultrack (aircraftid, rul, ts) VALUES (%(aircraftid)s, %(RUL)s, %(ts)s) ''' engine.execute(query, {"aircraftid": aircraftid, "RUL": RUL, "ts": str(ts)}) if (RUL<20): from utils.email import send_email send_email(aircraftid, RUL) return HttpResponse(json.dumps({"result" : True, "RUL": RUL, "aircraftid": aircraftid}), content_type='text/json') if request.method == 'DELETE': from factory import engine try: query='''delete from rultrack where aircraftid=%(aircraftid)s''' engine.execute(query, {"aircraftid": aircraftid}) return HttpResponse(json.dumps({"result": True}), content_type='text/json') except Exception as e: return HttpResponse(json.dumps({"result": False, "exception": str(e)}), content_type='text/json')
def loan(): logged_in = is_login() admin = is_admin() if logged_in: inventory = create_inventory_dictionary() session_name = session['name'] student_id = session['id'] if request.method == "POST": try: picked_id = request.form['select'] except Exception as e: print("No selection is done!", e) flash("You have yet to select anything!") return render_template('loan.html', name=session_name, inventory=inventory, id=student_id, admin=admin) quantity = get_attribute_value(picked_id, "quantity") item_name = get_attribute_value(picked_id, "name") limits = get_attribute_from_member(client, student_id, "limit") expiry_dates = get_attributes_from_sub_coll( client, student_id, "expiry") now = datetime.datetime.now() for date in expiry_dates: if datetime.datetime.timestamp( now) > datetime.datetime.timestamp(date): flash( "You have expired item(s). Please check your loan record and return the expired item before making a new loan!" ) return redirect(url_for('confirm_api.confirm')) if limits == 0: flash( "You have already loaned 5 items! You can't loan until you return them." ) return redirect(url_for('confirm_api.confirm')) if quantity == 0: flash( "You selected an item which is run out. Please select other items we have." ) return redirect(url_for('confirm_api.confirm')) update_attribute_value(picked_id, "quantity", quantity - 1) change_attribute_of_member(client, student_id, "limit", limits - 1) # for inventory side is_exist = check_sub_doc_exist(picked_id, student_id) if is_exist: number = get_sub_attr_from_member(picked_id, student_id, "quantity") if number == -1: number = 0 else: number = 0 # for member side x_is_exist = check_sub_doc_exist_x(client, student_id, picked_id) if x_is_exist: x_number = get_attr_from_sub_doc_x(client, student_id, picked_id, "quantity") if x_number == -1: x_number = 0 else: x_number = 0 expiry = now + datetime.timedelta(days=30) student_email = get_attribute_from_member(client, student_id, "email") std_name = get_attribute_from_member(client, student_id, "name") sub_object = { "student": student_id, "name": std_name, "email": student_email, "quantity": number + 1, "expiry": expiry } sub_object_2 = { "id": picked_id, "name": item_name, "quantity": x_number + 1, "expiry": expiry } inventory_updated = create_sub_collection(picked_id, "loaners", student_id, sub_object) member_updated = create_sub_collection_member( client, student_id, "loaned_items", picked_id, sub_object_2) if inventory_updated == -1 or member_updated == -1: flash("Can't create sub collection!") return redirect(url_for('error_api.error')) new_quantity = get_attribute_value(picked_id, "quantity") new_limit = get_attribute_from_member(client, student_id, "limit") student_name = get_attribute_from_member(client, student_id, "name") student_email = get_attribute_from_member(client, student_id, "email") master_email = ''' [Inventory System Update] --Item: {} --Item ID: {} --Quantity left: {} was loaned out successfully by --Student ID: {} --Studnet name: {} --Remaining loans: {} Item expiry date is set to be: {} '''.format(item_name, picked_id, new_quantity, student_id, student_name, new_limit, datetime.datetime.strftime(now, "%Y-%m-%d %H:%M:%S")) loaner_email = ''' Thank you for using IEEE SUTD Student Branch online inventory loaning system. Here is a summary for your loaning status. --Loaned Item: {} --Item ID: {} --Expiry date: {} Please make an arrangement with any of the exco members via Telegram or Email to collect your item. For further query, please contact us at [email protected] Please remember to return your item before the expiry date. Thank you for your understanding! IEEE SUTD Student Branch IEEE Web Development Team [This is an auto-generated email. Please do not reply.] '''.format(item_name, picked_id, datetime.datetime.strftime(now, "%Y-%m-%d %H:%M:%S")) send_email(master_email.encode('utf-8'), "*****@*****.**") sleep(1) send_email(loaner_email.encode('utf-8'), student_email) flash_message = "You picked {}. " \ "Now left {}. " \ "Remaining number of items you can loan: {}. " \ "Check your loaned item here".format(item_name, new_quantity, new_limit) flash(flash_message) return redirect(url_for('confirm_api.confirm')) else: return render_template('loan.html', name=session_name, inventory=inventory, id=student_id, admin=admin) else: flash("Please login first!") return redirect(url_for('login_api.login'))
def submit(request): log = logging.getLogger('logentries') log.setLevel(logging.INFO) handler = LogentriesHandler('28379e13-d9b8-434f-a233-7ec9369d2fcb') log.addHandler(handler) if request.method == 'POST': log.info("executing views.submit()"); try: contact_form = ContactForm(request.POST) except Exception as e: #log.error("ContactForm exception error({0}): {1}".format(e.errno, e.strerror)) log.error("ContactForm exception error") raise #log.info("contactForm() isvalid({0}) -> body: '{1}' email: '{2}' subject: '{3}'.".format(contact_form.is_valid(), contact_form.body, contact_form.from_email_address, contact_form.subject_type)); if contact_form.is_valid(): try: subject_type = contact_form.cleaned_data.get('subject_type') subject_type = reverse_category_lookup(subject_type, contact_form_settings.get('SUBJECT_TYPES')) body = contact_form.cleaned_data.get('body') from_email_address = contact_form.cleaned_data.get('from_email_address') except Exception as e: #log.error("contact_form.is_valid() error({0}): {1}".format(e.errno, e.strerror)) log.error("contact_form.is_valid()") raise try: # Send an email to [email protected] with the user's message send_email(SOCIAL_EMAIL_ADDRESS, subject_type, body, from_email=from_email_address ) except Exception as e: log.error("SOCIAL_EMAIL_ADDRESS error" ) #log.error("SOCIAL_EMAIL_ADDRESS error({0}): {1}".format(e.errno, e.strerror)) raise try: # Also shoot the user who contacted us an email to let them know we'll get back to them soon. send_email(from_email_address, FEEDBACK_SUBMISSION_RESPONSE_SUBJECT, '', FEEDBACK_SUBMISSION_RESPONSE_TEMPLATE, ) except Exception as e: log.error("from_email_address error") #log.error("from_email_address error({0}): {1}".format(e.errno, e.strerror)) raise # Notice that we always return True. If the email failed to send, we need to figure it out on our side. # There is nothing additional for the client to do. return ajax_popup_notification('success','We got your message! ' 'Someone should respond to you within 24 hours.', 200) # If the user ignored out javascript validation and sent an invalid form, send back an error. # We don't actually specify what the form error was. This is okay because our app requires JS to be enabled. # If the user managed to send us an aysynch request with JS disabled, they aren't using the site as designed. # eg., possibly a malicious user. No need to repeat the form pretty validation already done on the front end. else: return ajax_http(False) else: contact_form = ContactForm() return render(request, 'contact/contact_form.html', {'contact_form': contact_form, 'form_settings': contact_form_settings, } )
def post(self, request): data = request.POST.copy() item = data.get('item', '') # save the to the session so thankyou page will get it. request.session['item'] = item # check if quantity is sent with the data and it is greater then 0 if data.get('item_quantity') is None and data['item_quantity'] <= 0: return HttpResponse(status=500) # check if payment method is via Paypal and set Cash On Delivery to false if data.get('cash_on_delivery') is None and data.get( 'paypal') == 'true': data['cash_on_delivery'] = False # check if payment method is via Cash On Delivery and set Paypal to false if data.get('paypal') is None and data.get( 'cash_on_delivery') == 'true': data['paypal'] = False if data.get('paybal') is None and data.get('cash_on_delivery') is None: return HttpResponse(status=500) # TODO: validate the email using django validation # check if there is email if data.get('email', ''): payment_method = '' # check type of payment method and set it's value for the email # checking 'true' is bugging me though if data['paypal'] == 'true': payment_method = 'Paypal' if data['cash_on_delivery'] == 'true': payment_method = 'Cash on Delivery' email_template = 'apparel/email/order_email.html' email_subject = "Fourbags" ctx = { "item": item, "firstname": data.get('first_name', ''), "lastname": data.get('last_name', ''), "phone": data.get('phone', ''), "address": data.get('address', ''), "quantity": data['item_quantity'], "payment_method": payment_method } to_email = data.get('email') from_email = settings.EMAIL_HOST_USER if item: # check if that item exists (double checking) try: ordered_item = Item.objects.get(pk=item.get('id', '')) except Item.DoesNotExist: return HttpResponse(status=404) try: # get if the customer exists or create it buyer, created = Customer.objects.get_or_create( first_name=data.get('first_name', ''), last_name=data.get('last_name', ''), phone=data.get('phone', ''), email=data.get('email', ''), address=data.get('address', ''), ) except MultipleObjectsReturned: # will handle this cases later # but for now just return 500 return HttpResponse(status=404) else: # Finally create order object Order.objects.create(item=ordered_item, buyer=buyer, is_new_buyer=created, quantity=data['item_quantity'], paypal=data['paypal'], cash_on_delivery=data['cash_on_delivery']) # send the mail send_email(email_subject, email_template, ctx, to_email, from_email) return JsonResponse({"success": True})
def test_email(email_to, email_from, subject, body): send_email(email_to, email_from, subject, body)
def send_email_test(request): send_email("*****@*****.**", send_type=1) return render(request, "account/send_success.html")