def main(): import time import datetime from django.conf import settings from common import utils from www.weixin.interface import WexinBase from www.tasks import async_send_email from pprint import pprint wb = WexinBase() app_key = "cheka_test" to_user = '******' app_key = "cheka" to_user = '******' content = (u'古人云:鸟随鸾凤飞腾远,人伴贤良品质高。\n') # print wb.send_msg_to_weixin(content, to_user, app_key) context = { 'reset_url': '%s/reset_password?code=%s' % (settings.MAIN_DOMAIN, "123"), } print async_send_email( "*****@*****.**", u'来自车咖', utils.render_email_template('email/reset_password.html', context), 'html')
def send_forget_password_email(self, email): ''' @note: 发送密码找回邮件 ''' if not email: return 99800, dict_err.get(99800) user = self.get_user_by_email(email) if not user: return 10111, dict_err.get(10111) cache_obj = cache.Cache() key = u'forget_password_email_code_%s' % email code = cache_obj.get(key) if not code: code = utils.uuid_without_dash() cache_obj.set(key, code, time_out=1800) cache_obj.set(code, user, time_out=1800) if not cache_obj.get_time_is_locked(key, 60): context = { 'reset_url': '%s/reset_password?code=%s' % (settings.MAIN_DOMAIN, code), } async_send_email( email, u'智选找回密码', utils.render_email_template('email/reset_password.html', context), 'html') return 0, dict_err.get(0)
def send_recharge_success_notice(self, company, amount, balance, pay_type=1): PAY_TYPE_DICT = {1: u'人工转账', 2: u'支付宝在线支付'} pay_type_str = PAY_TYPE_DICT.get(pay_type, u'人工转账') # 发送邮件提醒 from www.tasks import async_send_email title = u'账户充值成功' content = u'账户「%s」通过「%s」成功充值「%.2f」元,当前余额「%.2f」元。' % (company.name, pay_type_str, amount, balance) async_send_email("*****@*****.**", title, content) # 发送微信提醒 from weixin.interface import WeixinBase for manager in CompanyManagerBase().get_managers_by_company(company.id): to_user_openid = ExternalTokenBase().get_weixin_openid_by_user_id(manager.user_id) if to_user_openid: WeixinBase().send_recharge_success_template_msg( to_user_openid, u"%s,您已成功充值" % company.name, datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), u"%.2f 元" % amount, u"账户余额:%.2f 元" % balance )
def create_invite(self, from_user_id, to_user_id, question_id): try: from www.question.interface import QuestionBase ub = UserBase() try: from_user = ub.get_user_by_id(from_user_id) to_user = ub.get_user_by_id(to_user_id) question = QuestionBase().get_question_by_id(question_id) assert from_user and to_user and question except: transaction.rollback(using=DEFAULT_DB) return 99800, dict_err.get(99800) if from_user_id == to_user_id: transaction.rollback(using=DEFAULT_DB) return 40100, dict_err.get(40100) # 同一个问题最多邀请6个人 if InviteAnswerIndex.objects.filter(from_user_id=from_user_id, question_id=question_id).count() >= 6: transaction.rollback(using=DEFAULT_DB) return 40101, dict_err.get(40101) # 重复邀请给出提示 if InviteAnswerIndex.objects.filter(from_user_id=from_user_id, to_user_id=to_user_id, question_id=question_id): transaction.rollback(using=DEFAULT_DB) return 40102, dict_err.get(40102) try: ia = InviteAnswer.objects.create(from_user_ids=json.dumps([from_user_id, ]), to_user_id=to_user_id, question_id=question_id) need_update_unread_count = True except: ia = InviteAnswer.objects.get(to_user_id=to_user_id, question_id=question_id) from_user_ids = json.loads(ia.from_user_ids) if from_user_id not in from_user_ids: from_user_ids.append(from_user_id) ia.from_user_ids = json.dumps(from_user_ids) ia.save() need_update_unread_count = True if ia.is_read else False # 建立索引 InviteAnswerIndex.objects.create(from_user_id=from_user_id, to_user_id=to_user_id, question_id=question_id) # 更新未读消息,新邀请或者邀请已读才更新未读数 if need_update_unread_count: UnreadCountBase().update_unread_count(to_user_id, code='invite_answer') # 发送提醒邮件 context = dict(user=from_user, question=question) async_send_email(to_user.email, u'%s 在智选邀请你回答问题' % (from_user.nick, ), utils.render_email_template('email/invite.html', context), 'html') transaction.commit(using=DEFAULT_DB) return 0, dict_err.get(0) except Exception, e: debug.get_debug_detail(e) transaction.rollback(using=DEFAULT_DB) return 99900, dict_err.get(99900)
def get_debug_detail_and_send_email(e): from www.tasks import async_send_email debug_detail = get_debug_detail(e) if isinstance(debug_detail, (list, tuple)): debug_detail = str(debug_detail) logging.error(debug_detail) async_send_email(settings.NOTIFICATION_EMAIL, u"%s%sworker error" % (settings.SERVER_NAME, str(datetime.datetime.now())), debug_detail, content_type="text")
def get_debug_detail_and_send_email(e): from www.tasks import async_send_email debug_detail = get_debug_detail(e) if isinstance(debug_detail, (list, tuple)): debug_detail = str(debug_detail) debug_detail = u"%s\n%s" % (str(datetime.datetime.now()), debug_detail) async_send_email(settings.NOTIFICATION_EMAIL, u"%s direct error" % (settings.SERVER_NAME, ), debug_detail, type="text")
def process_exception(self, request, exception): if type(exception) == Http404: return title = u'%s error in %s' % (settings.SERVER_NAME, request.get_full_path()) content = debug.get_debug_detail(exception) if settings.SERVER_NAME != 'DEVELOPER': from www.tasks import async_send_email async_send_email(settings.NOTIFICATION_EMAIL, title, content)
def weixinwarning(request): """ @note: 微信支付告警通知接口, 微信监测到商户服务出现问题时,会及时推送相关告警信息到商户后台 """ from django.conf import settings from www.tasks import async_send_email if request.GET or request.POST: title = u'微信支付告警通知' content = u'告警内容如下:\n%s' % request.REQUEST async_send_email(settings.NOTIFICATION_EMAIL, title, content) return HttpResponse("ok")
def send_weekly_email(): questions = get_all_important_question() if questions: context = dict(questions=questions) for user in User.objects.filter(state__gt=0): email = user.email context.update(dict(email=email)) async_send_email(email, u'智选每周精选', utils.render_email_template('email/important.html', context), 'html') # email = ["*****@*****.**", "*****@*****.**", "*****@*****.**"] # async_send_email(email, u'智选每周精选', utils.render_email_template('email/important.html', context), 'html') print 'ok'
def add_system_message(self, user_id, content, source=0, send_email=False): user = UserBase().get_user_by_id(user_id) if not user: return notice = Notice.objects.create(user_id=user_id, content=content, source=source) UnreadCountBase().update_unread_count(user_id, code='system_message') if send_email: # 发送提醒邮件 context = dict(user=user, content=content) async_send_email(user.email, u'智选系统通知', utils.render_email_template('email/common_msg.html', context), 'html') return notice
def send_confirm_email(self, user): ''' @note: 发送验证邮件 ''' cache_obj = cache.Cache() key = u'confirm_email_code_%s' % user.id code = cache_obj.get(key) if not code: code = utils.uuid_without_dash() cache_obj.set(key, code, time_out=1800) if not cache_obj.get_time_is_locked(key, 60): context = {'verify_url': '%s/account/user_settings/verify_email?code=%s' % (settings.MAIN_DOMAIN, code), } async_send_email(user.email, u'且行户外邮箱验证', utils.render_email_template('email/verify_email.html', context), 'html')
def send_weekly_email(): questions = get_all_important_question() if questions: context = dict(questions=questions) for user in User.objects.filter(state__gt=0): email = user.email context.update(dict(email=email)) async_send_email( email, u'智选每周精选', utils.render_email_template('email/important.html', context), 'html') # email = ["*****@*****.**", "*****@*****.**", "*****@*****.**"] # async_send_email(email, u'智选每周精选', utils.render_email_template('email/important.html', context), 'html') print 'ok'
def sell_car(self, user_used_car_id, mobile): obj = UserUsedCar.objects.filter(id=user_used_car_id) if obj: obj = obj[0] try: obj.mobile = mobile obj.save() from www.tasks import async_send_email title = u"生意来了,有人要卖车" content = u"手机用户 [ %s ] 要卖 [ %s - %s ], 新车价[ %s 万], 估价[ %s 万] " % (mobile, obj.car.serial.name, obj.car.name, obj.car.original_price, obj.price) async_send_email(["*****@*****.**", "*****@*****.**"], title, content) except Exception, e: debug.get_debug_detail(e) return 99900, dict_err.get(99900)
def send_balance_insufficient_notice(self, company, balance, max_overdraft): # 发送邮件提醒 from www.tasks import async_send_email title = u'账户已达最高透支额' content = u'账户「%s」当前余额「%.2f」元,已达「%.2f」元最高透支额,请联系充值' % (company.name, balance, max_overdraft) async_send_email("*****@*****.**", title, content) # 发送微信提醒 from weixin.interface import WeixinBase for manager in CompanyManagerBase().get_managers_by_company(company.id): to_user_openid = ExternalTokenBase().get_weixin_openid_by_user_id(manager.user_id) if to_user_openid: WeixinBase().send_balance_insufficient_template_msg( to_user_openid, u"账户已达「%.2f」元最高透支额,请联系充值" % max_overdraft, company.name, u"%.2f 元" % balance, u"感谢您的支持,祝工作愉快" )
def sell_car(self, user_used_car_id, mobile): obj = UserUsedCar.objects.filter(id=user_used_car_id) if obj: obj = obj[0] try: obj.mobile = mobile obj.save() from www.tasks import async_send_email title = u"生意来了,有人要卖车" content = u"手机用户 [ %s ] 要卖 [ %s - %s ], 新车价[ %s 万], 估价[ %s 万] " % ( mobile, obj.car.serial.name, obj.car.name, obj.car.original_price, obj.price) async_send_email(["*****@*****.**", "*****@*****.**"], title, content) except Exception, e: debug.get_debug_detail(e) return 99900, dict_err.get(99900)
def main(): import time import datetime from django.conf import settings from common import utils from www.weixin.interface import WexinBase from www.tasks import async_send_email from pprint import pprint wb = WexinBase() app_key = "cheka_test" to_user = '******' app_key = "cheka" to_user = '******' content = (u'古人云:鸟随鸾凤飞腾远,人伴贤良品质高。\n') # print wb.send_msg_to_weixin(content, to_user, app_key) context = {'reset_url': '%s/reset_password?code=%s' % (settings.MAIN_DOMAIN, "123"), } print async_send_email("*****@*****.**", u'来自车咖', utils.render_email_template('email/reset_password.html', context), 'html')
def send_forget_password_email(self, email): ''' @note: 发送密码找回邮件 ''' if not email: return 99800, dict_err.get(99800) user = self.get_user_by_email(email) if not user: return 10111, dict_err.get(10111) cache_obj = cache.Cache() key = u'forget_password_email_code_%s' % email code = cache_obj.get(key) if not code: code = utils.uuid_without_dash() cache_obj.set(key, code, time_out=1800) cache_obj.set(code, user, time_out=1800) if not cache_obj.get_time_is_locked(key, 60): context = {'reset_url': '%s/reset_password?code=%s' % (settings.MAIN_DOMAIN, code), } async_send_email(email, u'且行户外找回密码', utils.render_email_template('email/reset_password.html', context), 'html') return 0, dict_err.get(0)
def alipaynotify(request): """ @note: 支付宝手机支付通知,服务器通知方式 """ logging.error(u"alipaynotify info is: %s" % request.REQUEST) result = 'fail' flag = alipay_pc.sign_verify(request.POST) and alipay_pc.notify_verify(request.POST) # logging.error(u"flag ======> %s" % flag) if flag: params = request.POST # 验证支付宝发来的交易状态 if params.get('trade_status') in ('TRADE_FINISHED', 'TRADE_SUCCESS'): buyer_email = params.get('buyer_email') buyer_id = params.get('buyer_id') trade_no = params.get('trade_no') trade_id = params.get('out_trade_no') total_fee = params.get('total_fee') pay_info = 'trade_no:%s, buyer_email:%s, buyer_id:%s' % (trade_no, buyer_email, buyer_id) errcode, errmsg = RechargeOrderBase().order_pay_callback(trade_id=trade_id, payed_fee=total_fee, pay_info=pay_info) # 不存在的订单返回成功防止一直补发 result = u'success' if errcode in (0, 21301, 21302) else 'fail' # logging.error(u"errcode, errmsg, result ======> %s,%s,%s" % (errcode, errmsg, result)) if result != u"success": async_send_email( settings.NOTIFICATION_VIP_EMAIL, u"在线支付失败", u"errcode==>%s \n errmsg==>%s \n result==>%s \n trade_id==>%s \n total_fee==>%s \n pay_info==>%s \n" % ( errcode, errmsg, result, trade_id, total_fee, pay_info) ) return HttpResponse(result)
def create_answer(self, question, from_user_id, content, ip=None): try: content = utils.filter_script(content) if not all((question, from_user_id, content)): transaction.rollback(using=QUESTION_DB) return 99800, dict_err.get(99800) errcode, errmsg = QuestionBase().validate_content(content) if not errcode == 0: transaction.rollback(using=QUESTION_DB) return errcode, errmsg to_user_id = question.user_id answer = Answer.objects.create(from_user_id=from_user_id, to_user_id=to_user_id, content=content, question=question, ip=ip) from_user = UserBase().get_user_by_id(from_user_id) # 添加at信息 if content.find('@') != -1: at_usernicks = utils.select_at(content) for nick in at_usernicks: at_user = UserBase().get_user_by_nick(nick) if at_user: # 自己@自己的关系不进行存储 if at_user.id != from_user_id: AtAnswer.objects.create(answer=answer, user_id=at_user.id) if at_user.id != to_user_id: # 更新@未读消息数 UnreadCountBase().update_unread_count( at_user.id, code='at_answer') # 发送提醒邮件 context = dict(user=from_user, answer=answer) async_send_email( at_user.email, u'%s 在智选回答中@了你' % (from_user.nick, ), utils.render_email_template( 'email/at.html', context), 'html') # 更新未读消息 if from_user_id != to_user_id: UnreadCountBase().update_unread_count(to_user_id, code='received_answer') # 发送提醒邮件 to_user = UserBase().get_user_by_id(to_user_id) context = dict(user=from_user, answer=answer) async_send_email( to_user.email, u'%s 在智选回答了你的提问' % (from_user.nick, ), utils.render_email_template('email/answer.html', context), 'html') # 更新用户回答统计总数 UserCountBase().update_user_count(user_id=from_user_id, code='user_answer_count') # 更新回答数冗余信息 question.answer_count += 1 question.last_answer_time = datetime.datetime.now() question.save() # 发送feed if not question.is_silence: FeedBase().create_feed(from_user_id, feed_type=3, obj_id=answer.id) # 更新summary QuestionBase().get_question_summary_by_id(question, must_update_cache=True) transaction.commit(using=QUESTION_DB) return 0, answer except Exception, e: debug.get_debug_detail(e) transaction.rollback(using=QUESTION_DB) return 99900, dict_err.get(99900)
def get_prepay_id(self, body, out_trade_no, total_fee, openid, attach="", trade_type="JSAPI", ip="121.42.48.184", notify_url=None): """ @note: total_fee单位为分,不能带小数点 """ url = "%s/pay/unifiedorder" % WEIXINPAY_URL notify_url = notify_url or ("%s/weixinnotify" % MAIN_DOMAIN) params = dict(appid=self.appid, mch_id=self.mch_id, nonce_str=utils.uuid_without_dash(), body=body, attach=attach, out_trade_no=out_trade_no, total_fee=total_fee, spbill_create_ip=ip, notify_url=notify_url, trade_type=trade_type, openid=openid) params, prestr = self.format_params(params) sign = self.build_mysign(prestr) params["sign"] = sign xml = """ <xml> <appid>%(appid)s</appid> <attach><![CDATA[%(attach)s]]></attach> <body><![CDATA[%(body)s]]></body> <mch_id>%(mch_id)s</mch_id> <nonce_str>%(nonce_str)s</nonce_str> <notify_url>%(notify_url)s</notify_url> <out_trade_no>%(out_trade_no)s</out_trade_no> <spbill_create_ip>%(spbill_create_ip)s</spbill_create_ip> <total_fee>%(total_fee)s</total_fee> <trade_type>%(trade_type)s</trade_type> <openid><![CDATA[%(openid)s]]></openid> <sign><![CDATA[%(sign)s]]></sign> </xml> """ % params try: resp = requests.post(url=url, data=xml, timeout=30, verify=False) resp.encoding = "utf-8" text = resp.text # text = """ # <xml><return_code><![CDATA[SUCCESS]]></return_code> # <return_msg><![CDATA[OK]]></return_msg> # <appid><![CDATA[wx23cca542b396c669]]></appid> # <mch_id><![CDATA[1224504302]]></mch_id> # <nonce_str><![CDATA[YGJzdXq7hggzwGVx]]></nonce_str> # <sign><![CDATA[08AC09CF26D2820E833F857E61DE4B62]]></sign> # <result_code><![CDATA[SUCCESS]]></result_code> # <prepay_id><![CDATA[wx2014121518153157cbc1f6af0195338906]]></prepay_id> # <trade_type><![CDATA[JSAPI]]></trade_type> # </xml> # """ text = smart_str(text) if "prepay_id" in text: jq = pq(text) prepay_id = jq('prepay_id').html() self.prepay_id = prepay_id return True, prepay_id else: from www.tasks import async_send_email from django.conf import settings from django.utils.encoding import smart_unicode logging.error(u"get_prepay_id fail, info is:%s" % text) logging.error(u"get_prepay_id fail, params is:%s" % smart_unicode(xml)) title = u'%s 生成微信支付链接错误' % settings.SERVER_NAME content = u'params:%s\n\nreturn info:%s' % (smart_unicode(xml), text) async_send_email(settings.NOTIFICATION_EMAIL, title, content) return False, text except Exception, e: debug.get_debug_detail_and_send_email(e) return False, e
send_mail(title, content, settings.EMAIL_FROM, emails, fail_silently=True) else: msg = EmailMessage(title, content, settings.EMAIL_FROM, emails) msg.content_subtype = "html" # Main content is now text/html msg.send() return 0 def send_email_to_me(title, content, type='html', async=True): from django.conf import settings from www.tasks import async_send_email if async: async_send_email.delay(settings.MY_EMAIL, title, content, type=type) else: async_send_email(settings.MY_EMAIL, title, content, type=type) def get_clientip(request): if 'HTTP_X_FORWARDED_FOR' in request.META: client_ip = request.META['HTTP_X_FORWARDED_FOR'] arr_ip = client_ip.split(',', 1) return arr_ip[0].strip() elif 'HTTP_X_REAL_IP' in request.META: return request.META['HTTP_X_REAL_IP'] else: return request.META.get('REMOTE_ADDR', u'127.0.0.1') def time_format(value): import time