def get(self): result = Bond.query.all() name = uuid.uuid1().__str__() + ".csv" html = "<table>" with open(name, "w") as fd: fd.write("债券名称,债券描述,发行规模(亿),票面利率,债券类型,发行日期,到期日期\n") html += "<tr><th>SECUABBR</th><th>CHINAME</th><th>ISSUESIZE</th><th>COUPONRATE</th><th>SECUCATEGORY</th><th>LISTINGDATE</th><th>DELISTINGDATE</th></tr>" for row in result: fd.write('{},{},{},{},{},{},{}\n'.format( row.SECUABBR, row.CHINAME, row.ISSUESIZE, row.COUPONRATE, row.SECUCATEGORY, row.LISTINGDATE, row.DELISTINGDATE)) html += "<tr><th>{}</th><th>{}</th><th>{}</th><th>{}</th><th>{}</th><th>{}</th><th>{}</th></tr>".format( row.SECUABBR, row.CHINAME, row.ISSUESIZE, row.COUPONRATE, row.SECUCATEGORY, row.LISTINGDATE, row.DELISTINGDATE) html += "</table>" # 发送邮件 try: send_html_mail( "*****@*****.**", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "债券数据", html) except Exception as e: print("Cannot send mail: ", e.with_traceback()) response = make_response(send_file(name, as_attachment=True)) response.headers[ "content-disposition"] = "attachment; filename=" + time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime()) + ".csv" return response
def contact_us_modal_submit(request): ret = {"success":True} if request.POST.get("send_by_js") != 'true': ret['success'] = False return HttpResponse(json.dumps(ret)) fullname = request.POST.get("fullname_modal") email = request.POST.get("email_modal") state = request.POST.get("state_modal") district = request.POST.get("district_modal") from django.core.mail import send_mail from mitxmako.shortcuts import render_to_response, render_to_string from smtplib import SMTPException from mail import send_html_mail d = {"email":email, "fullname":fullname, "state":state, "district":district} subject = "PepperPd Contact Us From " + request.META['HTTP_HOST'] body = render_to_string('emails/contact_us_modal_body.txt', d) # todo: catch SMTPAuthenticationError and SMTPException send_html_mail(subject, body, settings.SUPPORT_EMAIL, [ settings.SUPPORT_EMAIL, "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**" ]) return HttpResponse(json.dumps(ret))
def do_import_adjustment_time(task, csv_lines, request): gevent.sleep(0) count_success = 0 rts = record_time_store() for i, line in enumerate(csv_lines): tasklog = ImportTaskLog() tasklog.create_date = datetime.now(UTC) tasklog.line = i + 1 tasklog.task = task tasklog.import_data = line try: task.process_lines = i + 1 validate_adjustment_time_cvs_line(line, tasklog) email = line[ADJUSTMENT_TIME_CSV_COLS.index('email')] adjustment_time = int(line[ADJUSTMENT_TIME_CSV_COLS.index('time')]) * 60 adjustment_type = line[ADJUSTMENT_TIME_CSV_COLS.index('type')] course_number = line[ADJUSTMENT_TIME_CSV_COLS.index('course_number')] try: comments = line[ADJUSTMENT_TIME_CSV_COLS.index('comments')] except: comments = '' user_id = str(User.objects.get(email=email).id) course_id = str(get_course_id(course_number)) success = validate_adjustment_time(rts, user_id, adjustment_type, adjustment_time, course_id) if success: rts.set_adjustment_time(user_id, adjustment_type, adjustment_time, course_id) save_adjustment_log(request, user_id, adjustment_type, adjustment_time, course_number, comments) tasklog.error = 'ok' except Exception as e: tasklog.error = "%s" % e log.debug("import error %s" % e) finally: count_success += 1 task.success_lines = count_success task.update_time = datetime.now(UTC) task.save() tasklog.save() tasklogs = ImportTaskLog.objects.filter(task=task).exclude(error='ok') if len(tasklogs): FIELDS = ["line", "username", "import_data", "create_date", "error"] TITLES = ["Line", "Useremail", "Import Data", "Create Date", "Error"] output = StringIO() writer = csv.DictWriter(output, fieldnames=FIELDS) writer.writerow(dict(zip(FIELDS, TITLES))) for d in tasklogs: row = {"line": d.line, "username": d.username, "import_data": d.import_data, "create_date": d.create_date, "error": d.error } writer.writerow(row) output.seek(0) attach = [{'filename': 'log.csv', 'mimetype': 'text/csv', 'data': output.read()}] send_html_mail("Adjustment Time Import Report", "Report of importing %s, see attachment." % task.filename, settings.SUPPORT_EMAIL, [request.user.email], attach) output.close()
def send_invite_email(request): try: data,filtered=filter_user(request) data=data.filter(subscription_status='Imported') remain=request.GET.get('remain') count=request.GET.get('count') wait=data[:int(count)] for item in wait: reg = Registration.objects.get(user_id=item.user_id) d = {'name': "%s %s" % (item.user.first_name,item.user.last_name), 'key': reg.activation_key,'district': item.district.name} subject = render_to_string('emails/activation_email_subject.txt', d) subject = ''.join(subject.splitlines()) message = render_to_string('emails/activation_email.txt', d) try: send_html_mail(subject, message, settings.SUPPORT_EMAIL, [item.user.email]) except Exception as e: # log.warning('unable to send reactivation email', exc_info=true) raise Exception('unable to send reactivation email: %s' % e) item.subscription_status='Unregistered' item.invite_date=datetime.datetime.now(UTC) item.save() db.transaction.commit() ret={"success":True,"sent":len(wait),"remain":data.count()} except Exception as e: ret={"success":False,"error":"%s" % e} return HttpResponse(json.dumps(ret))
def email_user(self, subject, message, from_email=None): """ Sends an email to this User. """ send_html_mail(subject, message, from_email, [self.email])