本文整理汇总了Python中utils.send_email函数的典型用法代码示例。如果您正苦于以下问题:Python send_email函数的具体用法?Python send_email怎么用?Python send_email使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了send_email函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: proc_prevmonth
def proc_prevmonth(cfg):
"""
Put together metrics for the previous month then
email the results out
:param cfg: database connection info
:type cfg: dict
"""
msg = ''
emails = get_addresses(cfg)
rng = date_range()
subject = EMAIL_SUBJECT.format(rng[0], rng[1])
try:
infodict = calc_dlinfo(LOG_FILE)
msg = download_boiler(infodict)
for source in ORDER_SOURCES:
infodict = db_orderstats(source, rng[0], rng[1], cfg)
infodict.update(db_scenestats(source, rng[0], rng[1], cfg))
infodict['tot_unique'] = db_uniquestats(source, rng[0], rng[1], cfg)
infodict['who'] = source.upper()
msg += ondemand_boiler(infodict)
infodict = db_prodinfo(cfg, rng[0], rng[1])
msg += prod_boiler(infodict)
except Exception:
exc_msg = str(traceback.format_exc()) + '\n\n' + msg
send_email(emails[1], emails[2], subject, exc_msg)
msg = 'There was an error with statistics processing.\n' \
'The following has been notified of the error: {0}.'.format(', '.join(emails[2]))
finally:
send_email(emails[1], emails[0], subject, msg)
示例2: register
def register():
if not current_user.is_anonymous:
return redirect(url_for('main.index'))
form = form_class.RegistrationForm()
if form.validate_on_submit():
ki = gpg.import_keys(form.pgp.data)
if not ki.fingerprints:
fingerp = "--- NO VALID PGP ---"
else:
fingerp = ki.fingerprints[0]
user = models.User(email=escape(form.email.data),
name=escape(form.name.data),
affiliation=escape(form.affiliation.data),
pgp=escape(form.pgp.data),
password=form.password.data,
fingerprint=fingerp)
models.db.session.add(user)
models.db.session.commit()
syslog.syslog(syslog.LOG_NOTICE, "New user registered: " + form.email.data)
token = user.generate_confirmation_token()
send_email(user.email,
'CVE-PORTAL -- Account Confirmation',
'/emails/confirm',
user=user,
token=token)
flash('A confirmation email has been sent to you by email.', 'info')
return redirect('/login')
else:
if form.email.data is not None:
pass
# syslog.syslog(syslog.LOG_ERR, "Registering Failed: Email: " + form.email.data + " Name: " + form.name.data + " Affiliation: " + form.affiliation.data)
return render_template("auth/register.html", form=form)
示例3: reject
def reject(db, user, id):
try:
item = db.query(model.Restriction).filter_by(id=id).one()
item.state = 'REJECTED'
item.approver = user
db.flush()
# email user the restriction was rejected
reason = request.forms.reason.strip()
if reason:
tpl = 'mail_restriction_rejected_reason'
else:
tpl = 'mail_restriction_rejected'
subject = config.restriction_rejected_email_subject
body = template(
tpl,
site_name=config.site_name,
site_url=config.site_url,
id=item.id,
slug=slug(item.title),
reason=reason
)
send_email(item.user.email, subject, body)
except NoResultFound:
return HTTPError(404, 'Not found')
示例4: report
def report(self, text, job, verbose=False, catalog=False, error=False):
'''Report to console and send email notifications if jobs are
configured to do so'''
assert job in self.cf.sections()
cf = getattr(self.cf, job)
text += "Job name:\t\t%s \n" % job
mail_text = text
if catalog:
text += "Catalog id:\t\t%s\nStatus Code:\t\t%s \n" % (catalog.id,
catalog.status)
mail_text = text + "Transcript:\n\n%s\n" % reindent(catalog.log, 4)
if verbose:
text += "Transcript:\n\n%s\n" % reindent(catalog.log, 4)
try:
if error:
if cf.send_email:
send_email(cf, mail_text, error=True)
else:
if cf.send_email and cf.report_success:
send_email(cf, mail_text)
except socket.error, e:
self.stdout.write(
"ERROR, could not contact to the smtp server: \n")
self.stdout.write(reindent(e.message, 4) + "\n")
示例5: create
def create(db, user):
try:
item = model.Restriction()
item.title = request.forms.title.strip().capitalize()
item.body = request.forms.body.strip()
item.state = 'NEW'
item.user = user
item.user_name = request.forms.name.strip()
item.user_city = request.forms.city.strip()
item.voters.append(user)
db.add(item)
db.flush()
if not user.admin:
subject = config.restriction_created_email_subject
body = template(
'mail_restriction_created',
site_name=config.site_name,
site_url=config.site_url,
id=item.id,
slug=slug(item.title)
)
send_email(config.site_email, subject, body)
return {'id': item.id, 'slug': slug(item.title)}
except AssertionError:
return HTTPError(400, 'Bad request')
示例6: sweep
def sweep():
to_check = []
bioguide = utils.flags().get('bioguide', None)
if bioguide:
possibles = [bioguide]
else:
possibles = current_bioguide.keys()
for bioguide in possibles:
if media_bioguide.get(bioguide, None) is None:
to_check.append(bioguide)
elif media_bioguide[bioguide]["social"].get(service, None) is None:
to_check.append(bioguide)
else:
pass
utils.mkdir_p("cache/social_media")
writer = csv.writer(open("cache/social_media/%s_candidates.csv" % service, 'w'))
writer.writerow(["bioguide", "official_full", "website", "service", "candidate", "candidate_url"])
if len(to_check) > 0:
email_body = "Social media leads found:\n\n"
for bioguide in to_check:
candidate = candidate_for(bioguide)
if candidate:
url = current_bioguide[bioguide]["terms"][-1].get("url", None)
candidate_url = "https://%s.com/%s" % (service, candidate)
row = [bioguide, current_bioguide[bioguide]['name']['official_full'].encode('utf-8'), url, service, candidate, candidate_url]
writer.writerow(row)
print "\tWrote: %s" % candidate
email_body += ("%s\n" % row)
if email_enabled:
utils.send_email(email_body)
示例7: backup
def backup(**kwargs):
# Avoid multiple instances of backup program
me = singleton.SingleInstance(flavor_id=u'esxi-backup')
# Obtain profile configuration
if not u'profile_name' in kwargs:
raise RuntimeError(u'Missing profile_name argument')
profile_name = kwargs[u'profile_name']
if not profile_name in settings.ESXI_BACKUP_PROFILES:
raise RuntimeError(u'No such profile "%s"' % profile_name)
profile = settings.ESXI_BACKUP_PROFILES[profile_name]
logger.info(u'Running backup profile "%s"' % (profile_name))
# Check if profile is currently active
t = get_current_time()
if not is_time_in_window(t, profile['backup_times']):
logger.debug(u'Out of time range. Skipping backup run for profile.')
return True
with BackupProfile(profile) as bp:
next_vm = bp.get_next_vm_to_backup()
if next_vm:
logger.info(u'Running backup for VM "%s"' % (next_vm))
bp.backup_vm(next_vm)
bp.trim_backup_archives()
if bp.email_report:
utils.send_email(
bp.gmail_user, bp.gmail_pwd, bp.from_field, bp.recipients,
u'BACKUP OK %s' % (next_vm), log_stream.getvalue())
else:
logger.info(u'No next VM to backup - Nothing to do.')
return True
示例8: register
def register(db):
try:
email = request.forms.email.strip()
if db.query(model.User).filter_by(email=email).first():
return HTTPError(409, 'Conflict')
user = model.User()
user.email = email
user.password = request.forms.password.strip()
user.name = request.forms.name.strip()
user.city = request.forms.city.strip()
db.add(user)
# create hmac verification token
token = hmac.new(config.site_secret, user.email).hexdigest()
subject = config.verification_email_subject
body = template(
'mail_verification',
email=user.email,
site_name=config.site_name,
site_url=config.site_url,
token=token
)
send_email(email, subject, body)
except AssertionError:
return HTTPError(400, 'Bad request')
示例9: run
def run():
"""
Change the password for a user and set up a cron job
to change it again based on the frequency
"""
# Since this is mostly a fire and forget script it needs
# broad exception handling so whatever traceback gets generated
# is sent out in the email
msg = 'General Failure'
success = 'Failure'
db_info = get_cfg()['config']
reciever, sender = get_addresses(db_info)
try:
username, freq = arg_parser()
old_pass = current_pass(db_info)
new_pass = change_pass(old_pass)
update_db(new_pass, db_info)
update_cron(username, freq)
msg = 'User: {0} password has been updated'.format(username)
success = 'Successful'
except Exception:
msg = str(traceback.format_exc())
finally:
send_email(sender, reciever, EMAIL_SUBJECT.format(success), msg)
示例10: wizard_send_email
def wizard_send_email():
# add new request to database
router_db = current_app.config['ROUTER_DB']
r = IPRequest(session['hostname'], session['email'], session['router_id'])
db.session.add(r)
db.session.commit()
# allocate mesh IPs
router = router_db_get_entry(router_db, session['router_id'])
ip_mesh_num = 2 if router['dualband'] else 1
get_api().allocate_ips(current_app.config['API_POOL_MESH'], r.id, r.email,
r.hostname, ip_mesh_num)
# allocate HNA network
get_api().allocate_ips(current_app.config['API_POOL_HNA'], r.id, r.email,
r.hostname, prefix_len = session['prefix_len'])
url = url_for(".wizard_activate", request_id=r.id,
signed_token=r.gen_signed_token(), _external=True)
send_email(session['email'], r.hostname, router, url)
for k in ('email', 'router_id'):
del session[k]
return render_template('waiting_for_confirmation.html')
示例11: Handle
def Handle(change, files):
is_migration = False
for filename in files:
if filename.find('nova/db/sqlalchemy/migrate_repo/versions') != -1:
is_migration = True
if is_migration:
print 'Sending email'
utils.send_email('[CI] Patchset %s #%s' %(change['id'],
change['number']),
'[email protected]',
NEW_PATCH_EMAIL
% {'change_id': change['id'],
'number': change['number'],
'subject': change['subject'],
'name': change['owner_name'],
'url': change['url'],
'is_migration': is_migration,
'files_list': '\n '.join(files)})
cursor = utils.get_cursor()
for dataset in ['nova_trivial_500', 'nova_trivial_6000',
'nova_user_001']:
for constraint in ['mysql', 'percona']:
w = workunit.WorkUnit(change['id'], change['number'],
'sqlalchemy_migration_%s' % dataset,
0, constraint)
w.enqueue(cursor)
示例12: send_resetpass_email
def send_resetpass_email(verifystring, email):
subject = "Anwen 密码找回"
verify_link = "%s/setpass?e=%s&k=%s" % (options.site_url, email, verifystring)
verify_a = '<a href="%s">%s</a>' % (verify_link, verify_link)
msg_body = "".join(
["<html>", "<p>Hi,</p>", "<p>请点击下面链接进行密码重设:</p>", verify_a.encode("utf-8"), options.msg_footer, "</html>"]
)
utils.send_email(email, subject, msg_body)
示例13: main
def main():
FILE_NAME = 'rates_to_watch.pkl'
EMAIL = ''
PASSWORD = ''
arg_count = len(sys.argv)
# Load trackers and record new rates to them.
if arg_count == 1:
# Check if tracking file exists.
if os.path.isfile(FILE_NAME):
rates_to_watch = utils.read_file(FILE_NAME)
for rate in rates_to_watch:
rate.add_rate(grab_rate(rate.get_currencies()))
utils.write_file(FILE_NAME, rates_to_watch)
report = generate_report(rates_to_watch)
utils.send_email('Exchange Rate Report', report,
EMAIL, EMAIL, PASSWORD)
# Tracking file doesn't exist, tell user to add trackers.
else:
print("Error: No currencies are being tracked.")
print("Please run the following command:")
print("python currency_report.py CURRENCY1 CURRENCY2")
print("eg. python currency_report.py GBP JPY")
# Create new currency tracker.
elif arg_count == 3:
__, currency_1, currency_2 = sys.argv
with open('currencies.txt') as file:
valid_currencies = file.read()
# Check if currencies are valid.
if currency_1 in valid_currencies and currency_1 in valid_currencies:
currencies = (currency_1, currency_2)
new_tracker = trackers.CurrencyTracker(currencies,
grab_rate(currencies))
# Edit existing tracker file.
if os.path.isfile(FILE_NAME):
rates_to_watch = utils.read_file(FILE_NAME)
rates_to_watch.append(new_tracker)
utils.write_file(FILE_NAME, rates_to_watch)
# Create new tracker file.
else:
rates_to_watch = [new_tracker]
utils.write_file(FILE_NAME, rates_to_watch)
else:
print("Error: Invalid currency codes.")
else:
print("Error: Invalid number of arguments. {count}"
"argument(s).".format(count=arg_count))
示例14: send_email
def send_email(self, request, email_template):
self.save()
send_email(request, "Alert confirmation",
email_template,
{
'object': self.content_object,
'id': int_to_base32(self.id),
'token': self.make_token(random.randint(0,32767)),
}, self.content_object.email
)
示例15: resend_confirmation
def resend_confirmation():
token = current_user.generate_confirmation_token()
send_email(current_user.email,
'CVE-PORTAL -- Account Confirmation',
'/emails/confirm',
user=current_user,
token=token)
syslog.syslog(syslog.LOG_WARNING, "User Resend a Confirmation Email to: " + current_user.email)
flash('A new confirmation email has been sent to you by email.', 'info')
return redirect(url_for('main.index'))