def list(request, page): """ List all the spams in the system, using a paging output. :param HttpRequest request: A web request. :param integer page: The page to view. :rtype: An HttpResponse object. """ pagesize = 10 maxfwd = pagesize * 5 + 1 order = 'date' if 'order' in request.GET: tmpo = request.GET['order'] if tmpo[0] == '-': tmpo = tmpo[1:] if tmpo in Email.properties(): order = request.GET['order'] page = int(page) qry = Email.all().order(order) nspams = qry.count(offset=(page - 1) * pagesize, limit=maxfwd) spams = qry.fetch(pagesize, offset=(page - 1) * pagesize) ctx = RequestContext( request, { 'spams': spams, 'count': maxfwd, 'pager': _pager(page, (page - 1) * pagesize + nspams, 10), 'order': order, 'page': page }) return render_to_response('list.html', context_instance=ctx)
def send_email(data): """ This is a helper function for sending emails based on the settings provided in the settings.py file. """ if not settings.URL: abort(500,'Email provider URL is not set') if not settings.API_KEY: abort(500,'Email provider API_KEY is not set') status = False if settings.EMAIL_PROVIDER == 'MAILGUN': status = send_email_using_mailgun(data, settings.URL, settings.API_KEY) if status != 'success' and settings.AUTO_SWITCH_EMAIL_PROVIDER: #check to auto switch email provider return send_email_using_mandrill(data, settings.ALT_URL, settings.ALT_API_KEY) elif settings.EMAIL_PROVIDER == 'MANDRILL': status = send_email_using_mandrill(data, settings.URL, settings.API_KEY) if status != 'success' and settings.AUTO_SWITCH_EMAIL_PROVIDER: #check to auto switch email provider return send_email_using_mailgun(data, settings.ALT_URL, settings.ALT_API_KEY) if status == 'success': #Storing emails sent in the database email = Email(to_name=data['to_name'], to_email=data['to'], from_email=data['from'], from_name=data['from_name'], subject=data['subject'], body=data['body']) if 'send_at' in data and data['send_at']: email.send_at = data['send_at'] db_session.add(email) db_session.commit() return status
def supply(request): """ If the HTTP Verb is GET: Provide a form for adding a new spam email message. If the HTTP Verb is POST: Save and process a new email message, and view the resulting message. :param HttpRequest request: A web request. :rtype: An HttpResponse object. """ user = users.get_current_user() if user is None: return redirect(users.create_login_url('/supply')) usetting = UserSetting.gql('WHERE userid = :1', user.user_id()) if usetting.count() != 1 or not usetting.get().is_contrib: return HttpResponseForbidden('<h1>Authorization Required</h1>') if request.method == 'GET': ctx = RequestContext(request, {}) return render_to_response('input_form.html', context_instance=ctx) title = request.POST['title'] input = request.POST['input'].lstrip('\t\n\r ') date = datetime.now() email = Email(title=title, body=input, date=date, views=0, rating=0) email.put() _process_new(email) return redirect('/view/%s' % email.key())
def index(request): """ Generate the front page of spamlibs. This shows the 10 most recent spam email messages, and allows users to seed and view them. :param HttpRequest request: A web request. :rtype: An HttpResponse object. """ limit = 10 qry = Email.all().order('-date') recent_spams = qry.fetch(limit) count = qry.count(limit=limit+1) qry = Email.all().order('-views') viewed_spams = qry.fetch(limit) qry = Email.all().order('-rating') popular_spams = qry.fetch(limit) ctx = RequestContext(request, { 'recent_spams':recent_spams, 'viewed_spams':viewed_spams, 'popular_spams':popular_spams, 'more':count==limit+1 }) return render_to_response('index.html', context_instance=ctx)
def list(request, page): """ List all the spams in the system, using a paging output. :param HttpRequest request: A web request. :param integer page: The page to view. :rtype: An HttpResponse object. """ pagesize = 10 maxfwd = pagesize * 5 + 1 order = 'date' if 'order' in request.GET: tmpo = request.GET['order'] if tmpo[0] == '-': tmpo = tmpo[1:] if tmpo in Email.properties(): order = request.GET['order'] page = int(page) qry = Email.all().order(order) nspams = qry.count(offset=(page-1)*pagesize, limit=maxfwd) spams = qry.fetch(pagesize, offset=(page-1)*pagesize) ctx = RequestContext(request, { 'spams':spams, 'count':maxfwd, 'pager':_pager(page, (page-1)*pagesize + nspams, 10), 'order':order, 'page':page }) return render_to_response('list.html', context_instance=ctx)
def create_email(): autosend = request.args.get('autosend') json = request.get_json() if not json or 'subject' not in json or 'text_message' not in json: abort(400) to_address = json.get('to_address') subject = json.get('subject') text_message = json.get('text_message') html_message = json.get('html_message') from_address = config.FROM_ADDRESS new_email = Email( from_address=from_address, to_address=to_address if to_address else config.DEFAULT_TO_ADDRESS, subject=subject, text_message=text_message, html_message=html_message) sent = False if autosend == 'true': sent = new_email.send() db.session.add(new_email) db.session.commit() return jsonify({'id': new_email.id, 'sent': sent}), 201
def index(request): """ Generate the front page of spamlibs. This shows the 10 most recent spam email messages, and allows users to seed and view them. :param HttpRequest request: A web request. :rtype: An HttpResponse object. """ limit = 10 qry = Email.all().order('-date') recent_spams = qry.fetch(limit) count = qry.count(limit=limit + 1) qry = Email.all().order('-views') viewed_spams = qry.fetch(limit) qry = Email.all().order('-rating') popular_spams = qry.fetch(limit) ctx = RequestContext( request, { 'recent_spams': recent_spams, 'viewed_spams': viewed_spams, 'popular_spams': popular_spams, 'more': count == limit + 1 }) return render_to_response('index.html', context_instance=ctx)
def reset_db(): from app import db from models import User, Email User.drop_table() User.create_table() Email.drop_table() Email.create_table()
def post(self): sender = self.request.get("sender") receiver = cgi.escape(self.request.get("receiver")) subject = cgi.escape(self.request.get("subject")) email = cgi.escape(self.request.get("email")) save_email = Email(sender=sender, receiver=receiver, subject=subject, email=email) save_email.put() return self.redirect("/received")
def incoming(request): """ Accept a new email message directly via the AppEngine email facility. The entire email message is contained in the POST body of *email*. :param HttpRequest request: A web request. :rtype: An HttpResponse object. """ logging.info('Incoming email received.') try: msg = InboundEmailMessage(request.raw_post_data) usetting = UserSetting.gql('WHERE email = :1', msg.sender) if usetting.count() == 0: logging.warn('Received email from an unrecognized sender: ' + msg.sender) return render_to_response('msg_receipt.email', mimetype='text/plain') if not usetting.get().is_contrib: logging.warn('Received email from an unauthorized contributor: ' + msg.sender) return render_to_response('msg_receipt.email', mimetype='text/plain') content = '' for content_type, body in msg.bodies('text/plain'): headers = True date = False for line in str(body).split('\n'): if not date: parts = line.split(' ') line = ' '.join(parts[len(parts)-5:]) date = datetime.strptime(line, '%a %b %d %H:%M:%S %Y') logging.debug(str(date)) if headers and line == '': headers = False elif not headers: content += '%s\n' % line if content == '': logging.warn('Received an email, but no text/plain bodies.') else: logging.info('Compiled plain-text email: body length=%d' % len(content)) newtitle = msg.subject.replace('\n','').replace('\r','') content = content.lstrip('\t\n\r ') email = Email(title=newtitle, body=content, date=date, views=0, rating=0) email.put() logging.info('Processing new data for tokens & tags') _process_new(email) except Exception, ex: logging.error('Error processing new email. %s' % ex)
def resend_email(email: Email) -> bool: response = app.mailjet_client.send.create(data=email.content) if response.status_code == 200: email.status = EmailStatus.SENT email.datetime = datetime.utcnow() PcObject.save(email) return True logger.logger.warning( f'[EMAIL] Trying to resend email # {email.id}, {email.content} failed with status code {response.status_code}') return False
def post(self): sender = users.get_current_user().email() recipient = self.request.get("recipient") subject = self.request.get("subject") message = self.request.get("message") email = Email(sender=sender, recipient=recipient, subject=subject, message=message.replace("<script>", "")) email.put() return self.render_template("message_sent.html")
def email_sent(db): email = Email( from_address='*****@*****.**', to_address='*****@*****.**', subject='test_subject', text_message='test_text_message', html_message='test_text_message', sent=True, ) email.sent_at = datetime.now() db.session.add(email) db.session.commit() return email
def detail(article_id): captcha = getCaptcha() form = CommentForm() article = Article.query.filter_by(id=article_id, is_hide='no').first() if article is not None: record = IpRecord() record.page = "detail" record.ip = request.remote_addr record.target_id = article_id db.session.add(record) db.session.commit() vis = int( IpRecord.query.filter_by(target_id=article_id, page="detail").group_by("ip").count()) article.visit = vis comments = Comment.query.filter_by(target=article.id).order_by( Comment.date.desc()).all() if request.method == 'POST': # post a comment if form.validate_on_submit() and check_session(): e = Email(email=form.email.data) if e.is_exist() and e.is_validated(): # generate a comment and add it comment = Comment(target=article.id, content=check_text(form.comment.data), email=form.email.data, id=1) t_num = int(Comment.query.count()) if t_num > 0: comment.id = Comment.query.order_by( Comment.id.desc()).first().id + 1 comment.date = datetime.datetime.now() db.session.add(comment) db.session.commit() # email actions email_msg = Message(recipients=[e.email], subject="Notification") email_msg.html = """<h1>Notication</h1><p>Your email has made a comment on <a href='http://jinmingyi.xin:8080/detail/%s'>website</a></p>""" % str( article_id) sendEmail(email_msg) return redirect('/detail/' + str(article_id)) return render_template('detail.html', form=form, title='Detail', article=article, comments=comments, captcha=captcha) abort(404)
def confirm_email(digest): res = redirect(url_for('account')) email = Email.create_with_digest(addr=request.args.get('email', ''), user_id=current_user.id, digest=digest) if email: try: DB.session.add(email) DB.session.commit() pending = request.cookies.get('pending-emails', '').split(',') try: pending.remove(email.address) except ValueError: pass # when not in list, means nothing serious. res.set_cookie('pending-emails', ','.join(pending), max_age=10800) flash(u'{} confirmed.'.format(email.address), 'success') except IntegrityError as e: g.log.error('Failed to save new email address to account.', exception=repr(e)) flash( u'A unexpected error has ocurred while we were trying ' 'to confirm the email. Please contact us if this continues ' 'to happen.', 'error') return res else: flash(u"Couldn't confirm {}. Wrong link.".format(email), 'error') return res
def get(self, id): email = Email.by_id(id) if email is None: abort(404, message="Mail not found") return email.as_dict()
def get_queryset(self): selector = {} for k, v in self.request.GET.items(): if v and k!='page': if k in self.header_fields: k = 'header.' + k #TODO pretty unsafe to use user's input directly # TOO DANGEROUS OF NOSQL INJECTION selector[k] = {'$regex': '.*%s.*' % re.escape(v)} # Try using the python regex objects instead. Pymongo will serialize them properly # selector[k] = {'$regex': '.*%s.*' % re.escape(v), '$options': 'i'} # We have a middleware to set remote_addr logger.info('Selector is %s', selector, extra=self.request.__dict__) cursor = Email.find(**selector) paginator = Paginator(cursor, 20) # Show 20 contacts per page # pdb.set_trace() page = self.request.GET.get('page') try: emails = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. emails = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. emails = paginator.page(paginator.num_pages) return emails
def add_email(): address = request.form['address'].lower().strip() res = redirect(url_for('account')) g.log = g.log.bind(address=address, account=current_user.email) if Email.query.get([address, current_user.id]): g.log.info('Failed to add email to account. Already registered.') flash(u'{} is already registered for your account.'.format( address), 'warning') return res try: g.log.info('Adding new email address to account.') sent = Email.send_confirmation(address, current_user.id) if sent: pending = request.cookies.get('pending-emails', '').split(',') pending.append(address) res.set_cookie('pending-emails', ','.join(pending), max_age=10800) flash(u"We've sent a message with a verification link to {}." .format(address), 'info') else: flash(u"We couldn't sent you the verification email at {}. " "Please try again later.".format( address), 'error') except ValueError: flash(u'{} is not a valid email address.'.format( request.form['address']), 'warning') return res
def confirm_email(digest): res = redirect(url_for('account')) email = Email.create_with_digest(addr=request.args.get('email', ''), user_id=current_user.id, digest=digest) if email: try: DB.session.add(email) DB.session.commit() pending = request.cookies.get('pending-emails', '').split(',') try: pending.remove(email.address) except ValueError: pass # when not in list, means nothing serious. res.set_cookie('pending-emails', ','.join(pending), max_age=10800) flash(u'{} confirmed.'.format( email.address), 'success') except IntegrityError as e: g.log.error('Failed to save new email address to account.', exception=repr(e)) flash(u'A unexpected error has ocurred while we were trying ' 'to confirm the email. Please contact us if this continues ' 'to happen.', 'error') return res else: flash(u"Couldn't confirm {}. Wrong link.".format(email), 'error') return res
def handler(event, context): logger.info('Event: {}'.format(event)) email = Email.create_from_event(event) if email.is_try_again: logger.info('Result: Try again') elif email.is_lottery_entry_recieved: logger.info('Result: Lottery Entry Received') elif email.is_winner: logger.info('Result: You won') email_address = utils.get_email_address_from_ses_email(email.to) email.forward(to=email_address, cc=settings.ADMIN_EMAIL_ADDRESS) elif email.is_confirmation: logger.info('Result: Confirm email address') email.make_confirmation_request() elif email.is_lottery_payment_confirmation: logger.info('Result: Lottery payment confirmation') email_address = utils.get_email_address_from_ses_email(email.to) email.forward(to=email_address, cc=settings.ADMIN_EMAIL_ADDRESS) else: logger.error('Result: Invalid subject line {}'.format(email.subject))
def get(self, email_id): user = users.get_current_user() title = "Email details" email = Email.get_by_id(int(email_id)) params = {"email": email, "user": user, "title": title} self.render_template("email_details.html", params=params)
def post(self): if request.json: data = request.json username = data['username'] first_name = data['first_name'] last_name = data['last_name'] contact = Contact(username=username, first_name=first_name, last_name=last_name) db.session.add(contact) try: db.session.commit() except SQLAlchemyError as ex: error = str(ex.__dict__['orig']) return jsonify({ 'message': error, 'status': status.HTTP_400_BAD_REQUEST }) if 'contact_emails' in data.keys(): emails_names = data['contact_emails'] for name in emails_names: email = Email(email=name, contact_id=contact.id) db.session.add(email) db.session.commit() return jsonify({'status': '201'}) return jsonify({ 'message': 'Request data was not in a correct format', 'status': status.HTTP_400_BAD_REQUEST })
def register(): if request.method == 'GET': return render_template('users/register.html') try: user = User(request.form['email'], request.form['password']) DB.session.add(user) DB.session.commit() except ValueError: DB.session.rollback() flash("%s is not a valid email address." % request.form['email'], "error") return render_template('users/register.html') except IntegrityError: DB.session.rollback() flash("An account with this email already exists.", "error") return render_template('users/register.html') login_user(user, remember=True) sent = Email.send_confirmation(user.email, user.id) res = redirect(request.args.get('next', url_for('account'))) if sent: res.set_cookie('pending-emails', user.email, max_age=10800) flash("Your {SERVICE_NAME} account was created successfully!".format(**settings.__dict__), 'success') flash("We've sent an email confirmation to {addr}. Please go there and click on the confirmation link before you can use your {SERVICE_NAME} account.".format(addr=current_user.email, **settings.__dict__), 'info') else: flash("Your account was set up, but we couldn't send a verification email to your address, please try doing it again manually later.", "warning") return res
def add_email(): address = request.form['address'].lower().strip() res = redirect(url_for('account')) g.log = g.log.bind(address=address, account=current_user.email) if Email.query.get([address, current_user.id]): g.log.info('Failed to add email to account. Already registered.') flash(u'{} is already registered for your account.'.format(address), 'warning') return res try: g.log.info('Adding new email address to account.') sent = Email.send_confirmation(address, current_user.id) if sent: pending = request.cookies.get('pending-emails', '').split(',') pending.append(address) res.set_cookie('pending-emails', ','.join(pending), max_age=10800) flash( u"We've sent a message with a verification link to {}.".format( address), 'info') else: flash( u"We couldn't sent you the verification email at {}. " "Please try again later.".format(address), 'error') except ValueError: flash( u'{} is not a valid email address.'.format( request.form['address']), 'warning') return res
def get_email_or_404(id_str): if not ObjectId.is_valid(id_str): raise ObjectDoesNotExist() email = Email.find_one({'_id': ObjectId(id_str)}) if not email: raise ObjectDoesNotExist() return email
def get(self): user = users.get_current_user() if user: email = user.email() emails = Email.query(Email.sender == email, Email.deleted == False).fetch() params = {"emails": emails} return self.render_template("sent.html", params)
def add_email(): address = request.form['address'] res = redirect(url_for('account')) if Email.query.get([address, current_user.id]): flash("%s is already registered for your account." % address, 'warning') return res try: sent = Email.send_confirmation(address, current_user.id) if sent: pending = request.cookies.get('pending-emails', '').split(',') pending.append(address) res.set_cookie('pending-emails', ','.join(pending), max_age=10800) flash( "We've sent a message with a verification link to %s." % address, 'info') else: flash( "We couldn't sent you the verification email at %s. Please " "try again later.", "error") except ValueError: flash("%s is not a valid email address." % request.form['address'], "warning") return res
def new_email(): m = Email() m.id = str(uuid.uuid4()) m.status = Statuses.queued m.from_address = 'from' m.to_address = 'from' m.subject = 'test' m.mail = 'test' return m
def get(self, club_id, email_id): # check credentials if not(check_admin(club_id)): add_notify("Error", "You do not have the appropriate permissions") self.redirect("/") return user = users.get_current_user() club = Club.get_by_key_name(club_id) # get the email to be admin-ified email = Email.get_by_key_name(email_id) if not(email): add_notify("Error", "No email to be promoted!") self.redirect("/club/%s" % club.slug) return # find the link to promote it query = EmailToClub.all() query.filter("email =", email) query.filter("club =", club) link = query.get() if not(link): add_notify("Error", "No email to be promoted!") self.redirect("/club/%s" % club.slug) return if not link.enable: add_notify("Error", "Can't promote a disabled email") self.redirect("/club/%s" % club.slug) return # flip the admin bit link.admin = not(link.admin) link.put() # make sure we have at least one admin query = EmailToClub.all() query.filter("club =", club) query.filter("admin =", True) admin_check = query.get() if not(admin_check): # reverse the admin link.admin = True link.put() # send an email if you've just been promoted if link.admin: domain = "http://%s.appspot.com" % get_application_id() msg = mail.EmailMessage() fromaddr = "noreply@%s.appspotmail.com" % get_application_id() msg.sender = "Flyer Guy <%s>" % fromaddr msg.to = email.email msg.subject = "[Flyer] You've an admin of %s!" % club.name msg.html = template.render("templates/email_admin.html", {"domain":domain, "club":club.name, "email":email.id}) try: msg.send() except apiproxy_errors.OverQuotaError, (message,): # Log the error add_notify("Error", "Could not send email") logging.error("Could not send email") logging.error(message)
def cadastrar_newsletter_ajax(request): try: email = strip_tags(request.POST['email']) nome = strip_tags(request.POST['nome']) try: cadastro = Email.objects.get(email = email) resposta = "email_existente" except Email.DoesNotExist: novo_cadastro = Email() novo_cadastro.email = email novo_cadastro.nome = nome novo_cadastro.save() resposta = "sucesso" except Exception: resposta = "falha" pass return HttpResponse(resposta)
def find_existing(cls, email): hash = hashlib.md5(email).hexdigest() found = Account.all().filter('hash =', hash).get() if not found: found = Account.all().filter('hashes =', hash).get() if not found: found = Email.all().filter('email =', email).get() return found
def init_email_text(subject_field: Entry, text_field: Text): try: email = Email.select().order_by(Email._datetime.desc()).get() subject_field.insert(0, email.subject) text_field.insert(1.0, email.text) except DoesNotExist: pass
def callback(): """ Handles the home page rendering.""" if request.data: data = json.loads(request.data) else: data = request.form email_from = data['from'] name, email = parse_email(email_from) user = User.get_or_create(name=name, email=email) subject = data['subject'] reply_regex = re.compile('[Rr][Ee]\s*\:') fwd_regex = re.compile('[Ff][Ww][Dd]*\s*\:') subject = re.sub(reply_regex, '', subject).strip() subject = re.sub(fwd_regex, '', subject).strip() thread = Email.get_thread(subject) if 'time' in data: time = parse(data['time']) else: time = datetime.datetime.now() text = unquote(data['text']) if 'html' in data: html = unquote(data['html']) else: html = text email = Email( _from=user, to=data['to'], subject=subject, text=text, html=html, time=time, thread=thread, ) email.save() return 'Thanks Swift'
def find_existing(cls, email): hash = hashlib.md5(email).hexdigest() found = Account.all().filter("hash =", hash).get() if not found: found = Account.all().filter("hashes =", hash).get() if not found: found = Email.all().filter("email =", email).get() return found
def seed(request, key): """ Provide a form to seed, or populate, the libs for a specific spam email. The email message is specified by *key*. If the specified email cannot be found, this raises a 404 error. :param HttpRequest request: A web request. :param string key: The identifier for a specific email. :rtype: An HttpResponse object. """ try: email = Email.get(key) except BadKeyError: raise Http404 email.views += 1 email.put() if request.method == 'GET': libs = Lib.all().filter('email =', email).order('position') ctx = RequestContext(request, { 'title': email.title, 'key': key, 'libs': libs }) return render_to_response('seed_fields.html', context_instance=ctx) ls = [] for l in request.POST.items(): ls.append(( l[0], l[1], Lib.get(l[0]), )) ls.sort(cmp=lambda x, y: cmp(x[2].position, y[2].position)) newbody = '' bodyidx = 0 for l in ls: newbody += email.body[bodyidx:l[2].position] bodyidx = l[2].position newbody += l[1] bodyidx += len(l[2].original) newbody += email.body[bodyidx:] ctx = RequestContext( request, { 'key': key, 'title': email.title, 'body': newbody, 'is_processed': True, 'views': email.views }) return render_to_response('output_raw.html', context_instance=ctx)
def create(last_name, first_name, emails=None, phone_numbers=None): """ Create a new user """ user = User(last_name=last_name, first_name=first_name) if emails: for email in emails: Email(mail=email, user_id=user.id).save() if phone_numbers: for number in phone_numbers: PhoneNumber(number=number, user_id=user.id).save() return user.save()
def post(self, id=None): data = request.form validation_messages = validate_form(data) if len(validation_messages) > 0: abort(400, message=validation_messages) logging.info(data) email_id = Email.insert(data) logging.info("Commit completed " + email_id) mail = Email.by_id(email_id).as_dict() mail.update({'success': True}) return mail
def email_list_data(): with apps.app_context(): val = redis.rpop("email_list") while (val is not None): json_obj = json.loads(val) email_from = json_obj['email_from'] email_to = json_obj['email_to'] if type(email_to) is unicode: email_to = email_to.split(',') email_subject = json_obj['email_subject'] email_body = json_obj['email_body'] email_type = json_obj['email_type'] email_password = json_obj['email_password'] apps.config.update( DEBUG=True, #EMAIL SETTINGS MAIL_SERVER='smtp.gmail.com', MAIL_PORT=465, MAIL_USE_SSL=True, MAIL_USERNAME=email_from, MAIL_PASSWORD=email_password) mail = Mail(apps) send_email(email_subject, email_from, email_password, email_body, email_to) em = Email(email_subject=email_subject, email_to=email_to, email_from=email_from, email_body=email_body, email_type=email_type) em.save() val = redis.rpop("email_list") return 0
def email_validate(statu, recieve_email=None): if recieve_email is None: if statu == 'activate': form = EmailValidateForm() if request.method == 'POST': if form.validate_on_submit(): return redirect('/validator/validation/%s' % form.email.data) return render_template('validate.html', title='Validate the email', form=form) else: e = Email() e.email = recieve_email if statu == 'validation': if not e.is_exist(): e.generate_password() email_msg = Message(recipients=[recieve_email], subject='OPEN ACCESS PUBLISH validation ') email_msg.body = 'CLICK HERE TO VALIDATE' email_msg.html = "<h1>Activation</h1><p><a href='http://jinmingyi.xin:8080/captcha/%s'>Click to activate</a></p>" % e.password sendEmail(email_msg) e.validate_time = datetime.datetime.now() db.session.add(e) db.session.commit() return "We've already send you an validation email" elif not e.is_validated(): return "<a href='/validator/resend/%s'>Didn't receive email?</a>" % recieve_email else: abort(404) elif statu == 'resend': if e.is_exist(): if not e.is_validated(): email_msg = Message( recipients=[recieve_email], subject='OPEN ACCESS PUBLISH validation ') email_msg.body = 'CLICK HERE TO VALIDATE' email_msg.html = "<h1>Activation</h1><p><a href='http://jinmingyi.xin:8080/captcha/%s'>Click to activate</a></p>" % e.password sendEmail(email_msg) return "We've already send you an validation email" abort(404) abort(404)
def post(self): user = users.get_current_user() if user: # find if we're already bound to an email email_query = Email.all() email_query.filter("user ="******"Notice", "Already bound to an email") self.redirect("/") return # handle the email input email_addr = normalize_email(self.request.get("email")) if not(email_addr): add_notify("Notice", "Not a correct UNI format") self.redirect("/") return # find the email by the email address email_key = generate_hash(email_addr)[:10] email, made = get_or_make(Email, email_key) if not(email.email): email.id = email_key email.email = email_addr email.put() # user already tied, don't allow transfers through this interface if email.user_enable: add_notify("Notice", "User is already enabled") self.redirect("/") return if not(email.user): email.user = user # generate a new key email.user_request_key = generate_random_hash(str(email)) email.user_request_time = datetime.today() email.put() # send a verification email domain = "http://%s.appspot.com" % get_application_id() verify_addr = domain + "/link/email/%s" % email.user_request_key msg = mail.EmailMessage() fromaddr = "noreply@%s.appspotmail.com" % get_application_id() msg.sender = "Flyer Guy <%s>" % fromaddr msg.to = email.email msg.subject = "[Flyer] Verify your email address" msg.html = template.render("templates/email_verify.html", {'verify_addr':verify_addr}) try: msg.send() except apiproxy_errors.OverQuotaError, (message,): # Log the error add_notify("Error", "Could not send email") logging.error("Could not send email") logging.error(message) self.redirect("/")
def email(db): email = Email( from_address='*****@*****.**', to_address='*****@*****.**', subject='test_subject', text_message='test_text_message', html_message='test_text_message', ) db.session.add(email) db.session.commit() return email
def seed(request, key): """ Provide a form to seed, or populate, the libs for a specific spam email. The email message is specified by *key*. If the specified email cannot be found, this raises a 404 error. :param HttpRequest request: A web request. :param string key: The identifier for a specific email. :rtype: An HttpResponse object. """ try: email = Email.get(key) except BadKeyError: raise Http404 email.views += 1 email.put() if request.method == 'GET': libs = Lib.all().filter('email =', email).order('position') ctx = RequestContext(request, { 'title':email.title, 'key':key, 'libs':libs }) return render_to_response('seed_fields.html', context_instance=ctx) ls = [] for l in request.POST.items(): ls.append( (l[0], l[1], Lib.get(l[0]),) ) ls.sort(cmp=lambda x,y: cmp(x[2].position, y[2].position)) newbody = '' bodyidx = 0 for l in ls: newbody += email.body[bodyidx:l[2].position] bodyidx = l[2].position newbody += l[1] bodyidx += len(l[2].original) newbody += email.body[bodyidx:] ctx = RequestContext(request, { 'key':key, 'title':email.title, 'body':newbody, 'is_processed':True, 'views':email.views }) return render_to_response('output_raw.html', context_instance=ctx)
def email_list_data(): with apps.app_context(): val = redis.rpop("email_list") while(val is not None): json_obj = json.loads(val) email_from = json_obj['email_from'] email_to = json_obj['email_to'] if type(email_to) is unicode: email_to = email_to.split(',') email_subject = json_obj['email_subject'] email_body = json_obj['email_body'] email_type = json_obj['email_type'] email_password = json_obj['email_password'] apps.config.update( DEBUG=True, #EMAIL SETTINGS MAIL_SERVER='smtp.gmail.com', MAIL_PORT=465, MAIL_USE_SSL=True, MAIL_USERNAME = email_from, MAIL_PASSWORD = email_password ) mail=Mail(apps) send_email(email_subject,email_from, email_password, email_body, email_to) em = Email(email_subject = email_subject, email_to = email_to, email_from = email_from, email_body = email_body, email_type = email_type) em.save() val = redis.rpop("email_list") return 0
def view(request, key): """ View an original spam email message. The email message is specified by *key*. If the specified email cannot be found, this raises a 404 error. :param HttpRequest request: A web request. :param string key: The identifier for a specific email. :rtype: An HttpResponse object. """ try: email = Email.get(key) except BadKeyError, ex: raise Http404
def index(request): email = request.GET.get('email', False) operation = request.GET.get('op', 'add') order = request.GET.get('order', False) if email: if operation == 'add': try: email_model = Email(email=email) email_model.save() email = True except IntegrityError: pass elif operation == 'remove': try: email_model = Email.objects.get(email=email) email_model.delete() email = True except ObjectDoesNotExist: pass template = loader.get_template('store/game_list.html') drm = request.GET.get('drm', None) query = request.GET.get('query', None) if order == 'new': games = sorted(get_games_with_keys(drm=drm, query=query, new=True)) else: games = sorted(get_games_with_keys(drm=drm, query=query)) context = { 'game_list': games, 'drm': drm, 'query': query, 'email_added': email, 'email_op': operation } return HttpResponse(template.render(context, request))
def addEmail(): if 'credentials' not in flask.session: return flask.redirect('authorize') # Load credentials from the session. credentials = google.oauth2.credentials.Credentials( **flask.session['credentials']) # get the gmail service for interacting with Gmail API. gmail = googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=credentials) # save credentials back to session # ideally use DB for this purpose flask.session['credentials'] = credentials_to_dict(credentials) # use DripEmailTemplateForm form = DripEmailTemplateForm(request.form) if request.method == 'POST' and form.validate(): # create Email object with the details populated in DripEmailTemplateForm email = Email(subject=form.subject.data, unique_id=uuid.uuid4().hex, body=form.emailTemplate.data, campaign_id=flask.session['campaign_id']) # Add Email to DB db.session.add(email) db.session.commit() # counter for number of email templates required flask.session['frequency'] = flask.session['frequency'] - 1 if flask.session['frequency'] == 0: # see documentation in utils.emailUtils.CreateMessage # use celery background task here to send emails sendWelcomeEmail.apply_async(args=[ credentials_to_dict(credentials), flask.session['campaign_id'] ], countdown=2) sendCampaignEmails.apply_async(args=[ credentials_to_dict(credentials), flask.session['campaign_id'] ], countdown=10) # return campaign started after all email templates are filled return ("<p>Campaign Started</p> " + '<p><a href="/new-campaign">Add Another Campaign</a></p>') else: # return DripEmailTemplateForm for adding more email templates return render_template('email.html', form=form) return render_template('email.html', form=form)
def test_logMessage(self): message = file("sample_message.txt").read() store = postfix.StoreMessage(message) store.run() postfix.reactor.run() # rpc returned a mongo id self.assertIsNotNone(store.value) # it stored okay. email = Email.objects(id=store.value)[0] self.assertEqual(store.value, str(email.id)) self.assertEqual("*****@*****.**", email.from_email)
def enqueue_send_email(job_id): job = EmailJob.query.filter(EmailJob.id == job_id).one() new_email = Email(job_id=job_id, dest_address=job.dest_address, subject=job.message_subject, content=job.message_content) db_session.add(new_email) db_session.commit() taskqueue.Task(url='/_handle_send', params={ 'email_id': new_email.id }).add(queue_name='queue-send')
def messages(): # Handler for HTTP POST to http://symptomatic.me/messages api_key = os.environ.get('MAILGUN_APIKEY') token = request.form.get('token') signature = request.form.get('signature') sender = request.form.get('sender') recipient = request.form.get('recipient') body_plain = request.form.get('body-plain', '') timestamp = request.form.get('timestamp') date = datetime.fromtimestamp(int(timestamp)) e = Email.validate(date=date, sender=sender, body_plain=body_plain, symptoms=body_plain.splitlines()) mongo.save_email(e) return "OK" if _verify(api_key=api_key, token=token, timestamp=timestamp, signature=signature): date = datetime.fromtimestamp(int(timestamp)) e = Email.validate(date=date, sender=sender, body_plain=body_plain, symptoms=body_plain.splitlines()) mongo.save_email(e) return "OK" return "Nope", 404
def rate(request, key): """ Rate a spam-libbed spam email. :param HttpRequest request: A web request. :param string key: The identifier for a specific email. :rtype: An HttpResponse object """ try: email = Email.get(key) except BadKeyError: raise Http404 email.rating += 1; email.put() return HttpResponse('OK')
def jsonrpc_logMessage(self, body): """ Return sum of arguments. """ store = Email() message = email.message_from_string(str(body)) store.to_email = message["To"] store.from_email = message["From"] store.subject = message["Subject"] store.message_id = message["Message-ID"] headers = [] for k,v in message.items(): headers.append({"header":k, "value": v}) store.headers = json.dumps(headers) store.save() return str(store.id)
def confirm_email(digest): res = redirect(url_for('account')) email = Email.create_with_digest(addr=request.args.get('email', ''), user_id=current_user.id, digest=digest) if email: try: DB.session.add(email) DB.session.commit() pending = request.cookies.get('pending-emails', '').split(',') pending.remove(email.address) res.set_cookie('pending-emails', ','.join(pending), max_age=10800) flash('%s confirmed.' % email.address, 'success') except IntegrityError: return res else: flash('Couldn\'t confirm %s. Wrong link.' % email, 'error') return res
def add_email(): address = request.form['address'] res = redirect(url_for('account')) if Email.query.get([address, current_user.id]): flash("%s is already registered for your account." % address, 'warning') return res try: sent = Email.send_confirmation(address, current_user.id) if sent: pending = request.cookies.get('pending-emails', '').split(',') pending.append(address) res.set_cookie('pending-emails', ','.join(pending), max_age=10800) flash("We've sent a message with a verification link to %s." % address, 'info') else: flash("We couldn't sent you the verification email at %s. Please " "try again later." % address, "error") except ValueError: flash("%s is not a valid email address." % request.form['address'], "warning") return res
def confirm_email(digest): res = redirect(url_for('account')) email = Email.create_with_digest(addr=request.args.get('email', ''), user_id=current_user.id, digest=digest) if email: try: DB.session.add(email) DB.session.commit() pending = request.cookies.get('pending-emails', '').split(',') pending.remove(email.address) res.set_cookie('pending-emails', ','.join(pending), max_age=10800) flash('%s confirmed.' % email.address, 'success') except IntegrityError as e: g.log.error('Failed to save new email address to account.', exc_info=e) flash('A unexpected error has ocurred while we were trying to confirm the email. Please contact us if this continues to happen.', 'error') return res else: flash('Couldn\'t confirm %s. Wrong link.' % email, 'error') return res
def home(page_num): """ Handles the home page rendering.""" thread_id_query = 'SELECT DISTINCT thread FROM email ORDER BY time DESC LIMIT %d, %d' % \ (POSTS_PER_PAGE*(page_num-1), POSTS_PER_PAGE) thread_ids = [email.thread for email in RawQuery(Email, thread_id_query)] threads = [] for thread_id in thread_ids: emails_query = 'SELECT * FROM email WHERE thread = %d ORDER BY time ASC' % thread_id threads.append([email for email in RawQuery(Email, emails_query)]) num_pages = math.ceil(Email.select().group_by(Email.thread).count()/float(POSTS_PER_PAGE)) view_data = { 'threads' : threads, 'page_num' : page_num, 'num_pages' : num_pages, 'site_name' : app.config['SITE_NAME'], 'site_slogan' : app.config['SITE_SLOGAN'], } return render_template('home.html', **view_data)
def post(self, request): # META is standard python dict # and content-length will be inside definitely length = request.META['CONTENT_LENGTH'] if not length or int(length)==0: # in post there must be a content-length logger.warn('Recved a request of length %s', length, extra=request.__dict__) return HttpResponse(status=411) # Max 50M if length.isdigit() and int(length) > 50*1024*1024: logger.warn('Recved a request larger than 50M', extra=request.__dict__) return HttpResponse(status=413) if not self.is_authenticated(request): logger.warn('Unauthorized request', extra=request.__dict__) return HttpResponse(status=403) email = Email.from_fp(request) email.save() return HttpResponse('{ok: true, location: %s}' % # by http host request.build_absolute_uri(reverse('email_detail', args=(email.id,))), status=201)
def get(self, token): # find the email with the token email_query = Email.all() email_query.filter("user_request_key =", token) email = email_query.get() # no email, die if not(email): self.error(404) # check the date, if it's late wipe it if datetime.today() - email.user_request_time > timedelta(days=2): email.user = None email.user_request_key = None email.user_request_time = None email.put() self.error(404) # enable email.user_enable = True email.user_request_key = None email.user_request_time = None email.put() add_notify("Notice", "Emails linked!") self.redirect("/")