def set_paid(self, value): if self.paid is False and value is True: logging.info("Order " + self.key.id() + " has been paid") Emails.order_paid(self) self.paid = value
def _process(self, args): '''Called by process() to do its work Return status of process as a string ''' cmd = args.pop(0) if cmd == 'show': validate_num_args('show', 1, args) target = args.pop(0) if target == 'missing_school_addresses': return self.schools.missingAddresses() else: return StemsibleArgsError('Unrecognized show target: %s' % target) print target elif cmd == 'email': validate_num_args('email', 1, args) target = args.pop(0) # get message_id: if target == 'message_notification': validate_num_args('email_notification', 1, args) message_id = args.pop(0) # get user: if args: try: email = args.pop(0) if email == '-': user = None else: user = self.users.getUsers({'email': email})[0] except IndexError, e: raise StemsibleArgsError('Unknown user: %s' % email) else: user = None if target == 'message_activity': self.notifications.sendMessageActivity(user) elif target == 'message_notification': self.notifications.sendMessageNotification(message_id, user) elif target == 'summary': self.notifications.sendSummary(user) elif target == 'verification': if not user: raise StemsibleArgsError('Must specific user_email') from emails import Emails Emails().send_verification_email(email) else: raise StemsibleArgsError('Unrecognized email target: %s' % target)
elif elapsed.days == 3: reminder = 'reminder_days' elif elapsed.days == 4: reminder = 'reminder_days_final' elif elapsed.days == 5: reminder = '' email_body = 'dropout' # change body to dropout if 5 days elif elapsed.days == 8: reminder = 'reminder_dropout' email_body = 'dropout' else: #includes if days == 6,7, or >8 continue footer = dt.datetime.now( ) # makes sure bottom of email isn't hidden by gmail due to repeated content email_class = Emails(reminder, email_body, survey_url, footer) html_email = email_class.make_email() text_email = email_class.make_plaintext() ###SEND EMAIL #gmail set up port = 465 smtp_server = "smtp.gmail.com" sender_email = "" password = "" #input("Type your password and press enter: ") #sussex webmail (outlook) setup #port = 465 #smtp_server = "smtp.office365.com"
def daily_quotes(): emails = Emails() emails.send_to_everyone()
def __init__(self, argv): self.email_login = Emails.get_login_from_email_address(argv[1]) self.male_names = Names.get_names("male") self.female_names = Names.get_names("female") self.main()
def __init__(self): self.conf = conf.getInstance() self.db = db.getInstance() self.users = Users() self.messages = Messages() self.email = Emails()
def emails(self): from emails import Emails return Emails()
class Notifications(object): @lazyproperty def logger(self): return logger.getLogger('Notifications') def __init__(self): self.conf = conf.getInstance() self.db = db.getInstance() self.users = Users() self.messages = Messages() self.email = Emails() def sendMessageActivity(self, user=None): '''Given a User Object, or None for all, Send Message Activity Email to user(s) Send notification about Comments on Users message or on comments to messages user has liked or commented on Since the last time run TO DO: Implement dynamtic send interval based on number of likes and comments ''' data = self._getMessageComments(user.id if user else None) for user_id in data.keys(): purge = [] user = User(user_id) print 'Email to:', data[user_id]['email'] posts = [] for message in data[user_id]['messages']: # message data mUser = User(message['message_user_id']) # comments data comments = [] for i, cid in enumerate(message['comment_ids']): cUser = User(Comment(cid).user_id) profile_url = 'http://%s/profile.py?u=%s' % \ (self.conf.baseurl, encrypt_int(cUser.id)) comments.append({'name': cUser.fullname, 'profile_image': getUserImage(cUser.id), 'profile_url': profile_url, 'text': message['comment_texts'][i]}) purge.append([user_id, cid]) # activity message message_url = 'http://%s/main.py#message_card_%s' \ % (self.conf.baseurl, message['id']) post_link = a(b('Post', style='font-size:14px'), href=message_url) orig_post = message['message_text'][0:119] if len(message['message_text']) > 120: orig_post += ' ...' if user_id == mUser.id: who = 'your' else: who = mUser.fullname + "'s" activity_msg = '%s new comment%s on %s %s<p/>%s' % \ (len(comments), 's' if len(comments) > 1 else '', who, post_link, orig_post) posts.append({ 'activity_msg': activity_msg, 'comments': comments, 'message_url': 'http://%s/main.py#message_card_%s' \ % (self.conf.baseurl, message['id']) }) html = open('%s/lib/emails/message_activity.html' % \ self.conf.basedir).read() html = Template(html) html = html.render(posts=posts) self.email.send_email(#to='*****@*****.**', to=user.email, subject='Recent activity', body='', html=html) # purge notify queue for user_id, comment_id in purge: # copy queue recors to queue_log sql = 'insert into notify_queue_log ' \ '(user_id, comment_id, created) ' \ 'select user_id, comment_id, created ' \ 'from notify_queue ' \ 'where user_id = %s and comment_id = %s' self.db.execute(sql, params=(user_id, comment_id)) # delete queue records sql = 'delete from notify_queue ' \ 'where user_id = %s and comment_id = %s' self.db.execute(sql, params=(user_id, comment_id)) def _getMessageComments(self, user_id): '''Return the following message activity Data structure: {1: # user_id {'email': '*****@*****.**', {'messages': [{id: 806, # message_id 'message_user_id': 1, 'message_text': "I'm very excited about how Stemsible", 'created': <datetime> 'comment_ids: [109, 134] 'comment_texts': ['test comment message', 'another test comment message'] ]} } } ''' data = {} # get sql user_filter = 'u.id = %s' % user_id if user_id else '1=1' sql_file = '%s/lib/sql/new_comments.sql' % self.conf.basedir sql = open(sql_file, 'r').read() % user_filter # loop thru records, tally on user_id change for row in self.db.query(sql): user_id = row['user_id'] user_email = row['user_email'] message_user_id = row['message_user_id'] message_id = row['message_id'] message_text = row['message_text'] comment_ids = row['comment_ids'].split(',') comment_texts = row['comment_texts'].split('^!^!^') if user_id not in data: data[user_id] = {'email': user_email, 'messages': []} data[user_id]['messages'].append( {'id': message_id, 'message_user_id': message_user_id, 'message_text': message_text, 'comment_ids': comment_ids, 'comment_texts': comment_texts }) return data def sendMessageNotification(self, message_id, user=None): '''Given a message_id, and a User Object, or None for all users not including original author, commenters or likers, send a Message Notification Email to user(s) with subject line: "<user.first_name> could use your help answering a question" ''' try: message = Message(message_id) except Exception, e: raise NotificationsError('Message %s not found: %s' % (message_id, e)) if user: users = [user] else: # exclude message author, commenters and likers: exclude = [message.user_id] exclude.extend([c.user_id for c in message.comments]) exclude.extend([l.user_id for l in message.likes]) filter = ("id not in (%s)" % ', '.join([str(x) for x in set(exclude)])) users = self.users.getUsers(filter) print message # mutiple possible subjects: SUBJECT1 = '%s could use your help answering a question' % \ message.user.first_name SUBJECT2 = '%s posted a link that may interest you' % \ message.user.first_name subject = SUBJECT2 profile_url = 'http://%s/profile.py?u=%s' % \ (self.conf.baseurl, encrypt_int(message.user.id)) mdata = {'notification_message': subject + '.', 'name': message.user.fullname, 'created': format_datetime(message.created), 'text': message.text, 'message_url': 'http://%s/main.py#message_card_%s' \ % (self.conf.baseurl, message.id), 'profile_image': getUserImage(message.user.id), 'profile_url': profile_url, } html = open('%s/lib/emails/message_notification.html' % \ self.conf.basedir).read() html = Template(html) html = html.render(mdata=mdata) for user in users: print 'email: %s' % (user.email) self.email.send_email(#to='*****@*****.**', to=user.email, subject=subject, body='', html=html)
# create database session Session = sessionmaker() Session.configure(bind=engine) session = Session() key_errors = 0 for email in emails: try: kw = { Emails.key_by_label[label]: value for label, value in email.items() } dt = parser.parse(kw.pop('sent_datetime')) emails_row = Emails(sent_datetime=dt, **kw) for address_type, column_name in Addresses.key_by_address_type.items(): addresses = kw.get(column_name) if addresses: for address in addresses.split(','): addresses_row = Addresses(sent_datetime=dt, sender=emails_row.message_from, send_type=address_type, sent_to=address.strip()) emails_row.addresses.append(addresses_row) session.add(emails_row) session.commit() except KeyError as k: print('KeyError in message {}: {}'.format(email, k)) key_errors += 1 except ValueError as v:
mongo = db.establish_mongo_connection(app) app.mongo = mongo # Config secret key app.secret_key = settings.secret_key # Routes app.add_url_rule('/adminnew', view_func=Admin.as_view('admin'), methods=["GET", "POST"]) app.add_url_rule('/adminnew/users', view_func=Users.as_view('users'), methods=["GET", "POST"]) app.add_url_rule('/adminnew/transactions', view_func=UserTransactions.as_view('transactions'), methods=["GET"]) app.add_url_rule('/adminnew/cronjobs', view_func=Cronjobs.as_view('cronjobs'), methods=["GET"]) app.add_url_rule('/adminnew/emails', view_func=Emails.as_view('emails'), methods=["GET"]) app.add_url_rule('/adminnew/unsubscribes', view_func=Unsubscribes.as_view('unsubscribes'), methods=["GET"]) # Run app in debug mode app.run(debug = 'TRUE')
def emails(): return Emails()
def checkForDups(self): '''-- Problem statement -- After user creates a new comment, or creates a new post -- if they immediately refresh the page (with Ctrl-R for example), the previous HTML POST data is repeated. And their data update is repeated. You can verify this is dev or staging. -- This pattern seems to be the solution; -- https://en.wikipedia.org/wiki/Post/Redirect/Get -- In the mean time we can remove duplicate entries from the database -- This query lists dupicate messages (or comments). ''' sql = ''' select u.id as user_id, concat_ws(' ', u.first_name, u.last_name) as user_fullname, m.created, m.text, m.reference_id from messages m join ( select text, count(*) from messages group by 1 having count(*) > 1 ) m2 on m.text = m2.text join users u on m.user_id = u.id order by m.text, m.id ''' from vlib.utils import format_datetime old_text = None dups = [] report = '' for row in self.db.query(sql): user_id = str(row['user_id']) user_fullname = row['user_fullname'] created = format_datetime(row['created']) text = row['text'][0:50] reference_id = str(row['reference_id']) print_rec = ', '.join( [user_id, user_fullname, created, text, reference_id]) # rec text same as last one? if old_text and text != old_text: report += '\n'.join(dups) + '\n\n' dups = [] dups.append(print_rec) old_text = text if dups: report += '\n'.join(dups) + '\n\n' dups = [] if report: from emails import Emails Emails().send_email('[email protected],[email protected]', 'Dupliate Messages Report', report)