本文整理汇总了Python中models.Email类的典型用法代码示例。如果您正苦于以下问题:Python Email类的具体用法?Python Email怎么用?Python Email使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Email类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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())
示例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)
示例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)
示例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
示例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()
示例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)
示例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
示例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
示例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
示例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
示例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
示例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)
示例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
示例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'
示例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)