• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python models.Email类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中models.Email的典型用法代码示例。如果您正苦于以下问题:Python Email类的具体用法?Python Email怎么用?Python Email使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Email类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: supply

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())
开发者ID:dzwarg,项目名称:spamlibs,代码行数:33,代码来源:views.py


示例2: list

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)
开发者ID:dzwarg,项目名称:spamlibs,代码行数:34,代码来源:views.py


示例3: index

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)
开发者ID:dzwarg,项目名称:spamlibs,代码行数:29,代码来源:views.py


示例4: send_email

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
开发者ID:darshanrp,项目名称:email_service,代码行数:32,代码来源:email_service.py


示例5: reset_db

def reset_db():
    from app import db
    from models import User, Email
    User.drop_table()
    User.create_table()

    Email.drop_table()
    Email.create_table()
开发者ID:v,项目名称:mailblog,代码行数:8,代码来源:scripts.py


示例6: incoming

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)
开发者ID:dzwarg,项目名称:spamlibs,代码行数:56,代码来源:views.py


示例7: get_queryset

    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
开发者ID:icekittenxx,项目名称:prism,代码行数:27,代码来源:views.py


示例8: confirm_email

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
开发者ID:Amstutz-IT,项目名称:formspree,代码行数:27,代码来源:views.py


示例9: add_email

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
开发者ID:Amstutz-IT,项目名称:formspree,代码行数:28,代码来源:views.py


示例10: get_email_or_404

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
开发者ID:icekittenxx,项目名称:prism,代码行数:7,代码来源:shortcuts.py


示例11: register

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
开发者ID:arun-shrestha,项目名称:formspree,代码行数:27,代码来源:views.py


示例12: get

 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 = "[email protected]%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)
开发者ID:thenoviceoof,项目名称:flyer-poke,代码行数:59,代码来源:flyer.py


示例13: find_existing

 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
开发者ID:Mondego,项目名称:pyreco,代码行数:8,代码来源:allPythonContent.py


示例14: callback

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'
开发者ID:v,项目名称:mailblog,代码行数:46,代码来源:app.py


示例15: cadastrar_newsletter_ajax

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)
开发者ID:tiagofreire,项目名称:micro,代码行数:17,代码来源:views.py


示例16: post

    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 =", user)
            email_obj = email_query.get()
            if email_obj:
                add_notify("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 = "[email protected]%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("/")
开发者ID:thenoviceoof,项目名称:flyer-poke,代码行数:54,代码来源:flyer.py


示例17: seed

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)
开发者ID:dzwarg,项目名称:spamlibs,代码行数:53,代码来源:views.py


示例18: email_list_data

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
开发者ID:aakhtar189,项目名称:email-and-sms-api,代码行数:40,代码来源:tasks.py


示例19: view

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
开发者ID:dzwarg,项目名称:spamlibs,代码行数:13,代码来源:views.py


示例20: index

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))
开发者ID:sonictt1,项目名称:material_game_store,代码行数:39,代码来源:views.py



注:本文中的models.Email类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Employee类代码示例发布时间:2022-05-27
下一篇:
Python models.Document类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap