def confirm(hashid): post = JobPost.query.filter_by(hashid=hashid).first() form = forms.ConfirmForm() if post is None: abort(404) elif post.status == POSTSTATUS.REJECTED: abort(410) elif post.status == POSTSTATUS.DRAFT: if post.edit_key not in session.get('userkeys', []): abort(403) else: # Any other status: no confirmation required (via this handler) return redirect(url_for('jobdetail', hashid=post.hashid), code=302) if 'form.id' in request.form and form.validate_on_submit(): # User has accepted terms of service. Now send email and/or wait for payment if not post.email_sent: msg = Message(subject="Confirmation of your job listing at the HasGeek Job Board", recipients=[post.email]) msg.body = render_template("confirm_email.md", post=post) msg.html = markdown(msg.body) mail.send(msg) post.email_sent = True post.status = POSTSTATUS.PENDING db.session.commit() session.get('userkeys', []).remove(post.edit_key) session.modified = True # Since it won't detect changes to lists session.permanent = True return render_template('mailsent.html', post=post) return render_template('confirm.html', post=post, form=form)
def resetpassword(): form = PasswordResetForm() if form.validate_on_submit(): if form.username.data: user = Users.query.filter_by(username=form.username.data).first() elif form.email.data: user = Users.query.filter_by(email=form.email.data).first() else: flash("Username or password not in system") if user: if user.email: s = URLSafeSerializer('12fe454t') key = s.dumps([user.username, user.email]) msg = Message("Password reset", sender="*****@*****.**", recipients=[user.email]) msg.html = "<b>testing</b> \ #<a href='http://127.0.0.1:5000/passwordreset/" + key + "'>http://127.0.0.1:5000/passwordreset/" + key + "</a>" mail.send(msg) flash('Email sent to: ' + user.email) return redirect(url_for('resetpassword')) else: flash('No such user') return redirect(url_for('resetpassword')) else: flash('No such user') return redirect(url_for('resetpassword')) return render_template('general/reset_password.html', form=form)
def new_jam(): require_admin() form = NewJam() if form.validate_on_submit(): title = form.title.data new_slug = get_slug(title) if Jam.query.filter_by(slug = new_slug).first(): flash('A jam with a similar title already exists.') else: start_time = form.start_time.data new_jam = Jam(title, get_current_user(), start_time) new_jam.theme = form.theme.data new_jam.end_time = start_time + timedelta(hours = form.duration.data) new_jam.team_jam = form.team_jam.data db.session.add(new_jam) db.session.commit() flash('New jam added.') # Send out mails to all interested users. with mail.connect() as conn: participants = Participant.query.filter_by(receive_emails=True).all() for participant in participants: msg = Message("BaconGameJam: Jam \"%s\" announced" % title) msg.html = render_template("emails/jam_announced.html", jam = new_jam, recipient = participant) msg.recipients = [participant.email] conn.send(msg) flash("Email notifications have been sent.") #return render_template("emails/jam_announced.html", jam = new_jam, recipient = get_current_user()) return redirect(new_jam.url()) return render_template('new_jam.html', form = form)
def verify_send(): if request.method == 'GET': return redirect(url_for('index')) username = request.form.get('username', "") print('username = '******'s account is already validated." % participant.username.capitalize()) return redirect(url_for('index')) msg = Message("Welcome to Bacon Game Jam, " + username, recipients=[participant.email], sender=("bgj","*****@*****.**")) msg.html = render_template("emails/verification.html", recipient=participant) msg.recipients = [participant.email] mail.send(msg) flash('Verification has been resent, check your email') return redirect(url_for('verify_status', username=username))
def register(): if get_current_user(): flash("You are already logged in.") return redirect(url_for("index")) error = None form = ParticipantRegistration() if form.validate_on_submit(): username = form.username.data.strip() password = form.password.data email = form.email.data receive_emails = form.receive_emails.data new_participant = Participant(username, password, email, False, # no admin False, # is verified receive_emails) msg = Message("Welcome to Bacon Game Jam, " + username, recipients=[email], sender=("bgj","*****@*****.**")) msg.html = render_template("emails/verification.html", recipient=new_participant) msg.recipients = [new_participant.email] mail.send(msg) db.session.add(new_participant) db.session.commit() flash("Your account has been created, confirm your email to verify.") return redirect(url_for('verify_status', username=username)) return render_template('register.html', form=form, error=error)
def register(year, eventname): form = RegisterForm() event = Event.query.filter_by(name=eventname, year=year).first() if form.validate_on_submit(): participant = Participant() form.populate_obj(participant) participant.event_id = event.id participant.ipaddr = request.environ["REMOTE_ADDR"] participant.useragent = request.user_agent.string participant.email_key = uuid4().hex db.session.add(participant) db.session.commit() if not participant.email_sent: msg = Message(subject="Geekup Confirmation", recipients=[participant.email]) msg.body = render_template("confirmemail.md", participant=participant) msg.html = markdown(msg.body) mail.send(msg) participant.email_sent = True db.session.commit() return render_template("regsuccess.html") else: if request.is_xhr: return render_template("regform.html", regform=form, ajax_re_register=True) else: flash("Please check your details and try again.", "error") return eventpage(eventname, regform=form)
def send(self): if not self.recipients: raise Exception("No email recipients set.") if not self.subject: raise Exception("No email subject set.") if not self.content: raise Exception("No email content set.") if app.config["MAIL_ENABLED"]: if not app.config["MAIL_SENDER"]: raise Exception("No email sender set in config (MAIL_SENDER).") with mail.connect() as connection: for recipient in self.recipients: msg = Message(self.subject, recipients = [recipient], sender = app.config["MAIL_SENDER"]) msg.html = self.content connection.send(msg) else: print "Sending mail to: " for p in self.recipients: print " - " + p print "=" * 40 print "Mail Content:" print "=" * 40 print self.content print "=" * 40
def send_notify(notify_type, data, status=NOT_PROCESSES): """ Отсылает администации уведомления о каких-либо событиях. В админку всегда, а на почту. """ # пока поддреживаем только один тип нотификаций (о новых видосах) if notify_type != 0: raise NotImplemented(u'%s notify does not support yet') # notice = app.connection.Notice() # notice.update({'notice_type': notify_type, 'data': data, 'status': status}) # notice.save() if not Message or not mail or status != NOT_PROCESSES: return msg = Message(u'Новое видео', recipients=app.config['ADMINS']) msg.html = u""" <p>Пользователь %(username)s добавил новое видео по трюку %(trickname)s:</p> <a href="%(video_url)s" target="_blank">%(video_url)s</a> <p>Отмодерировать это дело можно в админке: <a href="%(admin_url)s" target="_blank">%(admin_url)s</a></a> """ % { 'username' : app.db.user.find_one({"_id": data["user"]})['nick'], 'trickname' : data['trickname'], 'video_url' : data['video_url'], 'admin_url' : app.config['HOST'] + '/#admin/videos/' } msg.body = "" mail.send(msg)
def register(year, eventname): form = RegisterForm() event = Event.query.filter_by(name=eventname, year=year).first() if form.validate_on_submit(): participant = Participant() form.populate_obj(participant) participant.event_id = event.id participant.ipaddr = request.environ['REMOTE_ADDR'] participant.useragent = request.user_agent.string participant.email_key = uuid4().hex db.session.add(participant) db.session.commit() if not participant.email_sent: msg = Message(subject="Geekup Confirmation", recipients=[participant.email]) msg.body = render_template("confirmemail.md", participant=participant) msg.html = markdown(msg.body) mail.send(msg) participant.email_sent = True db.session.commit() return render_template('regsuccess.html') else: if request.is_xhr: return render_template('regform.html', regform=form, ajax_re_register=True) else: flash("Please check your details and try again.", 'error') return eventpage(eventname, regform=form)
def admin_approve(key): if key and key in app.config['ACCESSKEY_APPROVE']: p = Participant.query.get(request.form['id']) if not p: status = "No such user" else: if 'action.undo' in request.form: p.approved = False status = 'Undone!' # Remove from MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listUnsubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, send_goodbye = False, send_notify = False, ) pass except MailChimpError, e: status = e.msg db.session.commit() elif 'action.approve' in request.form: p.approved = True status = "Tada!" mailsent = False # 1. Make user account and activate it user = makeuser(p) user.active = True # 2. Add to MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listSubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, merge_vars = {'FULLNAME': p.fullname, 'JOBTITLE': p.jobtitle, 'COMPANY': p.company, 'TWITTER': p.twitter, 'PRIVATEKEY': user.privatekey, 'UID': user.uid}, double_optin = False ) except MailChimpError, e: status = e.msg if e.code == 214: # Already subscribed mailsent = True # 3. Send notice of approval if not mailsent: msg = Message(subject="Your registration has been approved", recipients = [p.email]) msg.body = render_template("approve_notice.md", p=p) msg.html = markdown(msg.body) with app.open_resource("static/doctypehtml5.ics") as ics: msg.attach("doctypehtml5.ics", "text/calendar", ics.read()) mail.send(msg) db.session.commit()
def test_send_without_body(self): msg = Message(subject="testing", recipients=["*****@*****.**"]) self.assertRaises(AssertionError, self.mail.send, msg) msg.html = "<b>test</b>" self.mail.send(msg)
def send_mail(): from datetime import datetime msg = Message("Hello", sender = ("Delai.me", "*****@*****.**"), recipients=["*****@*****.**", '*****@*****.**']) #msg.body = "testing" msg.html = "<h1>testing</h1> <p>%s</p> " % datetime.now() mail.send(msg) return 'email sended'
def send_email_verify_link(useremail): """ Mail a verification link to the user. """ msg = Message(subject="Confirm your email address", recipients=[useremail.email]) msg.body = render_template("emailverify.md", useremail=useremail) msg.html = markdown(msg.body) mail.send(msg)
def edit_jam(jam_slug): require_admin() jam = Jam.query.filter_by(slug = jam_slug).first_or_404() if not 0 <= jam.getStatus().code <= 1: # editing only during the jam and before flash("The jam is over, you cannot edit it anymore.") return redirect(jam.url()) form = EditJam() if form.validate_on_submit(): # remember what has changed changes = {} changes["theme"] = [jam.theme != form.theme.data, jam.theme] changes["title"] = [jam.title != form.title.data, jam.title] changes["start_time"] = [jam.start_time != form.start_time.data, jam.start_time] title_changed = jam.title != form.title.data start_time_changed = jam.start_time != form.start_time.data # change the options jam.theme = form.theme.data jam.title = form.title.data jam.start_time = form.start_time.data db.session.commit() changed = (changes["theme"][0] or changes["title"][0] or changes["start_time"][0]) if not changed: flash("Nothing has changed. Keep moving!") else: # inform users about change if form.email.data: with mail.connect() as conn: participants = Participant.query.filter_by(receive_emails=True).all() for participant in participants: msg = Message("BaconGameJam: Jam \"%s\" changed" % changes["title"][1]) msg.html = render_template("emails/jam_changed.html", jam = jam, changes = changes, recipient = participant) msg.recipients = [participant.email] conn.send(msg) flash("Email notifications have been sent.") flash("The jam has been changed.") return redirect(jam.url()) elif request.method != "POST": form.title.data = jam.title form.theme.data = jam.theme form.start_time.data = jam.start_time return render_template('edit_jam.html', jam = jam, form = form)
def save(data, stats): if not data: return stats src = data['meta']['source'] res = db.dossiers2.find_one({'meta.source': src}) or {} d = diff( dict([(k, v) for k, v in res.items() if not k in ['_id', 'meta', 'changes']]), dict([(k, v) for k, v in data.items() if not k in [ '_id', 'meta', 'changes', ]])) #logger.warn(pprint.pformat(d)) if d: now = datetime.datetime.utcnow().replace(microsecond=0).isoformat() if not res: logger.info(('adding %s - %s' % (data['procedure']['reference'], data['procedure']['title'])).encode('utf8')) data['meta']['created'] = data['meta']['timestamp'] del data['meta']['timestamp'] sys.stdout.flush() stats[0] += 1 else: logger.info(('updating %s - %s' % (data['procedure']['reference'], data['procedure']['title'])).encode('utf8')) data['meta']['updated'] = data['meta']['timestamp'] del data['meta']['timestamp'] sys.stdout.flush() stats[1] += 1 data['_id'] = res['_id'] logger.info(jdump(d)) m = db.notifications.find({'dossiers': data['procedure']['reference']}, ['active_emails']) for g in m: if len(g['active_emails']) == 0: continue msg = Message( "[PT] %s %s" % (data['procedure']['reference'], data['procedure']['title']), sender="*****@*****.**", bcc=g['active_emails']) msg.html = htmldiff(data, d) msg.body = makemsg(data, d) mail.send(msg) #logger.info(htmldiff(data,d)) #logger.info(makemsg(data,d)) data['changes'] = res.get('changes', {}) data['changes'][now] = d db.dossiers2.save(data) return stats
def approve(key): if key and key in app.config['ACCESSKEY_APPROVE']: p = Participant.query.get(request.form['id']) if not p: status = 'No such user' else: if 'action.undo' in request.form: p.approved = False status = 'Undone!' # Remove from MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listUnsubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, send_goodbye = False, send_notify = False, ) pass except MailChimpError, e: status = e.msg db.session.commit() elif 'action.approve' in request.form: p.approved = True status = "Tada!" mailsent = False # 1. Add to MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listSubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, merge_vars = {'FULLNAME': p.fullname, 'JOBTITLE': p.jobtitle, 'COMPANY': p.company, 'TWITTER': p.twitter}, double_optin = False ) except MailChimpError, e: status = e.msg if e.code == 214: # Already subscribed mailsent = True # 2. Send notice of approval if not mailsent: msg = Message(subject="Your registration has been approved", recipients = [p.email]) msg.body = render_template("approve_notice.md", p=p) msg.html = markdown(msg.body) mail.send(msg) db.session.commit()
def send_activation_email(self, view): """Send the e-mail that allows a user to activate their account.""" if not self.reg_code: self._gen_reg_code() db.session.commit() msg = Message("Account Activation", recipients=[self.email]) print self.reg_code activate_url = url_for(view, user_id=self.id, reg_code=self.reg_code, _external=True) msg.html = render_template('email_activate.html', user=self, activate_url=activate_url) msg.body = render_template('email_activate.txt', user=self, activate_url=activate_url) mail.send(msg)
def save(data, stats): src = data["meta"]["source"] res = db.dossiers2.find_one({"meta.source": src}) or {} d = diff( dict([(k, v) for k, v in res.items() if not k in ["_id", "meta", "changes"]]), dict([(k, v) for k, v in data.items() if not k in ["_id", "meta", "changes"]]), ) # logger.warn(d) if d: now = datetime.datetime.utcnow().replace(microsecond=0).isoformat() if not res: logger.info( ("adding %s - %s" % (data["procedure"]["reference"], data["procedure"]["title"])).encode("utf8") ) data["meta"]["created"] = data["meta"]["timestamp"] del data["meta"]["timestamp"] sys.stdout.flush() stats[0] += 1 else: logger.info( ("updating %s - %s" % (data["procedure"]["reference"], data["procedure"]["title"])).encode("utf8") ) data["meta"]["updated"] = data["meta"]["timestamp"] del data["meta"]["timestamp"] sys.stdout.flush() stats[1] += 1 data["_id"] = res["_id"] # print >> sys.stderr, (d) m = db.notifications.find({"dossiers": data["procedure"]["reference"]}, ["active_emails"]) for g in m: if len(g["active_emails"]) == 0: continue msg = Message( "[PT] %s %s" % (data["procedure"]["reference"], data["procedure"]["title"]), sender="*****@*****.**", bcc=g["active_emails"], ) msg.html = htmldiff(data, d) msg.body = makemsg(data, d) mail.send(msg) data["changes"] = res.get("changes", {}) data["changes"][now] = d db.dossiers2.save(data) return stats
def sendCookingReminder(): print "sending cooking reminder" invitationId = flask.request.args.get('invitationId') userId = flask.request.args.get('userId') isToday = flask.request.args.get('isToday', 'no') if not invitationId: return "invitation not found" if not userId: return "user not found" invitation = db.invitations.find_one({'_id' : ObjectId(invitationId)}) userInfo = db.users.find_one({'_id': ObjectId(userId)}) localDt = naiveLocalDatetimeForUser(invitation['datetime'], userInfo) readableDate = localDt.strftime("%A, %B %d, %Y") readableTime = localDt.strftime("%l:%M %p").strip() if userInfo.get('tzname'): readableTime += ' ' + userInfo['tzname'] invitation['readableDate'] = readableDate invitation['readableTime'] = readableTime # grab a list of all attendees attendeeIds = [invitation['hostId']] + [reply['userId'] for reply in invitation['replies'] if reply['mainReply'] == 'yes'] attendees = [db.users.find_one({'_id': ObjectId(aId)}) for aId in attendeeIds] # grab recipe ingredients to send along mealInfo = db.meals.find_one({'slug' : invitation['meal']}) # compose and send email to the user email = Message("Get Ready to Cook!", recipients=[userInfo['email']], sender=emailSenderInfo) message = render_template('email/reminder.html', invitation=invitation, attendees=attendees, meal=mealInfo, recipient=userInfo, isToday=isToday) email.html = message print message mail.send(email) return "reminder email sent!"
def sendSimpleInvitation(): data = flask.request.form print data['message'] invitation = { 'message' : data['message'], 'inviteeName' : data['inviteeName'] } if 'yourName' in data: newUserInfo = { 'name' : data['yourName'], 'email' : data['yourEmail'] } emailSenderInfo = (data['yourName'], data['yourEmail']) else: newUserInfo = {} user = db.users.find_one({'_id' : ObjectId(flask.session['userId'])}) emailSenderInfo = (user['name'], user['email']) if data['meal'] != '': meal = db.meals.find_one({'slug' : data['meal']}) mealInfo = { 'title' : meal['title'], 'shortDescription' : meal['shortDescription'], 'slug' : meal['slug'] } else: mealInfo = 'none' # compose email to send email = Message("Let's cook on Hotpot", recipients=[data['inviteeEmail']], sender=emailSenderInfo) # TODO: if recipient has an account, translate to their TZ invitationMessage = render_template('email/invitationSimple.html', meal=mealInfo, invitation=invitation) email.html = invitationMessage mail.send(email) return render_template('inviteSimpleSent.html', invitationMessage=invitationMessage, invitation=invitation, newUserInfo=newUserInfo)
def send_activation_email(self): """Send the e-mail that allows a user to activate their account.""" if not self.reg_code: self._gen_reg_code() db.session.commit() msg = Message("Account Activation", recipients=[self.email]) print self.reg_code activate_url = url_for('frontend.activate', user_id=self.id, reg_code=self.reg_code, _external=True) msg.html = render_template('email_activate.html', user=self, activate_url=activate_url) msg.body = render_template('email_activate.txt', user=self, activate_url=activate_url) mail.send(msg)
def save(data, stats): if not data: return stats src=data['meta']['source'] res=db.dossiers2.find_one({ 'meta.source' : src }) or {} d=diff(dict([(k,v) for k,v in res.items() if not k in ['_id', 'meta', 'changes']]), dict([(k,v) for k,v in data.items() if not k in ['_id', 'meta', 'changes',]])) #logger.warn(pprint.pformat(d)) if d: now=datetime.datetime.utcnow().replace(microsecond=0).isoformat() if not res: logger.info(('adding %s - %s' % (data['procedure']['reference'],data['procedure']['title'])).encode('utf8')) data['meta']['created']=data['meta']['timestamp'] del data['meta']['timestamp'] sys.stdout.flush() stats[0]+=1 else: logger.info(('updating %s - %s' % (data['procedure']['reference'],data['procedure']['title'])).encode('utf8')) data['meta']['updated']=data['meta']['timestamp'] del data['meta']['timestamp'] sys.stdout.flush() stats[1]+=1 data['_id']=res['_id'] logger.info(jdump(d)) m=db.notifications.find({'dossiers': data['procedure']['reference']},['active_emails']) for g in m: if len(g['active_emails'])==0: continue msg = Message("[PT] %s %s" % (data['procedure']['reference'],data['procedure']['title']), sender = "*****@*****.**", bcc = g['active_emails']) msg.html = htmldiff(data,d) msg.body = makemsg(data,d) mail.send(msg) #logger.info(htmldiff(data,d)) #logger.info(makemsg(data,d)) data['changes']=res.get('changes',{}) data['changes'][now]=d db.dossiers2.save(data) return stats
def send(self, conn=None): """ Sends a message and marks it as sent """ msg = Message(recipients=self.recipients, sender=self.sender, subject=self.subject) if self.is_plain: msg.body = self.message else: msg.html = self.message # Obfuscate the log masked_recipients = self._get_masked_recipients() app.logger.info("MAIL: %s: %s" % (masked_recipients, self.subject)) app.logger.debug("Sending mail to %s: %s\n%s" % (masked_recipients, self.subject, self.message)) if conn is None: with app.mail.connect() as conn: conn.send(msg) else: conn.send(msg) # Mark as sent self.is_sent = True self.save()
def message(): if request.method == 'POST': name = request.form['fullname'] email = request.form['email'] timedelta = datetime.timedelta(hours=0) starts = request.form['starts'] if starts.endswith('AM'): starts = starts.rstrip('AM') timedelta = datetime.timedelta(hours=5) elif starts.endswith('PM'): starts = starts.rstrip('PM') timedelta = datetime.timedelta(hours=17) t_stripped = time.strptime(starts, '%m-%d-%Y %H:%M') d = datetime.datetime(t_stripped.tm_year, t_stripped.tm_mon, t_stripped.tm_mday, t_stripped.tm_hour, t_stripped.tm_min) d_shifted = d + timedelta starts_formatted = d_shifted.strftime("%Y%m%dT%H%M00Z") hourlong_timedelta = datetime.timedelta(hours=1) ends_d_shifted = d_shifted + hourlong_timedelta ends_formatted = ends_d_shifted.strftime("%Y%m%dT%H%M00Z") """ends = request.form['ends'] if ends.endswith('AM'): ends = ends.rstrip('AM') timedelta = datetime.timedelta(hours=5) elif ends.endswith('PM'): ends = ends.rstrip('PM') timedelta = datetime.timedelta(hours=17) t_stripped = time.strptime(ends, '%m-%d-%Y %H:%M') d = datetime.datetime(t_stripped.tm_year, t_stripped.tm_mon, t_stripped.tm_mday, t_stripped.tm_hour, t_stripped.tm_min) d_shifted = d + timedelta ends_formatted = d_shifted.strftime("%Y%m%dT%H%M00Z")""" date1 = starts_formatted #'20120301T240000Z' date2 = ends_formatted #'20120303T270000Z' headline = request.form['headline'] details = request.form['details'] if (request.form['website'].strip() != ""): headline += ' (' + request.form['website'] + ')' params = { 'action' : 'TEMPLATE', 'text' : headline, 'dates' : date1 + '/' + date2, 'location' : request.form['location'], 'details' : details, 'prop' : 'name:eclubform' } #add_gcal_url = 'http://www.google.com/calendar/event?action=TEMPLATE' + '&text=' + headline + '&dates=' + date_time + '&location=' + location + '&details=' + announcement + '&prop=name:eclubform' #params = { 'name' : 'ryan', 'age' : 21 } utf_params = {} for k, v in params.iteritems(): utf_params[k] = unicode(v).encode('utf-8') query = urllib.urlencode(utf_params) parts = ['http', 'www.google.com', '/calendar/event', '', query, ''] add_to_gcal_url = urlparse.urlunparse(parts) messageText = '' messageText += '<h3>' + name + ' (' + email + ') just submitted an announcement to be added to the events calendar.</h3>' messageText += '<p>Title: ' + headline + '</p><p>Description: ' + details + '</p>' messageText += '<h2><a href="' + add_to_gcal_url + '">Add to Calendar</a></h2>' message_subject = "New Announcement Submission: " + headline # send mail msg = Message(message_subject, sender=org_email, recipients=[recipient_of_cal_emails]) msg.html = messageText #print msg mail.send(msg) return render_template('submission_confirmation.html', org_name=org_name) else: return render_template('submit_announcement.html', org_name=org_name)
def send_password_reset_link(email, user, secret): msg = Message(subject="Reset your password", recipients=[email]) msg.body = render_template("emailreset.md", user=user, secret=secret) msg.html = markdown(msg.body) mail.send(msg)
def sendInvitation(): data = flask.request.form user = db.users.find_one({'_id' : ObjectId(flask.session['userId'])}) # look up whether invited friend already exists as a user invitee = db.users.find_one({'email' : data['inviteeEmail']}) # if user exists, then use their ID code as identifier; otherwise use their name + email address # NOTE: throughout the system, lack of userId indicates that user is not registered if invitee is not None: inviteeId = str(invitee['_id']) else: inviteeId = data['inviteeEmail'] # construct new invitation document based on incoming form data and info above newInvitation = { "status" : "accepted", "hostId" : flask.session['userId'], "inviteeIds" : [inviteeId], # this is an array! "datetime" : int(data['datetime']), "sendDate" : time.time(), "meal" : data['meal'], "readableTime": data['readableTime'], "readableDate": data['readableDate'], "message" : "", "tzoffset": 300, "tzname": "EST", "itsHappening" : True } # get timezone info from form and store it in the database tzinfo = data.get('tzinfo', '').split() if len(tzinfo) and tzinfo[0].isdigit(): newInvitation['tzoffset'] = int(tzinfo[0]) if len(tzinfo) == 2 and len(tzinfo[1]) == 3: # e.g. EST, PDT newInvitation['tzname'] = tzinfo[1] # insert into database newInvitationId = db.invitations.insert(newInvitation) # add some extra info that's needed by the email template, but which we don't need stored in the database # NOTE: assuming for now there is only one friend! (even though the document has an array for 'friendIds') newInvitation['hostName'] = user['name'] newInvitation['hostEmail'] = user['email'] newInvitation['inviteeName'] = data['inviteeName'] newInvitation['inviteeId'] = inviteeId # other stuff that's needed by the template meal = db.meals.find_one({'slug' : newInvitation['meal']}) # compose email to send email = Message("Your friend created a Cooking Room for you", recipients=[data['inviteeEmail']], sender=emailSenderInfo) # TODO: if recipient has an account, translate to their TZ invitationMessage = render_template('email/cookingRoomCreated.html', meal=meal, invitation=newInvitation) email.html = invitationMessage mail.send(email) flask.flash('New Cooking Room was successfully created and notifications were sent to invitees. Hooray!') return flask.redirect('/cookingRooms/' + str(newInvitationId))
def admin_approve(edition): if request.method == 'GET': tz = timezone(app.config['TIMEZONE']) return render_template( 'approve.html', participants=Participant.query.filter_by(edition=edition), utc=utc, tz=tz, enumerate=enumerate, edition=edition) elif request.method == 'POST': p = Participant.query.get(request.form['id']) if not p: status = "No such user" else: if 'action.undo' in request.form: p.approved = False p.user = None status = 'Undone!' # Remove from MailChimp if MailChimp is not None and app.config[ 'MAILCHIMP_API_KEY'] and app.config[ 'MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listUnsubscribe( id=app.config['MAILCHIMP_LIST_ID'], email_address=p.email, send_goodbye=False, send_notify=False, ) pass except MailChimpError, e: status = e.msg db.session.commit() elif 'action.approve' in request.form: if p.approved: status = "Already approved" else: # Check for dupe participant (same email, same edition) dupe = False for other in Participant.query.filter_by(edition=p.edition, email=p.email): if other.id != p.id: if other.user: dupe = True break if dupe == False: p.approved = True status = "Tada!" # 1. Make user account and activate it user = makeuser(p) user.active = True # 2. Add to MailChimp if MailChimp is not None and app.config[ 'MAILCHIMP_API_KEY'] and app.config[ 'MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) addmailchimp(mc, p) # 3. Send notice of approval msg = Message( subject="Your registration has been approved", recipients=[p.email]) msg.body = render_template("approve_notice_%s.md" % edition, p=p) msg.html = markdown(msg.body) with app.open_resource("static/doctypehtml5-%s.ics" % edition) as ics: msg.attach("doctypehtml5.ics", "text/calendar", ics.read()) mail.send(msg) db.session.commit() else: status = "Dupe" else: status = 'Unknown action'
def createUser(self, user): msg = Message("Bienvenido a Enjoy-events", recipients=[user.email]) msg.html = self.lookup.get_template("registration.html").render( user=user) self.sendMail(msg)
def assistance(self, assistance, user): msg = Message("Vas a asistir al evento %s" % assistance.event.name, recipients=[user.email]) msg.html = self.lookup.get_template("assistance.html").render( assistance=assistance) self.sendMail(msg)
def admin_approve(edition): if request.method == 'GET': tz = timezone(app.config['TIMEZONE']) return render_template('approve.html', participants=Participant.query.filter_by(edition=edition), utc=utc, tz=tz, enumerate=enumerate, edition=edition) elif request.method == 'POST': p = Participant.query.get(request.form['id']) if not p: status = "No such user" else: if 'action.undo' in request.form: p.approved = False p.user = None status = 'Undone!' # Remove from MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listUnsubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, send_goodbye = False, send_notify = False, ) pass except MailChimpError, e: status = e.msg db.session.commit() elif 'action.approve' in request.form: if p.approved: status = "Already approved" else: # Check for dupe participant (same email, same edition) dupe = False for other in Participant.query.filter_by(edition=p.edition, email=p.email): if other.id != p.id: if other.user: dupe = True break if dupe == False: p.approved = True status = "Tada!" # 1. Make user account and activate it user = makeuser(p) user.active = True # 2. Add to MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) addmailchimp(mc, p) # 3. Send notice of approval msg = Message(subject="Your registration has been approved", recipients = [p.email]) msg.body = render_template("approve_notice_%s.md" % edition, p=p) msg.html = markdown(msg.body) with app.open_resource("static/doctypehtml5-%s.ics" % edition) as ics: msg.attach("doctypehtml5.ics", "text/calendar", ics.read()) mail.send(msg) db.session.commit() else: status = "Dupe" else: status = 'Unknown action'
def createUser(self, user): msg = Message("Bienvenido a Enjoy-events", recipients=[user.email]) msg.html = self.lookup.get_template("registration.html").render(user=user) self.sendMail(msg)
def sendReply(): data = flask.request.form invitation = db.invitations.find_one({'_id' : ObjectId(data['id'])}) # grab all the form data and stuff it into a dictionary replyInfo = { "userId" : flask.session['userId'], "mainReply" : data['mainReply'], "message" : data['message'] } # include extra info only if available if data['mainReply'] == "maybe": if data['altTimes'] != "": replyInfo["altTimes"] = data['altTimes'] if data['altMeals'] != "": replyInfo["altMeals"] = data['altMeals'] # if there aren't any replies stored yet, make an array to store them! if 'replies' not in invitation: # print 'no replies yet' invitation['replies'] = [] invitation['replies'].append(replyInfo) # else, there are replies! so check if there already is one from this user for this invitation # TODO: there is a little inconsistency here... when accessing the RSVP form, # it won't let you reply if you already did, # but the code below also handles the case in which you overwrite an existing reply. # ...must fix someday.......... else: replyFoundAt = -1 # search for invitee's own reply, if it exists for (index, reply) in enumerate(invitation['replies']): if reply['userId'] == flask.session['userId']: replyFoundAt = index # this means invitee's own reply was found # in that case, instead of creating a new entry, we should overwrite it if replyFoundAt != -1: # overwriting reply invitation['replies'][replyFoundAt] = replyInfo else: # appending reply invitation['replies'].append(replyInfo) # set status of invitation # TODO: this logic needs to be fixed major big time for multiple invitees, # because if a second person replies, it will just overwrite the status of the first person # Right now it works fine for just one invitee... if replyInfo['mainReply'] == "yes": invitation['status'] = "accepted" # also, set a flag in the database to indicate that the cooking's happening. # [insert Carrie voice: "It's HAPPENING!" invitation['itsHappening'] = True elif replyInfo['mainReply'] == 'maybe': invitation['status'] = 'changeNeeded' elif replyInfo['mainReply'] == 'no': invitation['status'] = 'declined' # store updated invitation entry back in database db.invitations.save(invitation) # grab host email address hostEmail = db.users.find_one({'_id' : ObjectId(invitation['hostId'])})['email'] # grab invitee info invitee = db.users.find_one({'_id' : ObjectId(flask.session['userId'])}) inviteeInfo = { 'name' : invitee['name'], 'userpic' : invitee['userpic'], 'email' : invitee['email'] } if 'lastname' in invitee: inviteeInfo['lastname'] = invitee['lastname'] # grab meal info meal = db.meals.find_one({'slug' : invitation['meal']}) mealInfo = { '_id' : str(meal['_id']), 'title' : meal['title'], 'ingredients' : meal['ingredients'], 'slug' : meal['slug'] } # grab invitation info invitationInfo = { '_id' : invitation['_id'], 'readableDate' : invitation['readableDate'], 'readableTime' : invitation['readableTime'] } # compose and send email back to host # email = Message("Hotpot RSVP", recipients=[hostEmail], sender=emailSenderInfo) replyMessage = render_template('email/replyToHost.html', reply=replyInfo, invitee=inviteeInfo, invitation=invitationInfo, meal=mealInfo) #email.html = replyMessage #mail.send(email) host = db.users.find_one({'_id' : ObjectId(invitation['hostId'])}) hostInfo = { 'name' : host['name'], 'userpic' : host['userpic'] } # if reply was a yes... if replyInfo['mainReply'] == "yes": # also send the invitee a confirmation invitee = db.users.find_one({'_id' : ObjectId(replyInfo['userId'])}) inviteeEmail = invitee['email'] # calculate the cooking time in the invitee's locale localDt = naiveLocalDatetimeForUser(invitation['datetime'], invitee) # make a copy so we can modify it for the invitee confirmationInfo = dict(invitationInfo) confirmationInfo['readableDate'] = localDt.strftime("%A, %B %d, %Y") readableTime = localDt.strftime("%l:%M %p").strip() if invitee.get('tzname'): readableTime += ' ' + invitee['tzname'] confirmationInfo['readableTime'] = readableTime email = Message("Hotpot RSVP Confirmation", recipients=[inviteeEmail], sender=emailSenderInfo) email.html = render_template('email/RSVPConfirmation.html', reply=replyInfo, host=hostInfo, invitation=invitationInfo, meal=mealInfo) mail.send(email) # check whether this invitation is for something happening on the same day. # if so, send out a "reminder" email for today (b/c the reminder emails contain the link to the room) currentTime = time.time(); # TODO: this is a VERY naive implementation whereby we consider something 'same day' if it's less than 12 hrs from now # obviously this wouldn't make sense if we sent the invite at 9pm for 8am the next day... # but since i haven't figured out time zones yet, this will have to do for now. if invitation['datetime'] <= currentTime+43200: print "oh we're cooking on the same day? cool." if 'reminderSent' not in invitation: invitation['reminderSent'] = True db.invitations.save(invitation) print "calling send cooking reminder" # have to set a timer to make a request on a separate thread, or else we get a request timeout def sendCookingReminderAfterWaitingOneSecond(): urllib2.urlopen(config.LOCAL_URL + '/sendCookingReminder?invitationId=' + str(invitation['_id']) + '&today=yes').read() timer = threading.Timer(1, sendCookingReminderAfterWaitingOneSecond) timer.start() return render_template('replySent.html', replyMessage=replyMessage, host=hostInfo, invitation=invitation)
def assistance(self, assistance, user): msg = Message("Vas a asistir al evento %s" % assistance.event.name, recipients=[user.email]) msg.html = self.lookup.get_template("assistance.html").render(assistance=assistance) self.sendMail(msg)
def aboutme(): #pn_salt = 'd786dff79a90' #email_salt = 'b2832fa81995' correct_phone_hash = 'YKHeeo7VOTo/OTI9Q+fPy/UUirw=' email_hash1 = 'UYTI6hPxlbUROrPG8L6DRh2gvdo=' email_hash2 = 'eWnrgcZ7f6h7dRjgCm1DjJRPQQY=' email_hash3 = 'SYk+FeQ18NpWPwve4tK8C/0gAfE=' phone_number = "" email = "" # grab unverified_phone_number = request.args.get('phone_number', '') s1 = request.args.get('s1', '') unverified_email = request.args.get('email', '') s2 = request.args.get('s2', '') # verifying phone number hash1 = SHA.new() hash1.update(str(s1) + str(unverified_phone_number)) if (base64.b64encode(hash1.digest()) == correct_phone_hash): phone_number = unverified_phone_number # verifying email address hash2 = SHA.new() hash2.update(str(s2) + str(unverified_email)) b = base64.b64encode(hash2.digest()) if (b == email_hash1 or b == email_hash2 or b == email_hash3): email = unverified_email # capture encrypted and base64-encoded parameter # if no viewer tracking id is present, stop and render the template i1 = request.args.get('i1', '') encrypted_name = i1 i2 = request.args.get('i2', '') encrypted_email = i2 if (len(encrypted_name) < 1) or (len(encrypted_email) < 1): return render_template('aboutme.html', email=email, phone_number=phone_number) # parse url options a1 = request.args.get('a1', '') show_welcome_popup = False if a1 is "1": show_welcome_popup = True a2 = request.args.get('a2', '') send_welcome_email = False if a2 == "1": send_welcome_email = True # base64 decoding name try: encrypted_name = base64.urlsafe_b64decode(str(encrypted_name)) except: print "base64 decoding... invalid URL attempted (name)" return render_template('aboutme.html', email=email, phone_number=phone_number) # base64 decoding email try: encrypted_email = base64.urlsafe_b64decode(str(encrypted_email)) except: print "base64 decoding... invalid URL attempted (email)" return render_template('aboutme.html', email=email, phone_number=phone_number) # ensuring parameter is 16 characters for decryption if (len(encrypted_name) != 16) or (len(encrypted_email) != 64): print "checking length of string... invalid URL attempted" return render_template('aboutme.html', email=email, phone_number=phone_number) # decrypting name and email obj = AES.new('ball so hard808s', AES.MODE_ECB) decrypted_name = obj.decrypt(encrypted_name) decrypted_email = obj.decrypt(encrypted_email) # stripping parameter of whitespace decrypted_name = string.rstrip(decrypted_name) decrypted_email = string.rstrip(decrypted_email) if (re.match(regex_name, decrypted_name)) and (re.match(regex_email, decrypted_email)): # our name and email is now verified - let's do some fun stuff # log our visitor print "#####_____##### " + decrypted_name + " (" + decrypted_email + ")" + " just visited your about page #####_____#####" # send our visitor a thank you for visiting our page if send_welcome_email: message_html = '<p>' + decrypted_name + ', thank you for visiting my about page!' + '</p>' msg = Message("Thank you for visiting my about page!", sender=("Ryan Shea's Mailbot", "*****@*****.**"), recipients=[decrypted_email]) #msg.html = message_text msg.html = message_html #print "sending welcome email... To: " + str(msg.recipients) mail.send(msg) else: print "invalid URL attempted" return render_template('aboutme.html', email=email, phone_number=phone_number, show_welcome_popup=show_welcome_popup)