def new_invite_users(self, new_invite_list): for user_email in new_invite_list: if user_email not in self.invited_users: user_obj = User.create_user(user_email, [-1, -1], '', '', '') user_obj.add_catchup(self.id) print(user_obj) util.send_email(user_email)
def _do_edit(system, form): edit = SystemEdit(system=system, date=datetime.datetime.now(), confirmed=False, name=form.cleaned_data['name'], owner_email=form.cleaned_data['owner_email'], operating_system=form.cleaned_data['operating_system'], graphics=form.cleaned_data['graphics'], processor=form.cleaned_data['processor'], notes=form.cleaned_data['notes'], secret_key=util.random_key()) edit.save() confirm_link = "confirm_edit?edit=%d&auth=%s" % (edit.id, edit.make_auth("confirm")) util.send_email( 'mails/confirm_edit.txt', { 'settings': settings, 'system': system, 'edit': edit, 'confirm_link': confirm_link }, system.owner_email) return edit
def test_email(self): # given mailbox_dir = '/var/mail' random_string = str(uuid.uuid4()) subject = 'Test Mail ' + random_string msg_body = 'Message body: ' + random_string attachments = [('attachment1-name-' + random_string, 'attachment1-body'), ('attachment2-name-' + random_string, 'attachment2-body')] # when util.send_email( smtp_server_addr='localhost', sender='root@localhost', recipients=['root@localhost'], subject=subject, message=msg_body, attachments=attachments) # then time.sleep(2) self.assertTrue(os.listdir(mailbox_dir)) mailbox_file_name = util.run_cmd('ls -Art /var/mail| tail -n 1') mail_file = mailbox_dir + '/' + mailbox_file_name mails = open(mail_file).read() self.assertTrue('From: root@localhost' in mails) self.assertTrue('To: root@localhost' in mails) self.assertTrue('Subject: ' + subject in mails) self.assertTrue(msg_body in mails) self.assertTrue('filename=\\"{}\\"";'.format(attachments[0][0]) in mails) self.assertTrue('filename=\\"{}\\"";'.format(attachments[1][0]) in mails)
def main(): '''The main entry point of stats.''' most_recent_match_id = 0 for post in match_collection.find({}).sort('_id', direction=-1).limit(1): most_recent_match_id = post['match_id'] most_recent_match_time = post['start_time'] total_matches = match_collection.count() human_readable_time = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.localtime(most_recent_match_time)) disk_stats = os.statvfs('/') mb_remaining = disk_stats.f_bavail * disk_stats.f_frsize / 1024.0 / 1024.0 / 1024.0 msg = ''' Hello! The database currently contains %s matches. The most recent match_id added to the database was %s. The date of that match was %s. There are %.2f remaining GB on the hard drive. <3 dotabot ''' % (total_matches, most_recent_match_id, human_readable_time, mb_remaining) send_email(msg, subject='DOTAbot Update')
def main(): message_info = [] trend_dict = {} for period in SUBSCRIBE_PERIODS: message_info.append({ 'from_city_name': CITY_NAME[period['from_city']], 'to_city_name': CITY_NAME[period['to_city']], 'from_city': period['from_city'], 'to_city': period['to_city'], 'date': period['date'], 'week_day_info': util.get_week_day(period['date']), 'flights': get_top_cheap_flights(period) }) trend_dict[(period['date'], period['from_city'], period['to_city'])] =\ get_price_trend(period) message_info = sorted(message_info, key=lambda x: x['date']) if message_info: tmp = template.page.get_html(message_info, trend_dict) if IS_RECORD_HTML: with open('html/%s.html' % EXEC_TIME.replace(' ', '_'), 'w') \ as handler: handler.write(tmp) if IS_SEND_EMAIL: util.send_email(tmp)
def send_forgot_password(email): # type: (str) -> Tuple[bool, Optional[str]] """ Returns: (email_sent: bool, error: string) """ if not email: return False, "Email address can't be empty" email_error = validate_email_address(email) if email_error: return False, email_error with crawl_db(password_db) as db: db.c.execute("select id from dglusers where email=? collate nocase", (email, )) result = db.c.fetchone() if not result: return False, None userid = result[0] token = create_password_token(userid) msg_body_plaintext, msg_body_html = generate_token_email(token) send_email(email, 'Request to reset your password', msg_body_plaintext, msg_body_html) return True, None
def send_forgot_password(email): # Returns a tuple where item 1 is a truthy value when an email was sent, and item 2 is an error message or None if not email: return False, "Email address can't be empty" email_error = validate_email_address(email) if email_error: return False, email_error try: # lookup user-provided email conn = sqlite3.connect(password_db) c = conn.cursor() c.execute("select id from dglusers where email=? collate nocase", (email,)) result = c.fetchone() # user was found if result: userid = result[0] # generate random token token_bytes = os.urandom(32) token = urlsafe_b64encode(token_bytes) # hash token token_hash_obj = hashlib.sha256(token) token_hash = token_hash_obj.hexdigest() # store hash in db c.execute("insert into recovery_tokens(token, token_time, user_id) " "values (?,datetime('now'),?)", (token_hash, userid)) conn.commit() # send email url_text = config.lobby_url + "?ResetToken=" + token msg_body_plaintext = """Someone (hopefully you) has requested to reset the password for your account at """ + config.lobby_url + """. If you initiated this request, please use this link to reset your password: """ + url_text + """ If you did not ask to reset your password, feel free to ignore this email. """ msg_body_html = """<html> <head></head> <body> <p>Someone (hopefully you) has requested to reset the password for your account at """ + config.lobby_url + """.<br /><br /> If you initiated this request, please use this link to reset your password:<br /><br />  <a href='""" + url_text + """'>""" + url_text + """</a><br /><br /> If you did not ask to reset your password, feel free to ignore this email. </p> </body> </html>""" send_email(email, 'Request to reset your password', msg_body_plaintext, msg_body_html) return True, None # email was not found, do nothing return False, None finally: if c: c.close() if conn: conn.close()
def main(): '''The main entry point of stats.''' most_recent_match_id = 0 for post in match_collection.find({}).sort('_id', direction=-1).limit(1): most_recent_match_id = post['match_id'] most_recent_match_time = post['start_time'] total_matches = match_collection.count() human_readable_time = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.localtime(most_recent_match_time)) disk_stats = os.statvfs('/') mb_remaining = disk_stats.f_bavail * disk_stats.f_frsize/1024.0/1024.0/1024.0 msg = ''' Hello! The database currently contains %s matches. The most recent match_id added to the database was %s. The date of that match was %s. There are %.2f remaining GB on the hard drive. <3 dotabot ''' % (total_matches, most_recent_match_id, human_readable_time, mb_remaining) send_email(msg, subject='DOTAbot Update')
def recover(): """recover""" if request.method == 'GET': return render_template('recover_password.html') username = request.form['username'] registered_user = User.query.filter_by(username=username,).first() if registered_user is None: flash(gettext('Invalid username'), 'danger') return redirect(url_for('recover', lang=g.current_lang)) fromaddr = '%s <%s>' % (APP.config['GHC_SITE_TITLE'], APP.config['GHC_ADMIN_EMAIL']) toaddr = registered_user.email template_vars = { 'config': APP.config, 'password': registered_user.password } msg = render_template2('recover_password_email.txt', template_vars) send_email(APP.config['GHC_SMTP'], fromaddr, toaddr, msg) flash(gettext('Password sent via email'), 'success') if 'next' in request.args: return redirect(request.args.get('next')) return redirect(url_for('home', lang=g.current_lang))
def recover(): """recover""" if request.method == 'GET': return render_template('recover_password.html') username = request.form['username'] registered_user = User.query.filter_by(username=username, ).first() if registered_user is None: flash(gettext('Invalid username'), 'danger') return redirect(url_for('recover', lang=g.current_lang)) fromaddr = '%s <%s>' % (APP.config['GHC_SITE_TITLE'], APP.config['GHC_ADMIN_EMAIL']) toaddr = registered_user.email template_vars = { 'config': APP.config, 'password': registered_user.password } msg = render_template2('recover_password_email.txt', template_vars) send_email(APP.config['GHC_SMTP'], fromaddr, toaddr, msg) flash(gettext('Password sent via email'), 'success') if 'next' in request.args: return redirect(request.args.get('next')) return redirect(url_for('home', lang=g.current_lang))
def send(self): """ Send the assembled log out as an email. """ body = "\n".join(self.log) recipient = ACCOUNTING_MAIL_RECIPIENT subject = "Batch run" send_email(body=body, recipient=recipient, subject=subject)
def save_match_id(): '''Save the last match ID processed to a file on exit.''' global last_match_id, date_max if last_match_id != -1 and date_max != -1: open('last_match', 'w').write('%d' % last_match_id) open('date_max', 'w').write('%d' % date_max) msg = 'Script crashed! Last match id was %s. Date_max was %s' % (last_match_id, date_max) send_email(msg, subject='Script crashed!')
def save_match_id(): '''Save the last match ID processed to a file on exit.''' global last_match_id, date_max if last_match_id != -1 and date_max != -1: open('last_match', 'w').write('%d' % last_match_id) open('date_max', 'w').write('%d' % date_max) msg = 'Script crashed! Last match id was %s. Date_max was %s' % ( last_match_id, date_max) send_email(msg, subject='Script crashed!')
def main(): for item in context: email_body = template.render(item) try: print("Sent to " + item['email']) if not args.quiet: print(email_body) if not args.dryrun: util.send_email(item['email'], subject, email_body) except: print("missing email address")
def reset_req(): """ Reset password request handling. """ if request.method == 'GET': return render_template('reset_password_request.html') # Reset request form with email email = request.form['email'] registered_user = User.query.filter_by(email=email).first() if registered_user is None: LOGGER.warn('Invalid email for reset_req: %s' % email) flash(gettext('Invalid email'), 'danger') return redirect(url_for('reset_req', lang=g.current_lang)) # Generate reset url using user-specific token token = registered_user.get_token() reset_url = '%s/reset/%s' % (CONFIG['GHC_SITE_URL'], token) # Create message body with reset link msg_body = render_template('reset_password_email.txt', lang=g.current_lang, config=CONFIG, reset_url=reset_url, username=registered_user.username) try: from email.mime.text import MIMEText from email.utils import formataddr msg = MIMEText(msg_body, 'plain', 'utf-8') msg['From'] = formataddr( (CONFIG['GHC_SITE_TITLE'], CONFIG['GHC_ADMIN_EMAIL'])) msg['To'] = registered_user.email msg['Subject'] = '[%s] %s' % (CONFIG['GHC_SITE_TITLE'], gettext('reset password')) from_addr = '%s <%s>' % (CONFIG['GHC_SITE_TITLE'], CONFIG['GHC_ADMIN_EMAIL']) to_addr = registered_user.email msg_text = msg.as_string() send_email(CONFIG['GHC_SMTP'], from_addr, to_addr, msg_text) except Exception as err: msg = 'Cannot send email. Contact admin: ' LOGGER.warn(msg + ' err=' + str(err)) flash(gettext(msg) + CONFIG['GHC_ADMIN_EMAIL'], 'danger') return redirect(url_for('login', lang=g.current_lang)) flash(gettext('Password reset link sent via email'), 'success') if 'next' in request.args: return redirect(request.args.get('next')) return redirect(url_for('home', lang=g.current_lang))
def send_email_update(new_top_stories): if not ADMIN_EMAIL: return for probe_name in [p for p in new_top_stories][:10]: title = new_top_stories[probe_name]['title'] link = new_top_stories[probe_name]['link'] # msg = '%s: %s <a href = "%s">%s</a>' % (probe_name, title, link, link) msg = '%s: %s' % (title, link) if len(new_top_stories) > 10: msg += "\n Alert! There are more than 10 top stories in this update" subject = "spaceprobes update for %s" % probe_name send_email(subject, msg, ADMIN_EMAIL)
def reset_req(): """ Reset password request handling. """ if request.method == 'GET': return render_template('reset_password_request.html') # Reset request form with email email = request.form['email'] registered_user = User.query.filter_by(email=email).first() if registered_user is None: LOGGER.warn('Invalid email for reset_req: %s' % email) flash(gettext('Invalid email'), 'danger') return redirect(url_for('reset_req', lang=g.current_lang)) # Generate reset url using user-specific token token = registered_user.get_token() reset_url = '%s/reset/%s' % (CONFIG['GHC_SITE_URL'], token) # Create message body with reset link msg_body = render_template('reset_password_email.txt', lang=g.current_lang, config=CONFIG, reset_url=reset_url, username=registered_user.username) try: from email.mime.text import MIMEText from email.utils import formataddr msg = MIMEText(msg_body, 'plain', 'utf-8') msg['From'] = formataddr((CONFIG['GHC_SITE_TITLE'], CONFIG['GHC_ADMIN_EMAIL'])) msg['To'] = registered_user.email msg['Subject'] = '[%s] %s' % (CONFIG['GHC_SITE_TITLE'], gettext('reset password')) from_addr = '%s <%s>' % (CONFIG['GHC_SITE_TITLE'], CONFIG['GHC_ADMIN_EMAIL']) to_addr = registered_user.email msg_text = msg.as_string() send_email(CONFIG['GHC_SMTP'], from_addr, to_addr, msg_text) except Exception as err: msg = 'Cannot send email. Contact admin: ' LOGGER.warn(msg + ' err=' + str(err)) flash(gettext(msg) + CONFIG['GHC_ADMIN_EMAIL'], 'danger') return redirect(url_for('login', lang=g.current_lang)) flash(gettext('Password reset link sent via email'), 'success') if 'next' in request.args: return redirect(request.args.get('next')) return redirect(url_for('home', lang=g.current_lang))
def post(self): '''Crear un nuevo usuario''' email = api.payload['email'] password = api.payload['password'] name = api.payload['name'] existing_user = db.db.users.find_one({'email': email}) if existing_user: api.abort(409, status="El email del usuario ya se encuentra registrado") if validate_email(email) and name and password: password_hashed = generate_password_hash(password) idUser = db.db.users.insert_one({ 'name': name, 'email': email, 'password': password_hashed, 'diagram': {} }) if idUser: expirationToken = datetime.datetime.utcnow( ) + datetime.timedelta(days=1) payloadToken = {'user': email, 'exp': expirationToken} token = jwt.encode(payloadToken, current_app.config['SECRET_KEY']) response = { "email": email, "name": name, "token": token.decode('UTF-8') } email_result = send_email(email, password, name) return response else: api.abort(500, status="Ocurrio un error en el proceso")
def put(self): '''Cambio de contraseña''' email = api.payload['email'] new_pass = api.payload['password'] user_exists = db.db.users.find_one({'email': email}) if not user_exists: api.abort(403, 'El correo eléctronico no se encuentra registrado') hash_new_pass = generate_password_hash(new_pass) db_result = db.db.users.update_one( {'email': email}, {'$set': { 'password': hash_new_pass }}) if db_result: sending_email = send_email(email, new_pass, user_exists['name'], True, True) return ("ok, revisa la bandeja de entrada de tu correo", sending_email) if sending_email == 200 else ( "Ocurrio un eror en el correo de verificación", sending_email) else: api.abort( 403, "No se pudo realizar el cambio de contraseña, intente en otro momento" )
def thread(): if util.validate_request_post(request.form) is not None: return jsonify(type='danger', text=util.validate_request_post(request.form)) try: submission = util.r.submission(url=request.form['submission']) except: return jsonify(type='danger', text='That wasn\'t a reddit link, was it?') if not submission.url.startswith('https://www.reddit.com/r/'): body = util.get_content(submission.url) else: body = util.markdown(submission.selftext, output_format='html5') title = submission.title author = "[deleted]" if submission.author is not None: author = submission.author.name address = request.form['email'] kindle_address = request.form['kindle_address'] comments = None if request.form['comments'] == 'true': submission.comments.replace_more(limit=0) comments = util.get_comments(submission, request.form['comments_style'], author) attachment = render_template('comments.html', title=title, body=body, author=author, comments=comments) status = util.send_email(address, kindle_address, attachment, title) if status is None: return jsonify(type='success', text='Success!') else: return jsonify(type='warning', text='Uh oh! Something went wrong on our end')
def foursquare_auth_callback(): code = request.args.get('code') if code: logger.info("Exchanging code for access token") response = requests.get( "https://foursquare.com/oauth2/access_token", params=dict( client_id=FOURSQUARE_CLIENT_ID, client_secret=FOURSQUARE_CLIENT_SECRET, grant_type='authorization_code', redirect_uri='https://checkin-checker.herokuapp.com/auth/callback/foursquare', code=code, ) ) response.raise_for_status() access_token = response.json().get('access_token') logger.info("Got access token for user") response = requests.get( "https://api.foursquare.com/v2/users/self", params=dict( oauth_token=access_token, v='20151108', ) ) response.raise_for_status() user_data = response.json()['response']['user'] email = user_data.get('contact', {}).get('email') if email: message = u"Hi {name},\n\n" \ "You just connected your Foursquare account to Checkin Checker at https://checkin-checker.herokuapp.com. " \ "If you ever want to disconnet, go to https://foursquare.com/settings/connections and remove the Checkin Checker app.\n\n" \ "Checkin Checker".format( name=user_data.get('firstName'), ) send_email(email, "Welcome to Checkin Checker", message) message = u"A new checkin-checker user from Foursquare just connected.\n\n" \ "Name: {name}\n" \ "Foursquare page: https://foursquare.com/user/{user_id}\n".format( name=user_data.get('firstName'), user_id=user_data.get('id'), ) send_email('*****@*****.**', "New Checkin Checker User", message) return render_template('auth_callback_foursquare.html')
def convert(): if util.validate_request_subreddit(request.form) is not None: return jsonify(type='danger', text=util.validate_request_subreddit(request.form)) subreddit = request.form['subreddit'] include_comments = request.form['comments'] time = request.form['time'] limit = int(request.form['limit']) address = request.form['email'] kindle_address = request.form['kindle_address'] try: posts = util.get_posts(subreddit, time, limit) if time == 'all': title = 'Top ' + str( limit) + ' posts from /r/' + subreddit + ' ever' else: title = 'Top ' + str( limit ) + ' posts from /r/' + subreddit + ' over the past ' + time top = [] for post in posts: author = '[deleted]' if post.author is None else post.author.name comments = None if include_comments == 'true': post.comments.replace_more(limit=0) comments = util.get_comments(post, request.form['comments_style'], author) try: top.append({ 'title': post.title, 'body': util.get_content(post.url) if not post.url.startswith('https://www.reddit.com/r/') else util.markdown(post.selftext), 'author': author, 'comments': comments }) except: pass except: return jsonify(type='danger', text='That ain\'t no subreddit I\'ve ever heard of!') attachment = render_template('posts.html', posts=top, title=title) status = util.send_email(address, kindle_address, attachment, title) if status is None: return jsonify(type='success', text='Success!') else: return jsonify(type='warning', text='Uh oh! Something went wrong on our end')
def main(start_match_id): '''The main entry point of dotabot.''' global date_max while True: # Note: GetMatchHistory returns a list of matches in descending order, # going back in time. sleep(1.0) logger.debug('Doing GMH query for start_at_match_id=%s' % start_match_id) gmh = api.get_match_history(start_at_match_id=start_match_id, skill=3, date_min=DATE_MIN, date_max=date_max, game_mode=2, min_players=10)['result'] error_code = gmh['status'] matches = gmh['matches'] if error_code is not 1: msg = 'GetMatchHistory query starting at match_id %s returned error code %s. Retrying.' % ( start_match_id, error_code) logger.debug(msg) send_email(msg, subject='GMH query failed (script still running)') continue if len(matches) is 0: msg = 'Zero matches for GMH query with start_at_match_id=%s: \n\n %s' % ( start_match_id, gmh) logger.debug(msg) send_email( msg, subject='GMH query had zero matches (forced script to crash)') exit(-1) for match in matches: sleep(1.0) process_match_details(match['match_id']) tail_match = matches[-1] date_max = tail_match['start_time'] tail_match_id = tail_match['match_id'] logger.debug('Match_id of last match of GMH query: %s' % last_match_id) logger.debug('Date of last match of GMH query: %s' % date_max) # We don't want to record the tail match twice, so subtract 1 start_match_id = tail_match_id - 1
def prepare_and_send_email(): to = cfg['notification_email'] if not to: logging.info("No notification email has been setup.") return sender = 'noreply@{}.appspotmail.com'.format(project_id) subject = 'A BVI process has failed.' image_link = "https://{}.appspot.com/images/google-cloud.png".format(project_id) template_values = { 'day': day, 'image_link': image_link } template_path = 'email_templates/processfailure.html' send_email(template_values, template_path, subject, sender, to)
def check_hosts(self): try: this_time = time.time() res = requests.get(settings.HOST_STATUS, timeout=settings.DOWNLOAD_TIMEOUT) data = json.loads(res.text) except: traceback.print_exc() return stamp_dict = data.get('stamp') str_dict = data.get('str') for k, v in stamp_dict.items(): if this_time - float(v) > settings.STANDARD: self.host_name[k.split(':')[1]] = str_dict.get(k) if not len(self.host_name): return body = self.format_data(self.host_name) self.host_name = {} util.send_email('Notice! invalid_hosts', body, settings.HOST_RECEIVERS)
def system_mail_key(request, system_name): try: system = System.objects.get(name=system_name) except System.DoesNotExist: raise Http404 mailed = False if request.method == 'POST': util.send_email('mails/mail_key.txt', { 'settings': settings, 'system': system }, system.owner_email) mailed = True return render_to_response('pages/system_mail_key.html', { 'page': 'system_mail_key', 'page_title': 'Mail Secret Key', 'settings': settings, 'mailed': mailed, 'system': system })
def _do_register(form): edit = SystemEdit(date=datetime.datetime.now(), confirmed=False, name=form.cleaned_data['name'], owner_email=form.cleaned_data['owner_email'], operating_system=form.cleaned_data['operating_system'], graphics=form.cleaned_data['graphics'], processor=form.cleaned_data['processor'], notes=form.cleaned_data['notes'], secret_key=util.random_key()) edit.save() activation_link = "activate?edit=%d&auth=%s" % (edit.id, edit.make_auth("activate")) util.send_email('mails/activate.txt', { 'settings': settings, 'system': edit, 'activation_link': activation_link }, edit.owner_email) return edit
def system_mail_key(request, system_name): try: system = System.objects.get(name=system_name) except System.DoesNotExist: raise Http404 mailed = False if request.method == 'POST': util.send_email('mails/mail_key.txt', { 'settings': settings, 'system': system }, system.owner_email) mailed = True return render_to_response( 'pages/system_mail_key.html', { 'page': 'system_mail_key', 'page_title': 'Mail Secret Key', 'settings': settings, 'mailed': mailed, 'system': system })
def main(start_match_id): '''The main entry point of dotabot.''' global date_max while True: # Note: GetMatchHistory returns a list of matches in descending order, # going back in time. sleep(1.0) logger.debug('Doing GMH query for start_at_match_id=%s' % start_match_id) gmh = api.get_match_history(start_at_match_id=start_match_id, skill=3, date_min=DATE_MIN, date_max=date_max, game_mode=2, min_players=10)['result'] error_code = gmh['status'] matches = gmh['matches'] if error_code is not 1: msg = 'GetMatchHistory query starting at match_id %s returned error code %s. Retrying.' % (start_match_id, error_code) logger.debug(msg) send_email(msg, subject='GMH query failed (script still running)') continue if len(matches) is 0: msg = 'Zero matches for GMH query with start_at_match_id=%s: \n\n %s' % (start_match_id, gmh) logger.debug(msg) send_email(msg, subject='GMH query had zero matches (forced script to crash)') exit(-1) for match in matches: sleep(1.0) process_match_details(match['match_id']) tail_match = matches[-1] date_max = tail_match['start_time'] tail_match_id = tail_match['match_id'] logger.debug('Match_id of last match of GMH query: %s' % last_match_id) logger.debug('Date of last match of GMH query: %s' % date_max) # We don't want to record the tail match twice, so subtract 1 start_match_id = tail_match_id - 1
def _do_edit(system, form): edit = SystemEdit(system=system, date=datetime.datetime.now(), confirmed=False, name=form.cleaned_data['name'], owner_email=form.cleaned_data['owner_email'], operating_system=form.cleaned_data['operating_system'], graphics=form.cleaned_data['graphics'], processor=form.cleaned_data['processor'], notes=form.cleaned_data['notes'], secret_key=util.random_key()) edit.save() confirm_link = "confirm_edit?edit=%d&auth=%s" % (edit.id, edit.make_auth("confirm")) util.send_email('mails/confirm_edit.txt', { 'settings': settings, 'system': system, 'edit': edit, 'confirm_link': confirm_link }, system.owner_email) return edit
def main(): message_info = [] trend_dict = {} for period in SUBSCRIBE_PERIODS: message_info.append({'from_city_name': CITY_NAME[period['from_city']], 'to_city_name': CITY_NAME[period['to_city']], 'from_city': period['from_city'], 'to_city': period['to_city'], 'date': period['date'], 'week_day_info': util.get_week_day(period['date']), 'flights': get_top_cheap_flights(period)}) trend_dict[(period['date'], period['from_city'], period['to_city'])] =\ get_price_trend(period) message_info = sorted(message_info, key=lambda x: x['date']) if message_info: tmp = template.page.get_html(message_info, trend_dict) if IS_RECORD_HTML: with open('html/%s.html' % EXEC_TIME.replace(' ', '_'), 'w') \ as handler: handler.write(tmp) if IS_SEND_EMAIL: util.send_email(tmp)
def process_rd_state(rd, state): if state == 'REVIEWING': # Google Checkout is reviewing the order. adminonly = True mail = False elif state == 'CHARGEABLE': # The order is ready to be charged. adminonly = True mail = True elif state == 'CHARGING': # The order is being charged; you may not refund or cancel an order until is the charge is completed. adminonly = True elif state == 'CHARGED': # The order has been successfully charged; if the order was only partially charged, the buyer's account page will reflect the partial charge. adminonly = False mail = True elif state == 'PAYMENT_DECLINED': # The charge attempt failed. adminonly = True mail = True elif state == 'CANCELLED': # Either the buyer or the seller canceled the order. An order's financial state cannot be changed after the order is canceled. adminonly = False mail = True elif state == 'CANCELLED_BY_GOOGLE': # Google canceled the order. Google may cancel orders due to a failed charge without a replacement credit card being provided within a set period of time or due to a failed risk check. adminonly = False mail = True else: mail = False logging.info("Unexpected state %s" % (str(state))) rd.payment_state = state rd.put() if mail: send_email(rd, adminonly=adminonly)
def send_email(ctx): """ Send an email notifying you of the number of orders awaiting shipment. """ count = 0 body = [] for user_id, cred in config.EBAY_CREDENTIALS.items(): request = OrderRequest(cred) orders = list(request.get_orders()) line = '{user_id} has {count} orders awaiting shipment'.format( user_id=user_id, count=len(orders)) body.append(line) print(line) count += len(orders) if count > 0: util.send_email( recipient=config.EMAIL_ADDRESS, subject='[{:HH:mm}] {} orders awaiting shipment'.format( util.local_now(), count), body='\n'.join(body), )
def thread(): if util.validate_request_post(request.form) is not None: return jsonify(type='danger', text=util.validate_request_post(request.form)) # do this validation client side post_id = request.form['submission'] if not post_id.isnumeric(): return jsonify(type='danger', text='That wasn\'t an HN post ID, was it?') try: post = util.get_item(post_id) except: return jsonify(type='danger', text='That wasn\'t an HN post ID, was it?') # IMPLEMENT THIS for posts with URLs #if not submission.url.startswith('https://www.reddit.com/r/'): # body = util.get_content(submission.url) #else: body = util.markdown(post['text'], output_format='html5') title = post['title'] author = post['by'] address = request.form['email'] kindle_address = request.form['kindle_address'] comments = None if request.form['comments'] == 'true': #submission.comments.replace_more(limit=0) # handle no comments comments = util.get_comments(post['kids'], request.form['comments_style'], author) attachment = render_template('comments.html', title=title, body=body, author=author, comments=comments) status = util.send_email(address, kindle_address, attachment, title) if status is None: return jsonify(type='success', text='Success!') else: return jsonify(type='warning', text='Uh oh! Something went wrong on our end')
def alert(self, infos): """ 判断消息并通知 :return: """ message = [] for info in infos: if info['weibo_time']: weibo_time = info['weibo_time'][0] min = re.compile('([0-9]+)').findall(weibo_time) if len(min) and int(min[0]) < 20 and ':' not in weibo_time: message.append('{} {} 发布了新消息'.format( weibo_time, info['weibo_author'])) message = '\n'.join(message) for receiver in receivers: if not send_email(message, 'monitor', receiver): print('%s: 邮件通知发送失败' % receiver)
def convert(): if util.validate_request_subreddit(request.form) is not None: return jsonify(type='danger', text=util.validate_request_subreddit(request.form)) subreddit = request.form['subreddit'] include_comments = request.form['comments'] time = request.form['time'] limit = int(request.form['limit']) address = request.form['email'] kindle_address = request.form['kindle_address'] try: posts = util.get_posts(subreddit, time, limit) if time == 'all': title = 'Top ' + str(limit) + ' posts from /r/' + subreddit + ' ever' else: title = 'Top ' + str(limit) + ' posts from /r/' + subreddit + ' over the past ' + time top = [] for post in posts: author = '[deleted]' if post.author is None else post.author.name comments = None if include_comments == 'true': post.comments.replace_more(limit=0) comments = util.get_comments(post, request.form['comments_style'], author) try: top.append({'title': post.title, 'body': util.get_content(post.url) if not post.url.startswith( 'https://www.reddit.com/r/') else util.markdown( post.selftext), 'author': author, 'comments': comments}) except: pass except: return jsonify(type='danger', text='That ain\'t no subreddit I\'ve ever heard of!') attachment = render_template('posts.html', posts=top, title=title) status = util.send_email(address, kindle_address, attachment, title) if status is None: return jsonify(type='success', text='Success!') else: return jsonify(type='warning', text='Uh oh! Something went wrong on our end')
def email_results(site): """ Email error and warning messages for a specific site. :param site: The site configuration with E-mail notification settings (if any) """ if not (site and 'EmailNotifications' in site and site['EmailNotifications'] is True and (error_messages or warning_messages)): return status = 'SUCCESS' if error_messages: status = 'ERROR' elif warning_messages: status = 'WARNINGS' message = '' log_files = [ path for path in [LOG_FILE_PATH, KTCLIENT_LOG_PATH, CRON_LOG_FILE_PATH] if os.path.isfile(path) ] message += 'Server hostname: {}\r\n'.format(platform.node()) message += 'Apache VHost: {}\r\n'.format(site['VHost']) message += 'Apache VHost ServerName: {}\r\n'.format(site['ServerName'] or '<None>') message += '\r\n' if error_messages: message += '== Errors ==\r\n{}'.format('\r\n'.join(error_messages)) if warning_messages: message += '\r\n\r\n' message += '== Warnings ==\r\n{}'.format('\r\n'.join(warning_messages)) message += '\r\n\r\nMore information can be found in the attached log file cutouts.' message += '\r\nFor full logs, please see the following files:\r\n\t' message += '\r\n\t'.join(log_files) subject = '{}: {} (VHost {}{})'.format( site['EmailSubject'], status, site['VHost'] or '<unknown>', ', {}'.format(site['ServerName']) if site['ServerName'] else '') server = site['EmailServer'] try: attachments = [] for log_file in log_files: att_name = os.path.basename(log_file) att_content = open(log_file).read() # Only send the last 200 lines of the log to save traffic att_content = '\n'.join(att_content.splitlines()[-200:]) attachments.append((att_name, att_content)) util.send_email(server, site['EmailFrom'], site['EmailTo'].split(','), subject, message, attachments) except Exception as e: log_error( 'Could not send e-mail summary for VHost "{}, {}": {} {} {}'. format(site.get('VHost', '<unknown>'), site.get('ServerName', ''), type(e), e, util.format_traceback()), 'Could not send e-mail summary for VHost "{}, {}": {} {}'.format( site.get('VHost', '<unknown>'), site.get('ServerName', ''), type(e), e)) return False return True
def notify(body='\xe4\xbb\x80\xe4\xb9\x88\xe9\x83\xbd\xe6\xb2\xa1\xe6\x9c\x89......'): title = '[Python]\xe7\xa0\x81\xe5\x86\x9c\xe5\x91\xa8\xe5\x88\x8aPython\xe7\x9b\xb8\xe5\x85\xb3\xe4\xb8\xbb\xe9\xa2\x98\xe6\x9b\xb4\xe6\x96\xb0' for mail in mail_list: util.send_email(title, body, mail)
if new_denied_hosts: info("new denied hosts: %s", str(new_denied_hosts)) else: debug("no new denied hosts") if new_suspicious_logins: info("new suspicious logins: %s", str(new_suspicious_logins.keys())) else: debug("no new suspicious logins") if not self.__report.empty(): if not self.__noemail: # send the report via email if configured send_email(self.__prefs, self.__report.get_report()) elif not self.__daemon: # otherwise, if not in daemon mode, log the report to the console info(self.__report.get_report()) self.__report.clear() return offset def sync_add_hosts(self, hosts): try: filename = os.path.join(self.__prefs.get("WORK_DIR"), SYNC_HOSTS) fp = open(filename, "a") for host in hosts: fp.write("%s\n" % host) fp.close() os.chmod(filename, 0644)
def buy(): """ When the user has completed the flow and is completing their insurance purchase. Example input: form = { 'insurance_type': 'Renters', 'first_name': 'Christian', 'last_name': 'Bale', 'dob': '01/30/1974', 'gender': 'm', 'address': '3328 Bay Road', 'city': 'Rewood City', 'state': 'CA', 'zip_code': '94063' } """ try: data = request.get_json() token = None if data.get('payment_form', None): payment_form = data['payment_form'] # Store payment information, get token and save it into renter_form_dict. headers = {'content-type': 'application/json'} try: r = requests.post(config.payment_endpoint, data=json.dumps(payment_form), headers=headers) result = r.json() if result['status'] == 'success': app.logger.info("Success to store credit card info.") token = result['token'] else: app.logger.error("Fail to store credicard. {message}".format(**result) ) return jsonify(status='fail', message="Invalid Credit Card Information") except Exception as e: app.logger.error("Fail to connect to payment service. %s" % e) memorized_price = get_price_of_user_form(data, use_memorized_only=True) app.logger.info("Get price of the form") # Expand defaults so we know what we are assuming. renter_form_dict = data['renter_form'] defaults = ExpandDefaults(renter_form_dict['purchase_category']) renter_form_dict.update(defaults) # Log whatever price we have calculated here. renter_form_dict['policy_price'] = '$%.2f' % (memorized_price) learned_price = get_price_of_user_form(data, use_memorized_only=False) renter_form_dict['learned_policy_price'] = '$%.2f' % (learned_price) # Payment information renter_form = RenterForm(**renter_form_dict) renter_form.token = token renter_form.save() app.logger.info("Save the form to database") util.send_email([renter_form.email_address], 'Thank You for Trusting! Confirmation for Your Purchase!', 'email/confirmation.html', 'email/confirmation.txt', **renter_form_dict) return jsonify(status='success') except Exception as e: print(e) line = traceback.format_exc() return jsonify(status='fail', message=line)
def text_handler(message): uid = message.from_user.id cid = message.chat.id if message.text == '⬅️ Отмена': if uid in READY_TO_ORDER: del READY_TO_ORDER[uid] if uid in SEE_QUESTIONS_ANSWERS: SEE_QUESTIONS_ANSWERS.remove(uid) markup = types.ReplyKeyboardMarkup(one_time_keyboard=False, resize_keyboard=True, row_width=1) for x in config.main_manu_buttons: markup.add(x) return bot.send_message(cid, config.main_text, reply_markup=markup) # Handle order action if uid in READY_TO_ORDER: if 'name' not in READY_TO_ORDER[uid]: READY_TO_ORDER[uid]['name'] = message.text text = 'Введите email' return bot.send_message(cid, text) if 'email' not in READY_TO_ORDER[uid]: READY_TO_ORDER[uid]['email'] = message.text text = 'Введите номер телефона' return bot.send_message(cid, text) if 'phone_number' not in READY_TO_ORDER[uid]: READY_TO_ORDER[uid]['phone_number'] = message.text text = 'Выберите вид работы' markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True, row_width=1) for work in config.work_types: markup.add(work) markup.add('⬅️ Отмена') return bot.send_message(cid, text, reply_markup=markup) if 'work_type' not in READY_TO_ORDER[uid]: READY_TO_ORDER[uid]['work_type'] = message.text text = 'Введите предмет' markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True, row_width=1) markup.add('⬅️ Отмена') return bot.send_message(cid, text, reply_markup=markup) if 'subject' not in READY_TO_ORDER[uid]: READY_TO_ORDER[uid]['subject'] = message.text text = 'Введите количество страниц' return bot.send_message(cid, text) if 'page_count' not in READY_TO_ORDER[uid]: READY_TO_ORDER[uid]['page_count'] = message.text text = 'Введите тему работы' return bot.send_message(cid, text) if 'work_topic' not in READY_TO_ORDER[uid]: READY_TO_ORDER[uid]['work_topic'] = message.text text = 'Введите срок выполнения' return bot.send_message(cid, text) if 'work_term' not in READY_TO_ORDER[uid]: READY_TO_ORDER[uid]['work_term'] = message.text text = 'Введите дополнительную информацию, если требуется' markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True, row_width=1) markup.add('🆗 Отправить заявку') markup.add('⬅️ Отмена') return bot.send_message(cid, text, reply_markup=markup) if 'add_info' not in READY_TO_ORDER[uid]: if message.text == '🆗 Отправить заявку': READY_TO_ORDER[uid]['add_info'] = '' else: READY_TO_ORDER[uid]['add_info'] = message.text print(READY_TO_ORDER[uid]) order = util.WorkOrder( READY_TO_ORDER[uid]['name'], READY_TO_ORDER[uid]['email'], READY_TO_ORDER[uid]['phone_number'], READY_TO_ORDER[uid]['work_type'], READY_TO_ORDER[uid]['subject'], READY_TO_ORDER[uid]['page_count'], READY_TO_ORDER[uid]['work_topic'], READY_TO_ORDER[uid]['work_term'], READY_TO_ORDER[uid]['add_info'], ) del READY_TO_ORDER[uid] order_text = util.generate_order_text(order) print(order_text) email_user = util.EmailUser(config.email_login, config.email_password) text = 'Ваша заявка оформлена!' try: util.send_email(email_user, config.manager_email, 'Новый заказ', order_text) except Exception as e: print(e) text = 'Не могу отправить вашу заявку. Попробуйте позже.' markup = types.ReplyKeyboardMarkup(one_time_keyboard=False, resize_keyboard=True, row_width=1) for x in config.main_manu_buttons: markup.add(x) return bot.send_message(cid, text, reply_markup=markup) if uid in SEE_QUESTIONS_ANSWERS: for x in config.questions_answers: if message.text == x[0]: return bot.send_message(cid, x[1]) text = 'Вопрос не найден. Выберите один из списка.' return bot.send_message(cid, text) # Handle main menu buttons if message.text in config.main_manu_buttons: if message.text == 'Заказать работу': text = 'Введите свое имя' READY_TO_ORDER[uid] = {} markup = types.ReplyKeyboardMarkup(one_time_keyboard=False, resize_keyboard=True, row_width=1) markup.add('⬅️ Отмена') return bot.send_message(cid, text, reply_markup=markup) elif message.text == 'Наши услуги': for text in config.services: bot.send_message(cid, text, parse_mode='markdown') return elif message.text == 'Вопрос-Ответ': text = 'Выберите вопрос' markup = types.ReplyKeyboardMarkup(one_time_keyboard=False, resize_keyboard=True, row_width=1) for x in config.questions_answers: markup.add(x[0]) markup.add('⬅️ Отмена') SEE_QUESTIONS_ANSWERS.append(uid) return bot.send_message(cid, text, reply_markup=markup) elif message.text == 'Гарантии': for text in config.assurances: bot.send_message(cid, text, parse_mode='markdown') return elif message.text == 'Контакты': return bot.send_message(cid, config.contacts, parse_mode='markdown') elif message.text == 'О компании': return bot.send_message(cid, config.about_company_text, parse_mode='markdown')
def train(config, trial_dir=None, visualize=False, overwrite_config=False): t_agent = config["agent"] assert t_agent in SUPPORTED_AGENTS, "Agent type {} not supported".format( t_agent) # prepare trial environment pid = os.getpid() trial_name = "{}_pid{}".format(t_agent, pid) logger, log_dir = prepare_for_logging(trial_name) # create agent if "max_obstacles" not in config: config["max_obstacles"] = 3 env = NIPS(visualize, max_obstacles=config["max_obstacles"]) logger.info("pid={}, env={}".format(pid, id(env))) # to train from scratch or fine tune fine_tuning = False if trial_dir is not None: config_file = os.path.join(trial_dir, "config.yaml") if not os.path.exists(config_file): convert_legacy_config(trial_dir, t_agent) existing_config = util.load_config(config_file) fine_tuning = True if overwrite_config: logger.info("Overwrite config from file {}".format(trial_dir)) for k, v in config.iteritems(): existing_config[k] = v config = existing_config config["model_dir"] = trial_dir # save config to the trial folder util.print_settings(logger, config, env) config_file = os.path.join(log_dir, "config.yaml") util.save_config(config_file, config) # instantiate an agent config["logger"] = logger config["log_dir"] = log_dir if t_agent == "DDPG": from ddpg import DDPG agent = DDPG(env, config) elif t_agent == "TRPO": from trpo import TRPO agent = TRPO(env, config) else: # because of the assertion above, this should never happen raise ValueError("Unsupported agent type: {}".format(t_agent)) # learn if fine_tuning: util.print_sec_header(logger, "Continual training") agent.set_state(config) else: util.print_sec_header(logger, "Training from scratch") reward_hist, steps_hist = agent.learn( total_episodes=config["total_episodes"]) env.close() # send result img_file = os.path.join(log_dir, "train_stats.png") util.plot_stats(reward_hist, steps_hist, img_file) log_file = os.path.join(log_dir, "train.log") util.send_email(log_dir, [img_file], [log_file], config) logger.info("Finished (pid={}).".format(pid))
#!/usr/bin/env python from util import download_file, parse_vulnerable_softwares, send_email from xmlExtractor import XMLReader if __name__ == "__main__": download_file() xmlReader = XMLReader() xmlReader.xml_parser() vulnearble = parse_vulnerable_softwares(xmlReader.get_cves()) if len(vulnearble) > 0: msg = "{}".format("\n".join(vulnearble[::-1])) print msg send_email(msg)
def notify(title='[Hackerbell]Hacker News Top 10', body='N/A', to=HACKERBELL_RECEIVER): util.send_email(title, body, to)
json.loads(reason)["Address"]) util.log( time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime(int( time.time()))) + " 签到提交成功!但是表单没成功") util.send_mail(email_str) else: print("签到没有成功!") util.send_mail("签到提交失败!") else: print("没有可提交的表单!") util.send_mail("没有可提交的表单!") break else: print(login["message"]) break except requests.exceptions.ConnectionError: print("失败, 可能是网络原因, %s 后开始 第'%s'次 尝试..." % (util.getTenAfter(), str(login_times))) time.sleep(600) login_times += 1 continue if login_times == 6: print("可能是网络原因,无法正常访问!请手动签到!") util.send_email("可能是网络原因,无法正常访问到易班!请手动签到!") login_times = 1
self.__report.add_section(msg, new_suspicious_logins.keys()) if new_denied_hosts: info("new denied hosts: %s", str(new_denied_hosts)) else: debug("no new denied hosts") if new_suspicious_logins: info("new suspicious logins: %s", str(new_suspicious_logins.keys())) else: debug("no new suspicious logins") if not self.__report.empty(): if not self.__noemail: # send the report via email if configured send_email(self.__prefs, self.__report.get_report()) elif not self.__daemon: # otherwise, if not in daemon mode, log the report to the console info(self.__report.get_report()) self.__report.clear() return offset def sync_add_hosts(self, hosts): try: filename = os.path.join(self.__prefs.get("WORK_DIR"), SYNC_HOSTS) fp = open(filename, "a") for host in hosts: fp.write("%s\n" % host) fp.close()
def foursquare_checkin_has_matches(checkin, user): venue = checkin.get('venue') venue_name = venue.get('name') logger.info("Looking for matches with Foursquare venue '%s'", venue_name) categories = venue.get('categories') primary_category = None for category in categories: if category.get('name').endswith('(private)'): logger.info("Skipping checkin at private venue") return if category.get('primary'): primary_category = category user_email = user.get('contact', {}).get('email') if not user_email: logger.warn("This checkin didn't have a user email, so I didn't do anything") return # Send emails for test pushes to me if user.get('id') == '1': user_email = '*****@*****.**' radius = default_overpass_radius override = {} if primary_category: logger.info("Foursquare venue has primary category '%s' (%s)", primary_category['name'], primary_category['id']) override = overrides_for_4sq_categories.get(primary_category['id'], {}) if override: logger.info("Found Overpass override %s because the primary category is %s", override, primary_category.get('name')) if override.get('radius'): radius = override.get('radius') overpass_results = query_overpass( venue.get('location').get('lat'), venue.get('location').get('lng'), radius, query_extra=override.get('extra'), timeout=default_overpass_timeout, ) overpass_remark = overpass_results.get('remark') if overpass_remark and 'Query timed out' in overpass_remark: logger.warn("Overpass query timed out: %s", overpass_remark) return elements = overpass_results.get('elements') logger.info("Found %s things on Overpass", len(elements)) potential_matches = filter_matches(venue_name, elements) if not potential_matches: logger.info("No matches! Send an e-mail to %s", user_email) message = u"""Hi {name}, You checked in at {venue_name} on Foursquare but that location doesn't seem to exist in OpenStreetMap. You should consider adding it! In fact, here's a direct link to the area in your favorite editor: https://www.openstreetmap.org/edit?zoom=19&lat={mlat}&lon={mlon} To remind you where you went, here's a link to your checkin. Remember that you should not copy from external sources (like Foursquare) when editing. https://foursquare.com/user/{user_id}/checkin/{checkin_id} -Checkin Checker (Reply to this e-mail for feedback/questions. Uninstall at https://foursquare.com/settings/connections to stop these e-mails.)""".format( name=user.get('firstName', 'Friend'), venue_name=venue_name, user_id=user['id'], checkin_id=checkin['id'], mlat=round(venue.get('location').get('lat'), 6), mlon=round(venue.get('location').get('lng'), 6), email=user_email, ) send_email(user_email, "Your Recent Foursquare Checkin Isn't On OpenStreetMap", message) else: logger.info(u"Matches: {}".format(u', '.join(map(lambda i: '{}/{} ({:0.2f})'.format(i[1]['type'], i[1]['id'], i[0]), potential_matches)))) best_match_score, best_match = potential_matches[0] logger.info(u"A really great match found: %s/%s (%0.2f)", best_match['type'], best_match['id'], best_match_score) tags = best_match['tags'] questions = [] if 'addr:housenumber' in tags: questions.append(u" - Is the housenumber still '{}'?".format(tags['addr:housenumber'])) else: questions.append(u" - What is the housenumber?") if 'addr:street' in tags: questions.append(u" - Is the venue still on '{}'?".format(tags['addr:street'])) else: questions.append(u" - What is the street name?") if 'phone' in tags: questions.append(u" - Is the phone number still '{}'?".format(tags['phone'])) else: questions.append(u" - What is the phone number?") message = u"""Hi {name}, Your recent checkin to {venue_name} seems to match something in OpenStreetMap. While you're visiting this place, try collecting these missing attributes for OpenStreetMap: {questions} If you want, you can reply to this email and Ian will make these changes, or you can save your email as a draft/note to yourself for later. If you'd like to edit the OSM object directly, use this edit link: https://www.openstreetmap.org/edit?{osm_type}={osm_id} To remind you where you went, here's a link to your checkin. Remember that you should not copy from external sources (like Foursquare) when editing. https://foursquare.com/user/{user_id}/checkin/{checkin_id} -Checkin Checker (Reply to this e-mail for feedback/questions. Uninstall at https://foursquare.com/settings/connections to stop these e-mails.)""".format( name=user.get('firstName', 'Friend'), venue_name=venue_name, user_id=user['id'], checkin_id=checkin['id'], mlat=round(venue.get('location').get('lat'), 6), mlon=round(venue.get('location').get('lng'), 6), osm_type=best_match['type'], osm_id=best_match['id'], questions='\n'.join(questions), email=user_email, ) send_email(user_email, "Your Recent Foursquare Checkin Is On OpenStreetMap!", message)
def run_application(options, instance_name): input_log_file_handler = logging.handlers.TimedRotatingFileHandler( os.path.expanduser(options.mailer_log), when='MIDNIGHT') input_log_file_handler.setFormatter(logging.Formatter(u"%(asctime)s - %(message)s")) mail_logger = logging.getLogger(instance_name) mail_logger.setLevel(logging.INFO) mail_logger.addHandler(input_log_file_handler) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) mail_logger.addHandler(ch) mail_logger.info('START') def log(command, key, value=None): log_msg = u'%s, %s, %s' %(command, key, value if value else None) mail_logger.info(unicode(log_msg)) log('PARAM', 'BEGIN') log('PARAM', 'trade_in', options.trade_in) log('PARAM', 'trade_pub', options.trade_pub) log('PARAM', 'mailer_log', options.mailer_log) log('PARAM', 'mailchimp_apikey', options.mailchimp_apikey) log('PARAM', 'mandrill_apikey', options.mandrill_apikey) log('PARAM', 'mailer_username', options.mailer_username) log('PARAM', 'mailchimp_newsletter_list_id', options.mailchimp_newsletter_list_id) log('PARAM', 'END') context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect(options.trade_pub) socket.setsockopt(zmq.SUBSCRIBE, "^EMAIL$") trade_in_socket = context.socket(zmq.REQ) trade_in_socket.connect(options.trade_in) application_trade_client = TradeClient( context, trade_in_socket) application_trade_client.connect() login_response = application_trade_client.sendJSON( MessageBuilder.login( 8999999, options.mailer_username, options.mailer_password)) if login_response.get('UserStatus') != 1: raise RuntimeError("Invalid user id") brokers = {} broker_list, broker_list_columns = application_trade_client.getBrokerList(['1']) for b in broker_list: brokers[b[0]] = { "params": b } broker_mandrill_column_index = None try: broker_mandrill_column_index = broker_list_columns.index('MandrillApiKey') except ValueError: pass for broker_id, broker_data in brokers.iteritems(): if broker_mandrill_column_index and broker_data['params'][ broker_mandrill_column_index ]: broker_data['MandrillApiKey'] = broker_data['params'][ broker_mandrill_column_index ] else: broker_data['MandrillApiKey'] = options.mandrill_apikey for broker_id, broker_data in brokers.iteritems(): print broker_id, broker_data['MandrillApiKey'] # [u'BrokerID', u'ShortName', u'BusinessName', u'Address', u'City', u'State', # u'ZipCode', u'Country', u'PhoneNumber1', u'PhoneNumber2', u'Skype', u'Currencies', # u'TosUrl', u'FeeStructure', u'TransactionFeeBuy', u'TransactionFeeSell', u'Status', # u'ranking', u'Email', u'CountryCode', u'CryptoCurrencies', u'WithdrawStructure', # u'SupportURL', u'SignupLabel', u'AcceptCustomersFrom', u'IsBrokerHub'] mailchimp_api = mailchimp.Mailchimp(options.mailchimp_apikey) try: mailchimp_api.helper.ping() except mailchimp.Error: raise RuntimeError("Invalid MailChimp API key") mandrill_api = mandrill.Mandrill(options.mandrill_apikey) try: mandrill_api.users.ping() except mandrill.Error: raise RuntimeError("Invalid Mandrill API key") while True: try: raw_email_message = socket.recv() log('IN', 'TRADE_IN_PUB', raw_email_message) msg = JsonMessage(raw_email_message) if not msg.isEmail(): log('ERROR', 'EXCEPTION', 'Received message is not an email message') continue try: broker_id = msg.get('BrokerID') sender = brokers[broker_id]['params'][broker_list_columns.index('MailerFromName')] + \ '<' + brokers[broker_id]['params'][broker_list_columns.index('MailerFromEmail')] + '>' body = "" msg_to = msg.get('To') subject = msg.get('Subject') language = msg.get('Language') content_type = 'plain' if msg.has('Template') and msg.get('Template'): params = {} if msg.has('Params') and msg.get('Params'): params = json.loads(msg.get('Params')) template_name = msg.get('Template') if template_name == 'welcome': # user signup .... let's register him on mailchimp newsletter try: mailchimp_api.lists.subscribe( id = brokers[broker_id]['params'][broker_list_columns.index('MailchimpListID')], email = {'email': params['email'] }, merge_vars = {'EMAIL' : params['email'], 'FNAME': params['username'] } ) except mailchimp.ListAlreadySubscribedError: log('ERROR', 'EXCEPTION', params['email'] + ' mailchimp.ListAlreadySubscribedError' ) except mailchimp.Error, e: log('ERROR', 'EXCEPTION', str(e)) template_content = [] for k,v in params.iteritems(): template_content.append( { 'name': k, 'content': v } ) for broker_column_key in broker_list_columns: broker_column_value = brokers[broker_id]['params'][broker_list_columns.index(broker_column_key)] template_content.append( { 'name': 'broker_' + convertCamelCase2Underscore(broker_column_key), 'content': broker_column_value } ) message = { 'from_email': brokers[broker_id]['params'][broker_list_columns.index('MailerFromEmail')], 'from_name': brokers[broker_id]['params'][broker_list_columns.index('MailerFromName')], 'to': [{'email': msg_to, 'name': params['username'],'type': 'to' }], 'metadata': {'website': 'www.blinktrade.com'}, 'global_merge_vars': template_content } result = mandrill_api.messages.send_template( template_name= (template_name + '-' + language.replace('_','-') ).lower(), template_content=template_content, message=message) log('INFO', 'SUCCESS', str(result)) continue elif msg.has('RawData') and msg.get('RawData'): body = msg.get('RawData') log('DEBUG', 'EMAIL', u'{"Sender":"%s","To":"%s","Subject":"%s", "Body":"%s" }' % (sender, msg_to, subject, body)) send_email(sender, msg_to, subject, body, content_type) log('IN', 'SENT', "") log('INFO', 'SUCCESS', msg.get('EmailThreadID')) except Exception as ex: traceback.print_exc() log('ERROR', 'EXCEPTION', str(ex)) time.sleep(1) except KeyboardInterrupt: mail_logger.info('END') break
def send_change_request(email): util.send_email(email, 'message')