def post(self): """Serve the form page. """ logging.info('PaypalIpnHandler.POST') logging.info('headers: %s', self.request.headers.items()) logging.info('params: %s', self.request.params.items()) # First check with Paypal to see if this notification is legit validation_url = config.PAYPAL_IPN_VALIDATION_URL % (self.request.body,) http = httplib2.Http() resp, body = http.request(validation_url, method='POST') if resp.status != 200 or body != 'VERIFIED': # NOT LEGIT logging.warning('invalid IPN request') logging.warning('%d; %s', resp.status, body) webapp2.abort(403) # Check if this actually represents a payment if self.request.params.get('payment_status') != 'Completed': # Not a completed payment, but some intermediate event. We don't # do anything with these. logging.info('IPN with status: %s', self.request.params.get('payment_status')) return # 200 # Check if the payment values are valid if not self._paypal_txn_values_okay(): # Alert our admins about this subject = 'ALERT: bad values in PayPal transaction' body = ''' We received a valid PayPal IPN transaction that contained incorrect or unexpected values. Specifically, either the recipient email address doesn't match ours (should be: %s), the value of the transaction was insufficient (should be: %s), or it was in an incorrect currency (should be: %s). Here are the transaction values: %s Current URL: %s [This email was sent automatically.] ''' % (config.PAYPAL_TXN_receiver_email, config.PAYPAL_TXN_mc_gross_FLOAT, config.PAYPAL_TXN_mc_currency_SET, pprint.pformat(self.request.params.items()), self.request.host_url) mail.send_mail_to_admins(config.MASTER_EMAIL_SEND_ADDRESS, subject, body) logging.info('IPN had bad values') return # 200 # Launch a task to actually create or renew the member. # We'll pass the Paypal params straight through. taskqueue.add(url='/self-serve/process-member-worker', params=self.request.params)
def get(self): gifts = MivakoGift.query(MivakoGift.emailed == False).fetch() if not gifts: return template = u"Отправитель: %s\nИмя получателя: %s\nТелефон получателя: %s\nПодарок: %s" messages = [] for g in gifts: messages.append( template % (g.sender, g.recipient_name, g.recipient, g.gift_item)) mail_body = "\n\n".join(messages) logging.info(mail_body) mail.send_mail_to_admins(_MAIL_SENDER, _MAIL_SUBJECT, mail_body) try: mail.send_mail(_MAIL_SENDER, _MAIL_RECIPIENTS, _MAIL_SUBJECT, mail_body) except Exception as e: logging.exception(e) mail.send_mail_to_admins(_MAIL_SENDER, u"Ошибка отправки подарков в Мивако", e.message) else: for g in gifts: g.emailed = True g.put()
def handle_exception(self, exception, debug_mode): error_message = [] subject = 'Caught Exception for ' + os.environ['APPLICATION_ID'] + ': v' + os.environ['CURRENT_VERSION_ID'] error_message.append(subject) error_message.append(str(exception)) lines = ''.join(traceback.format_exception(*sys.exc_info())) error_message.append(lines) env = [] for k, v in os.environ.iteritems(): env.append(str(k) + " : " + str(v)) env = "\n".join(env) error_message.append(env) body = "\n------\n".join(error_message) logging.error(body) mail.send_mail_to_admins(sender="Snippets <" + settings.SITE_EMAIL + ">", subject=subject, body=body) template_values = {} if users.is_current_user_admin() or os.environ['SERVER_SOFTWARE'] == 'Development/1.0': template_values['traceback'] = body self.response.out.write(render_to_string('error.html', template_values))
def notify(self,comment): sbody=self.sbody.decode('utf-8') bbody=self.bbody.decode('utf-8') if self.blog.comment_notify_mail and self.blog.owner and not users.is_current_user_admin() : sbody=sbody%{'title':comment.entry.title, 'author':comment.author, 'weburl':comment.weburl, 'email':comment.email, 'content':comment.content, 'commenturl':comment.entry.fullurl+"#comment-"+str(comment.key().id()) } mail.send_mail_to_admins(self.blog.owner.email(),'Comments:'+comment.entry.title, sbody,reply_to=comment.email) #reply comment mail notify refers = re.findall(r'#comment-(\d+)', comment.content) if len(refers)!=0: replyIDs=[int(a) for a in refers] commentlist=comment.entry.comments() emaillist=[c.email for c in commentlist if c.reply_notify_mail and c.key().id() in replyIDs] emaillist = {}.fromkeys(emaillist).keys() for refer in emaillist: if self.blog.owner and mail.is_email_valid(refer): emailbody = bbody%{'title':comment.entry.title, 'author':comment.author, 'weburl':comment.weburl, 'email':comment.email, 'content':comment.content, 'commenturl':comment.entry.fullurl+"#comment-"+str(comment.key().id()) } message = mail.EmailMessage(sender = self.blog.owner.email(),subject = 'Comments:'+comment.entry.title) message.to = refer message.body = emailbody message.send()
def sendmail(self, email, address, postcode): mail.send_mail_to_admins( sender="The Website<*****@*****.**>", subject="A request for pool maintenance", body="""email: %s address: %s postcode: %s""" % (email, address, postcode))
def handle_exception(self, exception, debug_mode): exception_name = sys.exc_info()[0].__name__ exception_details = str(sys.exc_info()[1]) exception_traceback = ''.join(traceback.format_exception(*sys.exc_info())) logging.error(exception_traceback) exception_expiration = 600 # seconds mail_admin = "*****@*****.**" # must be an admin sitename = "isabella" throttle_name = 'exception-'+exception_name throttle = memcache.get(throttle_name) if throttle is None: memcache.add(throttle_name, 1, exception_expiration) subject = '[%s] exception [%s: %s]' % (sitename, exception_name, exception_details) mail.send_mail_to_admins(sender=mail_admin, subject=subject, body=exception_traceback) values = {} template_name = 'error.html' if users.is_current_user_admin(): values['traceback'] = exception_traceback #values['traceback'] = exception_traceback directory = os.path.dirname(os.environ['PATH_TRANSLATED']) path = os.path.join(directory, os.path.join('templates', template_name)) self.response.out.write(template.render(path, values, debug=_DEBUG))
def send_exception_report(): if not config.DEBUG and config.JOB_EMAIL_RECIPIENT: to = config.JOB_EMAIL_RECIPIENT subject = "[Exception] {0}".format(traceback.format_exception_only(*sys.exc_info()[:2])[0].split(":")[0]) stacktrace = "".join(traceback.format_exception(*sys.exc_info())) body = "\n\n".join((stacktrace, pprint.pformat(dict(**os.environ)))) mail.send_mail_to_admins(to, subject, body[:EMAIL_TRIM_SIZE])
def save(self): self.put() self.entry.commentcount+=1 self.entry.put() memcache.delete("/"+self.entry.link) sbody=_('''New comment on your post "%s" Author : %s E-mail : %s URL : %s Comment: %s You can see all comments on this post here: %s ''') sbody=sbody.decode('utf-8') logging.info(type( sbody)) logging.info(sbody) if g_blog.comment_notify_mail and g_blog.owner and not users.is_current_user_admin() : sbody=sbody%(self.entry.title,self.author,self.email,self.weburl,self.content, g_blog.baseurl+"/"+self.entry.link+"#comment-"+str(self.key().id())) mail.send_mail_to_admins(g_blog.owner.email(),'Comments:'+self.entry.title, sbody,reply_to=self.email) logging.info('send %s . entry: %s'%(g_blog.owner.email(),self.entry.title))
def send_error_to_admins(exception, handler, write_tmpl): import settings # workaround. See https://github.com/renzon/zenwarch/issues/3 tb = traceback.format_exc() errmsg = exception.message logging.error(errmsg) logging.error(tb) write_tmpl("/templates/error.html") appid = app_identity.get_application_id() subject = 'ERROR in %s: [%s] %s' % (appid, handler.request.path, errmsg) body = """ ------------- request ------------ %s ---------------------------------- ------------- GET params --------- %s ---------------------------------- ----------- POST params ---------- %s ---------------------------------- ----------- traceback ------------ %s ---------------------------------- """ % (handler.request, handler.request.GET, handler.request.POST, tb) body += 'API statuses = ' + json.dumps(get_apis_statuses(exception), indent=4) mail.send_mail_to_admins(sender=settings.SENDER_EMAIL, subject=subject, body=body)
def wrapped(handler): try: resp_body = func(handler) except APIError as e: resp_body = e.value handler.response.set_status(e.status_code) except Exception as e: print traceback.format_exc() resp_body = {"msg": "unknown_server_error"} handler.response.set_status(500) # Inform admins app_name = get_application_id() sender = 'noreply@%s.appspotmail.com' % app_name subject = '%s server error' % app_name.capitalize() body = """ ==== API: %s ==== %s """ % (str(handler.request.route), traceback.format_exc()) mail.send_mail_to_admins(sender, subject, body) handler.response.headers['Content-Type'] = 'application/json' handler.response.write(json.dumps(resp_body))
def send_error_to_admins(settings, exception, handler, render, template): tb = traceback.format_exc() errmsg = exception.message logging.error(errmsg) logging.error(tb) handler.response.write(render(template)) appid = app_identity.get_application_id() subject = 'ERROR in %s: [%s] %s' % (appid, handler.request.path, errmsg) body = """ ------------- request ------------ %s ---------------------------------- ------------- GET params --------- %s ---------------------------------- ----------- POST params ---------- %s ---------------------------------- ----------- traceback ------------ %s ---------------------------------- """ % (handler.request, handler.request.GET, handler.request.POST, tb) body += 'API statuses = ' + json.dumps(get_apis_statuses(exception), indent=4) mail.send_mail_to_admins(sender=settings.SENDER_EMAIL, subject=subject, body=body)
def handle_exception(self, exception, debug_mode): error_message = [] subject = "Caught Exception for " + os.environ["APPLICATION_ID"] + ": v" + os.environ["CURRENT_VERSION_ID"] error_message.append(subject) error_message.append(str(exception)) lines = "".join(traceback.format_exception(*sys.exc_info())) error_message.append(lines) env = [] for k, v in os.environ.iteritems(): env.append(str(k) + " : " + str(v)) env = "\n".join(env) error_message.append(env) body = "\n------\n".join(error_message) logging.error(body) mail.send_mail_to_admins(sender=settings.ADMIN_EMAIL, subject=subject, body=body) template_values = {} if users.is_current_user_admin() or os.environ["SERVER_SOFTWARE"] == "Development/1.0": template_values["traceback"] = body self.response.out.write(render_to_string("error.html", template_values))
def mail_admins(subject, message, fail_silently=False): """Sends a message to the admins, as defined by the ADMINS setting.""" sender_mail = settings.DEFAULT_MAIL_FROM if sender_mail == '*****@*****.**': sender_mail = None if not sender_mail and not settings.ADMINS: # If neither DEFAULT_MAIL_FROM and ADMINS are set # simply do nothing. return if (settings.DEBUG and not sender_mail and (settings.ADMINS or settings.NOTIFY_ERRORS_TO_GAE_ADMINS)): # DEPRECATED 1.1 # This code is deprecated and will be removed in # versions >= 1.5 or 2.0 import logging logging.debug("Deprecation warning. Please set the DEFAULT_MAIL_FROM " "setting in your settings.py. You will need to set the " "DEFAULT_MAIL_FROM setting in order for error mails to " "work properly in future versions of kay.") if settings.NOTIFY_ERRORS_TO_GAE_ADMINS: mail.send_mail_to_admins(sender=sender_mail or settings.ADMINS[0][1], subject=subject, body=message) for admin in settings.ADMINS: mail.send_mail(sender=sender_mail or admin[1], to=admin[1], subject=subject, body=message)
def report_all_surveys(requestedBrand, emailRecipient): try: today = datetime.date.today() ioCsvOuput = utils.generate_survey_csv(requestedBrand) """ # [ST] Pre Py2.7 Upgrade mailProps = configparsers.loadPropertyFile('mail') message = mail.EmailMessage() message.sender = mailProps.get('NewSurvey', 'sender') message.to = emailRecipient message.subject = mailProps.get('NewSurvey', 'subject_report') message.body='New report' message.attachments=[(str(os.environ['HTTP_HOST'])+'-'+str(today.isoformat())+'.csv', ioCsvOuput.getvalue())] message.send() """ # [ST] Post Py2.7 Upgrade mailProps = configparsers.loadPropertyFile('mail') mail.send_mail_to_admins( sender=mailProps.get('NewSurvey', 'sender'), subject=mailProps.get('NewSurvey', 'subject_report'), body='New report', **dict( attachments=[(str(os.environ['HTTP_HOST'])+'-'+str(today.isoformat())+'.csv', ioCsvOuput.getvalue())] ) ) except (Exception, apiproxy_errors.ApplicationError, apiproxy_errors.OverQuotaError), e: logging.error(e) logging.error('report_all_surveys() : mail could not be sent as the 24-hour quota has been exceeded') raise e
def post(self): try: req = self.request.get('payload') mail_obj = decrypt(req) mail_msg = mail.EmailMessage() for key in ('sender', 'subject', 'to', 'body'): setattr(mail_msg, key, mail_obj[key]) attachments = [(name, base64.b64decode(content)) for name, content in mail_obj['attachments']] if attachments: mail_msg.attachments = attachments except Exception as e: self.response.set_status(400) return try: if not is_development(): mail_msg.send() else: logging.info('Pretending to send mail') except Exception as e: logging.error('Send mail failed: %s', e) mail.send_mail_to_admins( sender='*****@*****.**', subject='Attempt to send email rejected by Google', body= 'An attempt to send email to %s was rejected by Google.\n\nTechnical details:\n%s' % (mail_obj['to'], e)) self.response.set_status(204)
def get(self): """Sends a test email to the admins.""" key = self.request.get('key') if key: question = models.Question.get_by_id(int(key)) else: question = models.Question.get_next() if question and not len(question.errors()): email_body = self.generate_template('email/question.txt', { 'url': get_question_url(self.request.host_url, question.key.id()), 'msg': question.email_msg, 'name': 'Admin' }) subject = ('Friday Film Club: Season %s, Week %d (DRY RUN)' % (question.season.id(), question.week)) else: email_body = self.generate_template('email/dryrun.txt', {'question': question}) subject = 'Friday Film Club (FAILURE)' mail.send_mail_to_admins(settings.FMJ_EMAIL, subject, email_body) self.response.headers['content-type'] = 'text/plain' self.response.out.write(email_body)
def send_error_to_admins(exception, handler, write_tmpl): import settings # workaround. See https://github.com/renzon/zenwarch/issues/3 tb = traceback.format_exc() errmsg = exception.message logging.error(errmsg) logging.error(tb) write_tmpl("/templates/error.html") appid = app_identity.get_application_id() subject = 'ERROR in %s: [%s] %s' % (appid, handler.request.path, errmsg) body = """ ------------- request ------------ %s ---------------------------------- ------------- GET params --------- %s ---------------------------------- ----------- POST params ---------- %s ---------------------------------- ----------- traceback ------------ %s ---------------------------------- """ % (handler.request, handler.request.GET, handler.request.POST, tb) body += 'API statuses = ' + json.dumps(get_apis_statuses(exception), indent=4) mail.send_mail_to_admins(sender=settings.SENDER_EMAIL, subject=subject, body=body)
def notify(self, comment): sbody = self.sbody.decode('utf-8') bbody = self.bbody.decode('utf-8') if self.blog.comment_notify_mail and self.blog.owner and not users.is_current_user_admin( ): sbody = sbody % { 'title': comment.entry.title, 'author': comment.author, 'weburl': comment.weburl, 'email': comment.email, 'content': comment.content, 'commenturl': comment.entry.fullurl + "#comment-" + str(comment.key().id()) } mail.send_mail_to_admins(self.blog.owner.email(), 'Comments:' + comment.entry.title, sbody, reply_to=comment.email) #reply comment mail notify refers = re.findall(r'#comment-(\d+)', comment.content) if len(refers) != 0: replyIDs = [int(a) for a in refers] commentlist = comment.entry.comments() emaillist = [ c.email for c in commentlist if c.reply_notify_mail and c.key().id() in replyIDs ] emaillist = {}.fromkeys(emaillist).keys() for refer in emaillist: if self.blog.owner and mail.is_email_valid(refer): emailbody = bbody % { 'title': comment.entry.title, 'author': comment.author, 'weburl': comment.weburl, 'email': comment.email, 'content': comment.content, 'commenturl': comment.entry.fullurl + "#comment-" + str(comment.key().id()) } message = mail.EmailMessage(sender=self.blog.owner.email(), subject='Comments:' + comment.entry.title) message.to = refer message.body = emailbody message.send()
def get(self): verify_token = self.GET["hub.verify_token"] if verify_token and verify_token == memcache.get("hub_verify_token"): memcache.delete("hub_verify_token") self.write(self.GET["hub.challenge"]) mail.send_mail_to_admins(ADMIN_EMAIL, u"PubSubHubbub请求验证成功", u"验证参数为:\n%s" % dict(self.GET)) else: logging.warning(u"PubSubHubbub请求验证失败,验证参数为:\n%s" % dict(self.GET))
def get(self): verify_token = self.GET['hub.verify_token'] if verify_token and verify_token == memcache.get('hub_verify_token'): memcache.delete('hub_verify_token') self.write(self.GET['hub.challenge']) mail.send_mail_to_admins(ADMIN_EMAIL, 'PubSubHubbub request has been verified.', 'Request parameters are:\n%s' % dict(self.GET)) else: logging.warning('PubSubHubbub request verified failed. Request parameters are:\n%s' % dict(self.GET))
def MailTestResult(user, test_result): src = mail_settings.EMAIL_SOURCE subject = mail_settings.SUBJECT + ' ' + str(user.name) + ' test ' + test_result.flavor #xls_title, xls_attachment = GenerateExcelFile(test_result) mail.send_mail_to_admins( sender=src, subject=subject, body='Only HTML is supported, sorry.', html=report_generator.GetUserReport(user, [test_result]))
def get(self): verify_token = self.GET['hub.verify_token'] if verify_token and verify_token == memcache.get('hub_verify_token'): memcache.delete('hub_verify_token') self.write(self.GET['hub.challenge']) mail.send_mail_to_admins(ADMIN_EMAIL, u'PubSubHubbub请求验证成功', u'验证参数为:\n%s' % dict(self.GET)) else: logging.warning(u'PubSubHubbub请求验证失败,验证参数为:\n%s' % dict(self.GET))
def move_articles_between_categories(from_path, to_path): articles = Article.all().filter('category =', from_path).fetch(100) if not articles: mail.send_mail_to_admins(ADMIN_EMAIL, u'批量更改文章分类成功', u'源分类:%s\n目标分类:%s' % (from_path, to_path)) return for article in articles: article.category = to_path db.put(articles) deferred.defer(move_articles_between_categories, from_path, to_path)
def post(self): """ Post method to SupportSubmissionHandler.""" logging.info('Visiting the SupportSubmissionHandler via post. Good.') mail_admin = '*****@*****.**' # Pull this code out when posting. subject = 'AptAuction -- Support Question for Lane' mail.send_mail_to_admins(sender=mail_admin, subject=subject, body=self.request) self.redirect("/supportthanks")
def post(self): """Serve the form page. """ logging.info('PaypalIpnHandler.POST') logging.info('headers: %s', self.request.headers.items()) logging.info('params: %s', self.request.params.items()) # First check with Paypal to see if this notification is legit validation_url = config.PAYPAL_IPN_VALIDATION_URL % ( self.request.body, ) http = httplib2.Http() resp, body = http.request(validation_url, method='POST') if resp.status != 200 or body != 'VERIFIED': # NOT LEGIT logging.warning('invalid IPN request') logging.warning('%d; %s', resp.status, body) webapp2.abort(403) # Check if this actually represents a payment if self.request.params.get('payment_status') != 'Completed': # Not a completed payment, but some intermediate event. We don't # do anything with these. logging.info('IPN with status: %s', self.request.params.get('payment_status')) return # 200 # Check if the payment values are valid if not self._paypal_txn_values_okay(): # Alert our admins about this subject = 'ALERT: bad values in PayPal transaction' body = ''' We received a valid PayPal IPN transaction that contained incorrect or unexpected values. Specifically, either the recipient email address doesn't match ours (should be: %s), the value of the transaction was insufficient (should be: %s), or it was in an incorrect currency (should be: %s). Here are the transaction values: %s Current URL: %s [This email was sent automatically.] ''' % (config.PAYPAL_TXN_receiver_email, config.PAYPAL_TXN_mc_gross_FLOAT, config.PAYPAL_TXN_mc_currency_SET, pprint.pformat(self.request.params.items()), self.request.host_url) mail.send_mail_to_admins(config.MASTER_EMAIL_SEND_ADDRESS, subject, body) logging.info('IPN had bad values') return # 200 # Launch a task to actually create or renew the member. # We'll pass the Paypal params straight through. taskqueue.add(url='/self-serve/process-member-worker', params=self.request.params)
def get(self): verify_token = self.GET['hub.verify_token'] if verify_token and verify_token == memcache.get('hub_verify_token'): memcache.delete('hub_verify_token') self.write(self.GET['hub.challenge']) mail.send_mail_to_admins(ADMIN_EMAIL, u'PubSubHubbub请求验证成功', u'验证参数为:\n%s' % dict(self.GET)) else: logging.warning(u'PubSubHubbub请求验证失败,验证参数为:\n%s' % dict(self.GET))
def MailTestResult(user, test_result): src = mail_settings.EMAIL_SOURCE subject = mail_settings.SUBJECT + ' ' + str( user.name) + ' test ' + test_result.flavor #xls_title, xls_attachment = GenerateExcelFile(test_result) mail.send_mail_to_admins(sender=src, subject=subject, body='Only HTML is supported, sorry.', html=report_generator.GetUserReport( user, [test_result]))
def move_articles_between_categories(from_path, to_path): articles = Article.all().filter('category =', from_path).fetch(100) if not articles: mail.send_mail_to_admins(ADMIN_EMAIL, u'批量更改文章分类成功', u'源分类:%s\n目标分类:%s' % (from_path, to_path)) return for article in articles: article.category = to_path db.put(articles) deferred.defer(move_articles_between_categories, from_path, to_path)
def move_articles_between_categories(from_path, to_path): articles = Article.all().filter('category =', from_path).fetch(100) if not articles: memcache_client.delete_multi_async(['get_articles_in_category:' + Category.path_to_name(from_path), 'get_articles_in_category:' + Category.path_to_name(to_path)]) mail.send_mail_to_admins(ADMIN_EMAIL, "Batch change articles' category successful.", u'Source category: %s\nobject category: %s' % (from_path, to_path)) return for article in articles: article.category = to_path db.put(articles) deferred.defer(move_articles_between_categories, from_path, to_path)
def get(self): self.set_content_type('atom') feed = Feed.all().order('-time').get() if feed: self.write(feed.content.encode('utf-8')) if 'Feedfetcher-Google' in self.request.user_agent: url = u'%s%sgenerate_feed?cursor=%s' % (self.request.host_url, BLOG_ADMIN_RELATIVE_PATH, feed.cursor) mail.send_mail_to_admins(ADMIN_EMAIL, u'Feedfetcher-Google已抓取feed', u'确认Google Reader已收录后,可点此链接继续生成后续feed:\n' + url, html=u'确认Google Reader已收录后,可点此<a href="%s">链接</a>继续生成后续feed。' % url)
def _send(self, request): host = request.host splited = host.split('.') email = u'attention@' + splited[0] + u'.appspotmail.com' mail.send_mail_to_admins( sender=email, subject=request.get('subject'), body=u'件名のエラーが発生しました。', )
def update_articles_replies(cursor=None): query = query_with_cursor(Article.all(), cursor) articles = query.fetch(100) if articles: for article in articles: article.replies = Comment.all().ancestor(article).count(None) db.put(articles) if len(articles) < 100: mail.send_mail_to_admins(ADMIN_EMAIL, u'文章评论数更新完成', u'您可以去检查看看了') else: deferred.defer(update_articles_replies, query.cursor())
def delete_category(path): articles = Article.all().filter('category =', path).fetch(100) if not articles: db.delete(db.Key.from_path('Category', Category.path_to_name(path))) clear_categories_memcache() mail.send_mail_to_admins(ADMIN_EMAIL, u'删除分类成功', u'分类路径:' + path) return for article in articles: article.category = None db.put(articles) deferred.defer(delete_category, path)
def _send_mail_to_admins(sender, subject, body): try: mail.send_mail_to_admins( sender=sender, subject=subject, body=body, ) return True except apiproxy_errors.OverQuotaError, message: logging.error(message) return False
def tasks(cursor=None): cmd = UserSearch(cursor) user = cmd() if user: user = user[0] email = SingleEmailUserSearch(user)().email MainUser(name=email, email=email, key=to_node_key(user), creation=user.creation).put() path = to_path(tasks, cmd.cursor.urlsafe()) taskqueue.add(url=path) else: send_mail_to_admins(settings.SENDER_EMAIL, 'Migration End', 'Migration end')
def get(self): self.setup() try: self.login(os.environ["DXY_USERNAME"], os.environ["DXY_PASSWORD"]) self.fetch_dingdang() except Exception: logging.exception("Failed.") app_id = app_identity.get_application_id() mail.send_mail_to_admins("alert@%s.appspotmail.com" % app_id, subject="Fail to fetch DingDang", body="https://appengine.google.com/logs?&app_id=%s" % app_id)
def update_articles_replies(cursor=None): query = query_with_cursor(Article.all(), cursor) articles = query.fetch(100) if articles: for article in articles: article.replies = Comment.all().ancestor(article).count(None) db.put(articles) if len(articles) < 100: mail.send_mail_to_admins(ADMIN_EMAIL, "Articles' replies count has been updated.", 'You can go to check it now.') else: deferred.defer(update_articles_replies, query.cursor())
def update_articles_replies(cursor=None): query = query_with_cursor(Article.all(), cursor) articles = query.fetch(100) if articles: for article in articles: article.replies = Comment.all().ancestor(article).count(None) db.put(articles) if len(articles) < 100: mail.send_mail_to_admins(ADMIN_EMAIL, u'文章评论数更新完成', u'您可以去检查看看了') else: deferred.defer(update_articles_replies, query.cursor())
def error_report(viewer, url=None, request_code=None, description=None, stack=None, **ignored): settings = system_settings.get_system_settings() sender = viewer.user.email() if "email_admin" in settings: sender = settings["email_admin"] body = "%s\n\nURL: %s\nRequest: %s\n\n%s" % (description, url, request_code, stack) log.debug("Sending Email to Admins from %s:" % sender) log.debug(body) mail.send_mail_to_admins(sender, "Aegis Error - %s" % url, body)
def get(self): self.set_content_type('atom') feed = Feed.all().order('-time').get() if feed: self.write(feed.content.encode('utf-8')) user_agent = self.request.user_agent if 'pubsubhubbub' in user_agent or 'Feedfetcher-Google' in user_agent: url = u'%s%sgenerate_feed?cursor=%s' % (self.request.host_url, BLOG_ADMIN_RELATIVE_PATH, feed.cursor) mail.send_mail_to_admins(ADMIN_EMAIL, u'Feedfetcher-Google已抓取feed', u'Click this URL to generate next feed after confirm Google Reader has recorded:\n' + url, html=u'Click this URL to <a href="%s">generate next feed</a> after confirm Google Reader has recorded your feed.' % url)
def delete_category(path): articles = Article.all().filter('category =', path).fetch(100) if not articles: db.delete(db.Key.from_path('Category', Category.path_to_name(path))) clear_categories_memcache() mail.send_mail_to_admins(ADMIN_EMAIL, u'删除分类成功', u'分类路径:' + path) return for article in articles: article.category = None db.put(articles) deferred.defer(delete_category, path)
def _send_mail_to_admins(sender, subject, body): try: mail.send_mail_to_admins( sender=sender, subject=subject, body=body, ) return True except apiproxy_errors.OverQuotaError, message: logging.error(message) return False
def notify_admins_about_new_user_signup(user): mail.send_mail_to_admins(sender="Mockko <*****@*****.**>", subject="[Mockko] new user signed up: %s" % user.email(), body="""Dear Creators, Another human being is about to discover just how awesome our iPhone mock-up tool is. Say hello to %s! -- Your Mockko. """ % user.email())
def _notify_email(email, phone, name, login, password): mandrill.send_email( "*****@*****.**", email, "Ваши данные для входа в демо-приложение Ru-beacon", u"""Ваш логин: <b>%s</b><br/> Ваш пароль: <b>%s</b><br/> <a href="http://rbcn.mobi/get/dem?m=email">Скачать демо-приложение</a>""" % (login, password)) mail.send_mail_to_admins( "*****@*****.**", u"Создана компания через wizard", u"Название: %s\nТелефон: %s\nEmail: %s\nЛогин: %s\nПароль: %s" % (name, phone, email, login, password))
def post(self): user = users.get_current_user() if user is None: self.redirect('/') name = self.request.get('name') url = self.request.get('url') dup_name = Proxy.all().filter('name =', name) dup_url = Proxy.all().filter('url =', url) error = False context = { 'msg': 'Thanks for your addition! Your URL will be checked by an administrator soon.', } if url.find('$@') == -1: error = True context['msg'] = 'Your URL does not include the token "$@". Please see the other URLs in the database for examples.' if dup_name.count() > 0: error = True context['msg'] = 'A proxy with that name already exists in the database, please try again.' if dup_url.count() > 0: if error: context['msg'] = 'A proxy with that name and url already exists in the database, please try again.' else: error = True context['msg'] = 'A proxy with that url already exists in the database, please try again.' if not error: proxy = Proxy( name=self.request.get('name'), url=self.request.get('url'), approved=users.is_current_user_admin(), ) proxy.put() if not proxy.approved: memcache.delete('moderated_proxies') message = 'New EZProxy URL: {0}: {1}\n\nhttp://ezproxy-db.appspot.com'.format( proxy.name, proxy.url) mail.send_mail_to_admins('*****@*****.**', 'EZProxy DB Moderation Request', message) else: memcache.delete('proxies') return self.redirect('/') self.render_response('addproxy.html', context)
def send_error(scope, subject, body, html=None): subject = "[Resto] " + subject if config.DEBUG: subject = "[Test]" + subject sender = "%s_errors@%s" % (scope, _EMAIL_DOMAIN) recipients = config.ERROR_EMAILS.get(scope, _DEFAULT_EMAIL) kw = {'html': html} if html else {} if recipients == "admins": mail.send_mail_to_admins(sender, subject, body, **kw) else: try: mail.send_mail(sender, recipients, subject, body, **kw) except: pass
def delete_tag(name): articles = Article.all().filter('tags =', name).fetch(100) if not articles: db.delete(db.Key.from_path('Tag', name)) clear_tags_memcache() mail.send_mail_to_admins(ADMIN_EMAIL, u'删除标签成功', u'标签名:' + name) return for article in articles: tags = article.tags while name in tags: tags.remove(name) article.tags = tags db.put(articles) deferred.defer(delete_tag, name)
def receive(self, mail_message): sender = mail_message.sender.lower() if APPROVED_EMAILS[0] not in sender and APPROVED_EMAILS[ 1] not in sender: logging.warn("Parser: sender %s is not approved", mail_message.sender) return plaintext_bodies = mail_message.bodies('text/plain') res = [] for content_type, body in plaintext_bodies: if body.encoding == "binary": # "Unknown decoding binary" happens if Content-Transfer-Encoding is set to binary plaintext = body.payload if body.charset and str(body.charset).lower() != '7bit': plaintext = plaintext.decode(str(body.charset)) else: # Decodes base64 and friends plaintext = body.decode() v = self.parseAlfabank(plaintext) if v: res.append(v) else: logging.warning("Unable to parse mail %s", plaintext) mail.send_mail_to_admins( sender=USER_EMAIL, subject="DrebeDengi parser: unable to parse email", body=plaintext) if len(res) > 0: mail.send_mail_to_admins(sender=USER_EMAIL, subject="DrebeDengi parser: " + "; ".join(res), body="Parse result:\n" + "\n".join(res)) mail.send_mail(sender=USER_EMAIL, to="*****@*****.**", subject="Please parse " + DD_MAIL_CODE, body=DD_MAIL_CODE, attachments=[('lines.txt', "\n".join(res))]) logging.info("Success result sent to DrebeDengi") else: logging.warning( 'Nothing sent to Drebedengi... empty result parsed') logging.info("Parse result: %s", "; ".join(res))
def tasks(cursor=None): cmd = UserSearch(cursor) user = cmd() if user: user = user[0] email = SingleEmailUserSearch(user)().email MainUser(name=email, email=email, key=to_node_key(user), creation=user.creation).put() path = to_path(tasks, cmd.cursor.urlsafe()) taskqueue.add(url=path) else: send_mail_to_admins(settings.SENDER_EMAIL, 'Migration End', 'Migration end')
def post(self): post = self.request.POST painting = ndb.Key(urlsafe=post.get('painting_id')).get() mail.send_mail_to_admins(sender="{0} <{1}>".format( post.get('name'), post.get('email')), subject="Painting requested", body=""" Dear Jeanne: I'm interested in your painting: {0} {1} {2} """.format(painting.name, post.get('name'), post.get('number'))) self.response.status = '200 OK'
def _mail_group(group, subject, message, fail_silently=False): """Sends a message to an administrative group.""" if group: mail.send_mail(settings.EMAIL_SUBJECT_PREFIX + subject, message, settings.SERVER_EMAIL, [a[1] for a in group], fail_silently) return # If the group had no recipients defined, default to the App Engine admins. try: gmail.send_mail_to_admins(settings.SERVER_EMAIL, settings.EMAIL_SUBJECT_PREFIX + subject, message) except: if not fail_silently: raise
def mail_admins(subject, message, fail_silently=False): """Sends a message to the admins, as defined by the ADMINS setting.""" if not settings.ADMINS: return if settings.NOTIFY_ERRORS_TO_GAE_ADMINS: mail.send_mail_to_admins(sender=settings.ADMINS[0][1], subject=subject, body=message) return for admin in settings.ADMINS: mail.send_mail(sender=admin[1], to=admin[1], subject=subject, body=message)
def post(self): t = make_getter(lang_selector(self.request)) self.response.content_type = "text/plain;charset=utf-8" email = self.request.get('email') phone = filter_phone(self.request.get('phone')) if not phone: self.response.write(t["RESULT_WRONG_PHONE"]) return phone = phone[1:] phone = "+%s (%s) %s-%s-%s" % (phone[0], phone[1:4], phone[4:7], phone[7:9], phone[9:]) mail_body = u"Телефон: %s, email: %s" % (phone, email) mail.send_mail_to_admins("*****@*****.**", "Новая заявка с landing", mail_body) self.response.write(t["RESULT_OK"])
def get(self): self.set_content_type('atom') feed = Feed.all().order('-time').get() if feed: self.write(feed.content.encode('utf-8')) if 'Feedfetcher-Google' in self.request.user_agent: url = u'%s%sgenerate_feed?cursor=%s' % ( self.request.host_url, BLOG_ADMIN_RELATIVE_PATH, feed.cursor) mail.send_mail_to_admins( ADMIN_EMAIL, u'Feedfetcher-Google已抓取feed', u'确认Google Reader已收录后,可点此链接继续生成后续feed:\n' + url, html= u'确认Google Reader已收录后,可点此<a href="%s">链接</a>继续生成后续feed。' % url)
def get(self): if not requires_user(self): return template_file = os.path.join(os.path.dirname(__file__), 'templates/register.html') if not is_registered() and not is_pending(): # add to pending users models.add_pending_user(users.get_current_user()) status = 'new pending' registered = False # send email to both user and admin sender_address = 'Squash TAI <' + ADMIN_EMAIL + '>' to = users.get_current_user().email() subject = "Inscription à Squash TAI" body = """ Votre inscription a bien été prise en compte, et est en attente de validation. Un nouveau mail vous sera envoyé lorsque votre inscription deviendra effective. Vous pouvez répondre à cette adresse pour plus d'information. Squash TAI """ mail.send_mail(sender_address, to, subject, body) subject = "Demande d'inscription à Squash TAI" body = """ Nouvelle demande d'inscription pour %s. %s.appspot.com/users/pending """ % (users.get_current_user().email() , APP_URL) mail.send_mail_to_admins(sender_address, subject, body) elif not is_registered(): # pending but not registered status = 'already pending' registered = False else: # already registered status = 'already registered' registered = True template_values = { 'greeting': get_greeting(), 'is_admin': is_admin(), 'is_registered': registered, 'status': status } self.response.out.write(Template(filename=template_file,lookup=mylookup).render_unicode(**template_values))
def error_report(viewer, url=None, request_code=None, description=None, stack=None, **ignored): settings = system_settings.get_system_settings() sender = viewer.user.email() if "email_admin" in settings: sender = settings["email_admin"] body = "%s\n\nURL: %s\nRequest: %s\n\n%s" % (description, url, request_code, stack) log.debug("Sending Email to Admins from %s:" % sender) log.debug(body) mail.send_mail_to_admins(sender, "Aegis Error - %s" % url, body)
def request_account_deletion(user): """Requests deletion of user's account from application administrators by sending them an email. This is a temporary method, until we have an automated solution. """ account = accounts.getCurrentAccount(normalize=False) sender = system.getApplicationNoReplyEmail() subject = ADMIN_REQUEST_EMAIL_SUBJEST % {'url_id': user.url_id} body = ADMIN_REQUEST_EMAIL_BODY % { 'name': user.name, 'email': account.email(), 'url_id': user.url_id, } mail.send_mail_to_admins(sender, subject, body)
def log_error(subject, message, *args): if args: try: message = message % args except: pass logging.error(subject + ' : ' + message) subject = 'MyLife Error: ' + subject app_id = app_identity.get_application_id() sender = "MyLife Errors <errors@%s.appspotmail.com>" % app_id try: to = Settings.get().email_address mail.check_email_valid(to, 'To') mail.send_mail(sender, to, subject, message) except: mail.send_mail_to_admins(sender, subject, message)
def get(self): today = str(datetime.date.today() + datetime.timedelta(days=-1)) tdgrkeyname = "GoogleReader%s" % (today) tdgbkeyname = "GoogleBuzz%s" % (today) today_gr_stat = UpdateStat.get_or_insert(tdgrkeyname) today_gb_stat = UpdateStat.get_or_insert(tdgbkeyname) today_all = today_gr_stat.counter + today_gb_stat.counter sender_address = "G2T <*****@*****.**>" subject = "[%s]G2T Daily UpdateStat Summary" % today body = """ Daily Google Reader Update : %d Daily Google Buzz Update : %d Daily All Update : %d """ % (today_gr_stat.counter, today_gb_stat.counter, today_all) mail.send_mail_to_admins(sender_address, subject, body)