Example #1
0
def forgottenpassword():
  form = ForgottenPasswordForm()
  temp_password = id_generator()

  if request.method == 'POST':
    if form.validate() == False:
      flash('All fields are required.')
      return render_template('forgottenpassword.html', form=form)
    else:
      email = form.Members_Email.data
      
      user = User.query.filter_by(Members_Email = email).first()
      test = UserReset.query.filter_by(Members_Email = email).first()
      if test:
        db.session.delete(test)
        db.session.commit()

      msg = Message('Password Reset', sender='*****@*****.**', recipients=[form.Members_Email.data])
      msg.body = """
      Hi %s, 
      You have clicked on the password reset link. Please find your temporary password below:
      %s
      Please go to the below link to reset your password:
      
      """ % (user.Members_First_Name, temp_password)
      mail.send(msg)

      member_reset = UserReset(form.Members_Email.data, temp_password, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
      db.session.add(member_reset)
      db.session.commit()
      return render_template('home.html', success=True)

  elif request.method == 'GET':
    return render_template('forgottenpassword.html', form=form)    
Example #2
0
def send_email(sender, to, subject, body, html=None):
    msg = Message(sender=sender, subject=subject, recipients=[to])
    msg.body = body
    if html:
        msg.html = html
    if to:
        mail.send(msg)
Example #3
0
def order_pizza_for_everybody():
    """
    Orders pizza for every user and sedns him an e-mail.
    """
    new_event = Pizza()
    new_event.who_created = current_user.username
    new_event.pizza_ordering_is_allowed = True
    new_event.users_already_ordered = ""
    db.session.add(new_event)
    db.session.commit()
    new_event = Pizza.query.all()[-1]
    new_event_id = new_event.id
    event_url = server_url() + url_for("pizza_time_view", happening=new_event_id)
    stop_url = server_url() + url_for("pizza_time_stop", happening=new_event_id)
    users = User.query.filter(User.active).all()
    emails = [user.email for user in users]
    text = (
        "You succesfully orderd pizza for all You can check who wants"
        " what here:\n{}\n to finish the pizza orgy click here\n{}\n "
        "than order pizza!".format(event_url, stop_url)
    )
    msg = Message("Lunch app PIZZA TIME", recipients=emails)
    msg.body = "{} ordered pizza for everyone ! \n order it here:\n\n" "{}\n\n and thank him!".format(
        current_user.username, event_url
    )
    mail.send(msg)
    msg = Message("Lunch app PIZZA TIME", recipients=[current_user.username])
    msg.body = text
    mail.send(msg)
    flash(text)
    return redirect(url_for("pizza_time_view", happening=new_event_id))
Example #4
0
def send_email(subject, sender, recipients, text_body):
    msg = Message(subject, sender = sender, recipients = recipients)
    msg.body = text_body
    msg.html = text_body
    thr=Thread(target = send_async_email, args=[msg])
    thr.start()
# from flask import render_template
# from config import ADMINS

# def follower_notification(followed, follower):
#     send_email("[microblog] %s is now following you!" % follower.nickname,
#         ADMINS[0],
#         [followed.email],
#         render_template("follower_email.txt", 
#             user = followed, follower = follower),
#         render_template("follower_email.html", 
#             user = followed, follower = follower))

# from threading import Thread

# def send_async_email(msg):
#     mail.send(msg)

# def send_email(subject, sender, recipients, text_body, html_body):
#     msg = Message(subject, sender = sender, recipients = recipients)
#     msg.body = text_body
#     msg.html = html_body
#     thr = Thread(target = send_async_email, args = [msg])
#     thr.start()
Example #5
0
def endContest(shoe_id):
	all_tix = []
	tickets = Tickets.query.filter_by(kicks_id = shoe_id).all()
	if tickets:
		for t in tickets:
			for k in range(t.num_tickets):
				all_tix.append(t.user_id)

		winner_id = random.choice(all_tix)
		print winner_id
		kick = Kicks.query.filter_by(id = shoe_id).first()
		kick.winner_id = winner_id
		db.session.add(kick)
		db.session.commit()
		winner = User.query.filter_by(id = winner_id).first()
		msg = Message('test subject', sender = ADMINS[0], recipients = ADMINS)
		msg.body = 'text body'
		msg.html = '<b>HTML</b> body'
		mail.send(msg)

		flash("Contest has ended, winner is " +str(winner_id))
		return redirect(url_for('index'))
	else:
		flash('No one has bought tickets')
		return redirect(url_for('index'))
Example #6
0
def send_email(to, subject, template, **kwargs):
    """Send asynchronous e-mail with flask-mail.

    Send an asynchronous e-mail to address ``to`` with subject ``subject``
    using either a txt or html file type template ``template``. Arguments for
    the template are accepted by ``**kwargs``.

    Args:
        to (str): E-mail address of recipient.
        subject (str): Subject of e-mail.
        template (str): Path to template from the default templates
            directory of the flask project.
        **kwargs: Arguments for template.

    Returns:
        thr: :class:`threading.Thread` sending e-mail.

    """
    app = current_app._get_current_object()
    msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject,
                  sender=app.config['MAIL_SENDER'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    thr = Thread(target=_send_async_email, args=[app, msg])
    thr.start()
    return thr
Example #7
0
    def emit(self, record):
        """
        Emit a record.

        Format the record and send it to the specified addressees.
        """
        try:
            import smtplib

            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            if self.use_ssl:
                smtp = smtplib.SMTP_SSL(self.mailhost, port, timeout=self._timeout)
            else:
                smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout)

            _msg = self.format(record)
            msg = Message(self.get_subject(record), sender=self.fromaddr, recipients=self.toaddrs)
            msg.body = _msg

            if self.username:
                if self.secure is not None:
                    smtp.ehlo()
                    smtp.starttls(*self.secure)
                    smtp.ehlo()
                smtp.login(self.username, self.password)
            smtp.sendmail(self.fromaddr, self.toaddrs, msg.as_string())
            smtp.quit()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
Example #8
0
def saveIt(user, form, op_type='new'):

        user.about_me = form.about_me.data
        user.email = form.email.data
        
#        print 'Will save: {}\n - Notes: {}\n - Email: {}\n - Roles: {}'.format(user.nickname, user.about_me, user.email, form.roles.data)

        if administrator_permission.can():
            user.roles = []
            for aRole in form.roles.data.split(','):
                user.roles.append(Role.query.get(aRole))
        else:
            msg = Message (
                  '{} privileges request.'.format(config.PROJECT_NAME)
                , sender=config.DEFAULT_MAIL_SENDER
                , recipients=[g.user.email, config.DEFAULT_MAIL_SENDER]
            )
                        
            msg.body = "{} requests to be allocated {} privileges".format(g.user.nickname, ampersandAtEnd(form.roles.data))
            mail.send(msg)
            
            alert = 'An email has been sent to the site administrators, stating : "{}".'.format(msg.body)
            flash(gettext(alert), 'info')

        if op_type == 'new':
            user.nickname = form.nickname.data
            orm_db.session.add(user)
            
        orm_db.session.commit()
        
        flash(gettext('Your {} user: {}, has been saved.'.format(op_type, user.nickname)), 'success')
        flash(gettext('({}).'.format(user.id)), 'info')
        return redirect(url_for('users'))
Example #9
0
def send_email(subject, recipient, template, callback=None, **context):
    """Send an email via the Flask-Mail extension.

    :param subject: Email subject
    :param recipient: Email recipient
    :param template: The name of the email template
    :param context: The context to render the template with
    """

    # context.setdefault('security', _security)
    # context.update(_security._run_ctx_processor('mail'))
    recipients = isinstance(recipient, basestring) and [recipient] or recipient
    msg = Message(subject, recipients=recipients)

    ctx = ('email', template)
    msg.body = render_template('%s/%s.txt' % ctx, **context)
    msg.html = render_template('%s/%s.html' % ctx, **context)
    if hasattr(callback, '__call__'):
        msg = callback(msg)
    # if _security._send_mail_task:
    #     _security._send_mail_task(msg)
    #     return

    mail = current_app.extensions['mail']
    mail.send(msg)
Example #10
0
def charge():
    # Amount in cents
    amount = 2500
    email = request.form['email']
    customer = stripe.Customer.create(
        email=email,
        card=request.form['stripeToken']
    )

    charge = stripe.Charge.create(
        customer=customer.id,
        amount=amount,
        currency='usd',
        description='Hormonal Nutrition eBook Purchase'
    )

    #mongo goes here...
    customer = Customers(created_at=datetime.now(),email=email,downloads=3)
    customer.save()

    #flask mail...
    msg = Message("Thank you %s for your purchase!" % email,
                  sender=os.environ["MAILGUN_SMTP_LOGIN"],
                  recipients=[email])

    msg.body =  "Thank you! You have 3 attempts to download your ebook. " + url_for('send_pdf', email=email.replace('%40','@'), _external=True) +  " Please note: This ebook is over 1MB in size. It might take up to 30 seconds to download. Please do not refresh your browser during this time"

    mail.send(msg)
    return render_template('charge.html', amount=amount)
Example #11
0
def send(subject, recipients, template_base, **kwargs):
    '''
    Send a given email to multiple recipients.

    User prefered language is taken in account.
    To translate the subject in the right language, you should ugettext_lazy
    '''
    sender = kwargs.pop('sender', None)
    if not isinstance(recipients, (list, tuple)):
        recipients = [recipients]

    debug = current_app.config.get('DEBUG')
    connection = debug and dummyconnection or mail.connect

    with connection() as conn:
        for recipient in recipients:
            lang = i18n._default_lang(recipient)
            with i18n.language(lang):
                log.debug(
                    'Sending mail "%s" to recipient "%s"', subject, recipient)
                msg = Message(subject, sender=sender,
                              recipients=[recipient.email])
                msg.body = theme.render(
                    'mail/{0}.txt'.format(template_base), subject=subject,
                    sender=sender, recipient=recipient, **kwargs)
                msg.html = theme.render(
                    'mail/{0}.html'.format(template_base), subject=subject,
                    sender=sender, recipient=recipient, **kwargs)
                if debug:
                    log.debug(msg.body)
                    log.debug(msg.html)
                else:
                    conn.send(msg)
Example #12
0
def send_registerd_email(address):
    msg = Message("Welcome to Arctic Game Jam 2014", sender=("Arctic Game Jam team", "*****@*****.**"))
    msg.add_recipient(address)

    msg.html = render_template("email/welcome.html")
    msg.body = render_template("email/welcome.txt")
    send_email_async(msg)
Example #13
0
def send_email(to, subject, template, **kwargs):
    msg = Message(subject=subject, sender=current_app.config['EHUIGO_MAIL_SENDER'], recipients=[to])
    msg.html = render_template(template, **kwargs)
    # thread = Thread(target=_async_send_email, args=[current_app._get_current_object(), msg])
    # thread.start()
    # return thread
    mail.send(msg)
Example #14
0
def send_mail(subject, recipient, template, **context):
    """Send an email via the Flask-Mail extension.

    :param subject: Email subject
    :param recipient: Email recipient
    :param template: The name of the email template
    :param context: The context to render the template with
    """

    context.setdefault('security', _security)
    context.update(_security._run_ctx_processor('mail'))

    msg = Message(subject,
                  sender=_security.email_sender,
                  recipients=[recipient])

    ctx = ('security/email', template)
    msg.body = render_template('%s/%s.txt' % ctx, **context)
    msg.html = render_template('%s/%s.html' % ctx, **context)

    if _security._send_mail_task:
        _security._send_mail_task(msg)
        return

    mail = current_app.extensions.get('mail')
    mail.send(msg)
Example #15
0
def send_email(to,subject,template,**kwargs):

    msg = Message(subject,sender='Hatch Intranet <*****@*****.**>',recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)

    mail.send(msg)
Example #16
0
def send_email(subject, template, **kwargs):
    msg = Message('[HH-Farms] ' + subject,
                  sender='*****@*****.**',
                  recipients=['*****@*****.**'])
    # msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', form=ContactForm(), **kwargs)
    mail.send(msg)
Example #17
0
def _sendAboutUserPassword(**kw):
    try:
        title = MailSubject.ResetUserPassword + \
            MailSubject.Subject_Suffix
        nickname = kw.get('nickname')
        email = kw.get('email')
        token = kw.get('token')
        mode = kw.get('mode')

        param = {
            'nickname': nickname,
            'token': token,
            'mode': mode
        }


        msg = Message(title)
        msg.add_recipient(email)
        msg.body = render_template("./mail/resetpassword.txt", param=param)
        mail.send(msg)

        body = render_template("./mail/resetpassword.txt", param=param)
        _mailsend(email, title, body)

        sendNotifyMail(email, title, param)
        return True
    except Exception as e:
        current_app.logger.exception('_sendAboutUserPassword')
        sendException(e, '_sendAboutUserPassword')
        return False
Example #18
0
def send_mail(to,subject,template,**kwargs):
	msg = Message(app.config['BLOG_MAIL_SUBJECT_PREFIX']+subject, sender = app.config['BLOG_MAIL_SENDER'], recipients = [to])
	msg.body = render_template(template+'.txt', **kwargs)
	msg.html = render_template(template+'.html', **kwargs)
	thr = Thread(target=send_async_mail, args=[app, msg])
	thr.start()
	return thr
Example #19
0
def users_register():
    form = UserRegisterForm()
    mail = Mail(app)
    error = None

    if request.method == "POST":
        # if username is blank
        if not form.username.data:
            error = "Username can't be empty!"
            return render_template("/users/register.html", form=form, error=error)
        # elif email is blank
        elif not form.email.data:
            error = "Email can't be empty!"
            return render_template("/users/register.html", form=form, error=error)
        # elif no password
        elif not form.password.data:
            error = "Please supply a password!"
            return render_template("/users/register.html", form=form, error=error)
        # is email already exists, failed
        elif form.username.data in ["admin", "banteng"]:
            error = "You can't use this username, try something else."
            return render_template("/users/register.html", form=form, error=error)
        elif dbentity.users.find_one({"email": form.email.data}):
            error = "Email is already taken, please choose another."
            return render_template("/users/register.html", form=form, error=error)
        elif dbentity.users.find_one({"username": form.username.data}):
            error = "Username is already taken, please choose another."
            return render_template("/users/register.html", form=form, error=error)
        elif "@" in form.username.data:
            error = "Don't use email as username. Pick another one!"
            return render_template("/users/register.html", form=form, error=error)
        else:
            # simpan session username
            session["username"] = form.username.data
            # simpan data
            dbentity.users.insert({
                                 "username": form.username.data,
                                 "password": form.password.data,
                                 "email": form.email.data,
                                 "joined_at": datetime.datetime.now(),
                                 })
            # send email
            emailstring = """
            Thank you for registering with example.com.

            Here is your credential info, please keep it secret:

            username: %s
            password: %s

            Regards,

            wallgigs.com
            """ % (form.username.data, form.password.data)
            msg = Message("Welcome to example.com", sender="*****@*****.**", recipients=[form.email.data])
            msg.body = emailstring
            # mail.send(msg)
            # return redirect(request.args.get("next") or url_for("users"))
            return redirect(request.args.get("next") or url_for("index"))
    return render_template("/users/register.html", form=form)
Example #20
0
def send_user_email(user_name, email, action_code, key):
   try:
      url =  'http://%s/session/verify?action=%s&key=%s&email=%s'%(current_app.config['DOMAIN_NAME'], action_code, key, email)
      
      #setup email contents
      if action_code == ACTIVATE_USER:
         subject = "[%s] Welcome to the Family" %NAME
         html_body = render_template('emails/activate_user.html', user_name=user_name, url=url, email=email)
      elif action_code == RESET_PASSWORD:
         subject = "[%s] Reset Password" %NAME
         html_body = render_template('emails/reset_password.html', user_name=user_name, url=url)  
      elif action_code == VERIFY_EMAIL:
         subject = "[%s] Verify your email '%s'" % (NAME, email)
         html_body = render_template('emails/verify_email.html', user_name=user_name, url=url, email=email)   
      else:
         return "email action type does not exist!"
      print subject
      #Send the email   
      if(current_app.config['USE_EMAIL']):
         msg = Message(subject, recipients = [email])
         if html_body:
            msg.html = html_body
         mail.send(msg)
         logger.info("Sent email:{} to {}".format(EMAIL_ACTION[action_code], email))
      else:
         logger.info("Turn use_email setting on to send emails!")
   except Exception as e:
      logger.info("Exception : %s" % str(e))
Example #21
0
def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject,
                  sender=app.config['MAIL_SENDER'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    send_async_email.delay(msg)
Example #22
0
def confirm(hashid):
    post = JobPost.query.filter_by(hashid=hashid).first_or_404()
    form = forms.ConfirmForm()
    if post.status in [POSTSTATUS.REJECTED, POSTSTATUS.SPAM]:
        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 Hasjob",
                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)
Example #23
0
def send(template, subject, recipients, **templatevars):
    """Send an e-mail with a jinja2 template"""
    path = os.path.dirname(__file__)
    plaintext_template = '%s%stemplates/emails/%s.txt' % (path, os.path.sep,
                                                          template)
    html_template = '%s%stemplates/emails/%s.html' % (path, os.path.sep,
                                                      template)
    msg = Message(subject,
                  sender=app.config['MAIL_DEFAULT_SENDER'],
                  recipients=recipients)

    # Plain-text template
    if os.path.exists(plaintext_template):
        msg.body = render_template('emails/%s.txt' % template,
                                   **templatevars).encode('ascii', 'ignore')
    else:
        app.logger.debug('Plain-text e-mail template does not exist for "%s"'
                         % plaintext_template)

    # HTML template
    if os.path.exists(html_template):
        msg.html = render_template('emails/%s.html' % template,
                                   **templatevars).encode('ascii', 'ignore')
    else:
        app.logger.debug('HTML e-mail template does not exist for "%s"'
                         % html_template)

    """This is only here temporarily until I can figure out why setting
    CSRF_ENABLED in TestingConfig seems to make Flask-Mail ignore the TESTING
    flag and send mail anyways. It's annoying to have a #pragma: no cover tag,
    it feels like wearing the python cone of shame :(."""
    if app.config['TESTING']:
        return True
    return mail.send(msg)  # pragma: no cover
Example #24
0
def rejectjob(hashid):
    post = JobPost.query.filter_by(hashid=hashid).first_or_404()
    if post.status in [POSTSTATUS.DRAFT, POSTSTATUS.PENDING]:
        if post.edit_key not in session.get('userkeys', []):
            abort(403)
    if post.status in [POSTSTATUS.REJECTED, POSTSTATUS.WITHDRAWN, POSTSTATUS.SPAM]:
        abort(410)
    rejectform = forms.RejectForm()
    if rejectform.validate_on_submit():
        post.closed_datetime = datetime.utcnow()
        post.review_comments = rejectform.reason.data
        post.review_datetime = datetime.utcnow()
        post.reviewer = g.user

        if request.form.get('submit') == 'spam':
            flashmsg = "This job listing has been marked as spam."
            post.status = POSTSTATUS.SPAM
        else:
            flashmsg = "This job listing has been rejected."
            post.status = POSTSTATUS.REJECTED
            msg = Message(subject="About your job listing on Hasjob",
                recipients=[post.email])
            msg.body = render_template("reject_email.md", post=post)
            msg.html = markdown(msg.body)
            mail.send(msg)
        db.session.commit()
        if request.is_xhr:

            return "<p>%s</p>" % flashmsg
        else:
            flash(flashmsg, "interactive")
    elif request.method == 'POST' and request.is_xhr:
        return render_template('inc/rejectform.html', post=post, rejectform=rejectform, ajaxreg=True)
    return redirect(url_for('jobdetail', hashid=post.hashid))
Example #25
0
def send_message(subject, body, html=False, caps_gs_sem=False):
    from sync import app

    mail = Mail(app)

    if caps_gs_sem:
        recipients = CAPS_GS_SEM_RECIPIENTS
    else:
        recipients = ADMIN_RECIPIENTS
    msg = Message(subject=subject,
                  sender="*****@*****.**",
                  recipients=recipients)

    if html:
        msg.html = body
    else:
        msg.body = body

    try:
        mail.send(msg)
    except socket.error:
        print "failed to send message %s" % body
        return False

    return True
Example #26
0
def send_activate(user):
	message = Message(subject='MyLink Activation.',
					  sender='*****@*****.**',
					  recipients=[user.get_email()])
	activate_url = url_for('activate_account', uid=user.get_id(), _external=True)
	message.html = activate_url
	mail.send(message)
Example #27
0
def newsletter(email):
	msg = Message('subject', sender='*****@*****.**', recipients=[email])
	msg.body = 'Hola'
	msg.html = '<b>HTML</b> body'
	with app.app_context():
		mail.send(msg)
	return redirect(redirect_url())
Example #28
0
def conflict_create(order_id):
    """
    Renders conflict create page.
    """
    order = Order.query.get(order_id)
    form = CreateConflict(formdata=request.form)
    form.user_connected.choices = [
        (user.username, user.username) for user in User.query.options(load_only("username")).all()
    ]
    form.user_connected.choices.append(("None", "None"))
    form.user_connected.default = ("None", "None")
    if request.method == "POST":
        conflict = Conflict()
        conflict.did_order_come = request.form.get("did_order_come") == "y"
        conflict.i_know_who = request.form.get("i_know_who") == "y"
        conflict.user_connected = request.form.get("user_connected")
        conflict.order_connected = order.id
        conflict.created_by_user = current_user.username
        db.session.add(conflict)
        db.session.commit()
        if conflict.i_know_who:
            new_conflict = Conflict.query.order_by(Conflict.date_added.desc()).first()
            conflict_url = server_url() + url_for("conflict_resolve", conf_id=new_conflict.id)
            msg = Message("Lunch app new conflict", recipients=[conflict.user_connected])
            msg.body = (
                "You were chosen as the one who ate my lunch! "
                "Please use the link below to respond"
                " \n\n {}".format(conflict_url)
            )
            mail.send(msg)
        flash("Conflict created")
        return redirect("my_orders")
    return render_template("conflict_create.html", form=form)
Example #29
0
def message_reset_password(email, password):
    msg = Message(_('Reset password'), sender=DEFAULT_MAIL_SENDER, recipients=[email])
    msg.html = render_template('email/reset_password.html',
                               site_name=SITE_NAME,
                               user=email,
                               password=password)
    return msg
Example #30
0
def send_abstainer_confirmation(abstainer_id):
    abstainer = db.session.query(Abstainer).get(abstainer_id)
    ballot = abstainer.ballot
    body = render_template(
        'abstainer_email.txt',
        ballot=ballot,
        abstainer=abstainer,
        timestamp=int(time.mktime(abstainer.created_at.timetuple())),
    )

    if app.config["USE_SMTP"]:
        msg = Message(u"Potvrzení o zdržení se hlasování",
                      sender=(u"Volební komise", "*****@*****.**"),
                      recipients=[abstainer.email])
        msg.body = body
        logger.info(u"Sending abstainer confirmation {0} {1}"
                    .format(abstainer.name, abstainer.email))
        mail.send(msg)
        logger.info(u"Abstainer confirmation sent {0} {1}"
                    .format(abstainer.name, abstainer.email))
    else:
        # Only SMTP supported here
        logger.warning(u"Not sending abstainer confirmation {0} {1}"
                       .format(abstainer.name, abstainer.email))

    abstainer.confirmation_sent = True
Example #31
0
def index():
    # sender 发送方哈,recipients 邮件接收方列表
    msg = Message("Hi!This is a test ",
                  sender='*****@*****.**',
                  recipients=['*****@*****.**'])
    msg.body = "This is a first email"  # msg.body 邮件正文
    with app.open_resource("F:\2281393651481.jpg") as fp:  # msg.attach 邮件附件添加
        msg.attach("image.jpg", "image/jpg",
                   fp.read())  # msg.attach("文件名", "类型", 读取文件)

    mail.send(msg)
    print "Mail sent"
    return "Sent"
Example #32
0
def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject,
                  sender=app.config['MAIL_SENDER'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr
    # msg = Message('test subject', sender='*****@*****.**',
    #              recipients=['*****@*****.**'])
    # msg.body = 'text body'
    # msg.html = '<b>HTML</b> body'
    # with current_app.app_context():
    #     mail.send(msg)
Example #33
0
    def send(self):
        """
        Send email to all form recipients.
        """
        assert self.title, 'Please, supply "title" attribute first.'
        assert self.template, 'Please, supply "template" attribute first.'

        title = self.get_title()
        message = Message(u'[Learn Python] {0}'.format(title),
                          sender=(self.data['name'], self.data['email']),
                          recipients=self.recipients)
        message.body = render_template(self.template, **self.data)

        mail.send(message)
Example #34
0
def send_email(to, subject, template, **kwargs):
              
              '''  邮件发送  '''

              # 收件人, 主题,  渲染邮件正文的模板, 关键字参数列表
              msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
                            sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])

              msg.body = render_template(template + '.txt', **kwargs)    #邮件内容.主题
              msg.html = render_template(template + '.html', **kwargs)   #邮件内容.内容

              thr = Thread(target=send_async_email, args=[app, msg])
              thr.start()
              return thr
def sendemail():
    """sends emails and handles scheduling"""

    msg = Message('Your reminder!', sender=config.ADMINS[0], recipients=config.ADMINS)
    msg.body = 'text body'
    msg.html = '''<p> Its time to track your time! Please visit http://localhost:5000/response
        to fill out your activity tracker form :D
    </p>

    <p>To unsubscribe from these emails, please visit http://localhost:5000/response
        and deselect the "Get Reminder Emails" checkbox </p>'''

    with app.app_context():
        mail.send(msg)
Example #36
0
def send_mail(destination, subject, template, **template_kwargs):
    text = flask.render_template("{0}.txt".format(template), **template_kwargs)

    logging.info("Sending email to {0}. Body is: {1}".format(
        destination,
        repr(text)[:50]))

    msg = Message(subject, recipients=[destination])

    msg.body = text
    msg.html = flask.render_template("{0}.html".format(template),
                                     **template_kwargs)

    mail.send(msg)
Example #37
0
 def __init__(self, username, email, password=None, **kwargs):
     db.Model.__init__(self, username=username, email=email, **kwargs)
     if password:
         self.set_password(password)
     else:
         self.password = None
     # Send Email and SMS confirmation messages
     message = 'You are now signed up for CorpScores.'
     if self.carrier and self.phone_num:
         send_sms(self.carrier, self.phone_num, message)
     msg = Message('CorpScores Registration Confirmation',
                   recipients=[self.email])
     msg.body = render_template('users/reg_confirm.txt')
     mail.send(msg)
Example #38
0
def correct_this_page():
    form = forms.CorrectThisPageForm(request.form)
    if form.validate_on_submit():
        msg = Message("Correct This Page feedback", recipients=["*****@*****.**"], sender='*****@*****.**')
        msg.html = render_template('correct_this_page.html', submission={
            'url': form.url.data,
            'details': form.details.data,
            'email': form.email.data,
        })
        mail.send(msg)

        flash('Thanks for your feedback.', 'info')

    return redirect(request.form.get('url', '/'))
Example #39
0
def send_mail(subject=None, text=None, to=[]):
    """
    Sends mail

    :param subject: Subject
    :param text: Message
    :param to: Recipients as list

    """
    mail = current_app.config.get('mail')
    msg = Message(subject, sender=current_app.config.get('DEFAULT_SENDER'), \
        recipients=to)
    msg.body = text
    return mail.send(msg)
Example #40
0
    def send(self):
        """
        Send email to all form recipients.
        """
        assert self.title, 'Please, supply "title" attribute first.'
        assert self.template, 'Please, supply "template" attribute first.'

        title = self.get_title()
        message = Message(u'[Dive into IT] {0}'.format(title),
                          sender=app.config.get('DEFAULT_MAIL_SENDER'),
                          recipients=self.recipients)
        message.body = render_template(self.template, **self.data)

        mail.send(message)
Example #41
0
def send_email(recording_name, intent, ani, requireds, assign, app=app):
    '''send an email to the required and assigned recipients'''
    intent = str(intent)
    # look for configuration variables in params.conf file...
    msg = Message(sender=from_email)
    description = Intent.query.filter_by(digit=intent).first().description
    assign_names = " and ".join([
        a.split('@')[0].replace(".", " ").title() for a in assign.split(',')
    ])  # fancy :)
    msg.subject = assign_names + ' assigned EHHOP voicemail from ' + description + ", number " + ani
    msg.sender = from_email
    msg.recipients = assign.split(',') if ',' in assign else [assign]
    msg.cc = requireds.split(',') if ',' in requireds else [requireds]
    with app.app_context():
        msg.html = render_template('email.html',
                                   from_phone=ani,
                                   assign_names=assign_names,
                                   playback_url=player_url + recordings_base +
                                   recording_name,
                                   desc=description)
        msg.body = render_template('email.txt',
                                   from_phone=ani,
                                   assign_names=assign_names,
                                   playback_url=player_url + recordings_base +
                                   recording_name,
                                   desc=description)
    mail.send(msg)
    return None
Example #42
0
 def sendmessage(self):
     coll = get_coll()
     result = coll.find_one({"userID": self.userID})
     code = result['confirmnumber']
     address = result['email']
     mail = Mail(app)
     msg = Message('What to Eat Tonight',
                   sender='*****@*****.**',
                   recipients=[address])
     msg.body = "Hello, dear friend!\nYour verification code is : " + str(
         code) + "\nThanks for your support!"
     with app.app_context():
         mail.send(msg)
     return "True"
Example #43
0
def send_role_change_notification(user, new_roles):
    app = current_app
    role_description = {row.name: row.description for row in models.Role.query}
    msg = Message(
        subject="Role update on the Biological Diversity website",
        sender=app.extensions['security'].email_sender,
        recipients=[user.email],
    )
    msg.body = render_template(
        'auth/email_user_role_change.txt', **{
            'user': user,
            'new_roles': [role_description[r] for r in new_roles],
        })
    safe_send_mail(app, msg)
Example #44
0
def send_welcome_email(user, plaintext_password=None):
    app = current_app
    msg = Message(
        subject="Role update on the Biological Diversity website",
        sender=app.extensions['security'].email_sender,
        recipients=[user.email],
    )
    msg.body = render_template(
        'auth/email_user_welcome.txt', **{
            'user': user,
            'plaintext_password': plaintext_password,
            'home_url': url_for(HOMEPAGE_VIEW_NAME, _external=True),
        })
    safe_send_mail(app, msg)
Example #45
0
def send_email(subject, sender, recipients, text_body=None, html_body=None):
    """
    发送邮件
    :param subject:
    :param sender:
    :param recipients:
    :param text_body:
    :param html_body:
    :return:
    """
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    mail.send(msg)
Example #46
0
def send_email(subject, sender, recipients, text_body):
    """
    Sent an email and return the Message instance of sent email.

    :param subject: str
    :param sender: str
    :param recipients: list
    :param text_body: str
    :return: Message
    """
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    mail.send(msg)
    return msg
Example #47
0
def submit_benchmarks(database):
    db = models.get_database(database) or abort(404)
    form = forms.BenchmarksForm()

    if form.validate_on_submit():
        upload_dir = os.path.join(config.UPLOAD_FOLDER, database,
                                  str(g.User.idUser))
        move_dir = os.path.join(config.UPLOAD_FOLDER, database,
                                secure_filename(form.category.data),
                                str(g.User.idUser))
        try:
            os.makedirs(upload_dir, mode=0700)
        except:
            pass
        try:
            os.makedirs(move_dir, mode=0700)
        except:
            pass

        try:
            for file in session.get('benchmarks', list()):
                try:
                    os.rename(os.path.join(upload_dir, file),
                              os.path.join(move_dir, file))
                except Exception as ex:
                    print ex

            flash('Benchmark submission successful.')
            try:
                msg = Message("[" + db.label + "][Admin] Benchmarks submitted",
                              recipients=[config.DEFAULT_MAIL_SENDER])
                msg.body = (
                    "The user %s %s with id %d just submitted some benchmarks"
                    % (g.User.firstname, g.User.lastname, g.User.idUser))
                mail.send(msg)
            except:
                pass
            session.pop('benchmarks', None)
            return redirect(
                url_for('frontend.experiments_index', database=database))

        except Exception as ex:
            print ex
            flash('Error occured when trying to move the uploaded files.')

    return render('/accounts/submit_benchmarks.html',
                  db=db,
                  database=database,
                  form=form)
Example #48
0
def reset_password(database):
    db = models.get_database(database) or abort(404)
    form = forms.ResetPasswordForm()

    if form.validate_on_submit():
        # find user by lower case email address
        user = db.session.query(
            db.User).filter_by(email=form.email.data.lower()).first()
        if not user or not user.verified:
            if not user: flash('No account with this e-mail address exists.')
            if user and not user.verified:
                flash('Account was not verified yet.')
            return render('/accounts/reset_password.html',
                          db=db,
                          database=database,
                          form=form)

        hash = hashlib.sha256()
        hash.update(config.SECRET_KEY)
        hash.update(user.email)
        hash.update(str(datetime.datetime.now()))
        hash.update(user.password)
        # reuse the activation hash (user should be activated at this point already)
        user.activation_hash = 'pw_reset_' + hash.hexdigest()

        try:
            db.session.commit()

            msg = Message("[" + db.label + "] Password reset instructions",
                          recipients=[user.email])
            msg.body = "Dear " + user.firstname + " " + user.lastname + ",\n\n" + \
                       "If you did not use the password reset link on the website ignore this mail.\n\n" + \
                       "To reset your password please use the following link:\n" + \
                       request.url_root[:-1] + url_for('accounts.change_password', database=database,
                                                       reset_hash=hash.hexdigest())
            mail.send(msg)

            flash(
                'E-mail was sent. Please refer to the mail for further instructions.'
            )
        except Exception as e:
            print e
            flash(
                'Could not send reset mail. Please contact an administrator.')

    return render('/accounts/reset_password.html',
                  db=db,
                  database=database,
                  form=form)
Example #49
0
def contact():
    print request.form
    print request.values
    client_name = request.form['name']
    client_org = request.form['org']
    client_email = request.form['email']
    client_phone = request.form['phone']
    client_image = request.form['image']
    print client_name
    print client_org
    print client_email
    print client_phone
    print client_image

    msgUAC = Message("Nonprofit Overhead Analyzer: new prospect",
                     sender="*****@*****.**",
                     recipients=[
                         '*****@*****.**', '*****@*****.**',
                         '*****@*****.**'
                     ])
    msgUAC.html = (
        "<p>Hello,</p><p>A new prospect requested a report on the Nonprofit Overhead Analyzer. Here are the details:<br>Name: "
        + client_name + "<br>Organization: " + client_org + "<br>Email: " +
        client_email + "<br>Phone: " + client_phone +
        "<br>Please see the CSV file attached for the prospect's financials.</p><p>This is an automatically-generated message. Please do not reply.<br>Have a good day!</p>"
    )

    # create the CSV
    current_time = datetime.datetime.now().strftime("%c")
    csv_data = 'Expense type, Amount\n'
    field_names = [
        'name', 'org', 'email', 'phone', 'pension_plan_contributions',
        'othremplyeebene', 'feesforsrvcmgmt', 'legalfees', 'accountingfees',
        'feesforsrvclobby', 'profndraising', 'feesforsrvcinvstmgmt',
        'feesforsrvcothr', 'advrtpromo', 'officexpns', 'infotech',
        'interestamt', 'insurance', 'total_expense', 'total_revenue'
    ]

    for name in field_names:
        csv_data += name + ',' + request.values[name] + '\n'

    # attach the client financial data in the CSV
    msgUAC.attach(data=csv_data,
                  content_type="text/plain",
                  filename='Nonprofit Overhead Analyzer prospect data from ' +
                  current_time + '.csv')

    mail.send(msgUAC)
    return "200"
Example #50
0
def Register():

    error = None

    if not session.get('username'):

        if request.method == 'POST':

            firstname = request.form['firstname']
            lastname = request.form['lastname']
            email = request.form['email']
            number = request.form['number']

            if len(email) < 5:
                error = 'The email is invalid'
            elif len(firstname) < 1:
                error = 'The firstname cannot be empty'
            elif len(lastname) < 1:
                error = 'The lastname cannot be empty'
            else:
                system = System()
                account = system.account()

                response = User(email).register(firstname, lastname, email,
                                                account, number)
                if response == 1:
                    error = 'No record inserted, the email (' + email + ') already exist'

                else:

                    session['username'] = email
                    msg = Message(
                        "Registration successfull, your registration details ",
                        sender=app.config["DEFAULT_MAIL_SENDER"],
                        recipients=[email])
                    msg.html = render_template("reg-email.html",
                                               firstname=firstname,
                                               lastname=lastname,
                                               account=account,
                                               email=email)
                    thr = Thread(target=send_async_email_test, args=[app, msg])
                    thr.start()
                    flash("Logged In")
                    login_user = system.getUser(session.get('username'))
                    return redirect(url_for('Home'))
        return render_template('register.html', error=error)
    system = System()
    login_user = system.getUser(session.get('username'))
    return render_template('home.html', login_user=login_user)
Example #51
0
def send_feedback_email(name, sender, subject, data, attachments=None):
    # Allow the default recipient to be overriden depending on email subject
    email = current_app.config['FEEDBACK_EMAILS'].get(subject, current_app.config['DEFAULT_EMAIL'])
    msg = Message(subject="%s from %s (%s)" % (subject, name, sender),
                  recipients=[email],
                  sender=("ADS Administration", current_app.config['DEFAULT_EMAIL']),
                  reply_to=(name, sender),
                  body=data)
    if attachments:
        for attachment in attachments:
            # Each entry is a tuple of file name and JSON data
            msg.attach(attachment[0], "application/json", json.dumps(attachment[1]))
    current_app.extensions['mail'].send(msg)
    current_app.logger.info('Successfully sent email: data submitted by {0}, sent to {1} (form: {2})'.format(sender, email, subject))
    return msg
Example #52
0
def send_email(user):
    from flask.ext.mail import Mail, Message
    mail = Mail(app)
    msg = Message("Gamma Computations Complete", recipients=[user.email])
    msg.body = """A simulation has been completed by the Flask Gamma app. Please log in at

http://localhost:5000/login

to see the results.

---
This email has been automatically generated by the Gamma app created by
Parampool. If you don't want email notifications when a result is found, please
register a new user and leave the 'notify' field unchecked."""
    mail.send(msg)
Example #53
0
def send_bug():
    form = forms.ContactForm(request.form)
    if form.validate() == False:
        flash('All fields are required.', 'warning')
        return render_template('reportbug.html', user=current_user)
    else:
        page = form.page.data
        bug = form.bug.data
        msg = Message('bug report',
                      sender='*****@*****.**',
                      recipients=['*****@*****.**'])
        msg.body = "Page: %s Body: %s" % (page, bug)
        mail.send(msg)
        flash('Message sent!', 'success')
        return render_template('reportbug.html', user=current_user)
Example #54
0
def forgot():
    form = ForgotForm()
    if form.validate_on_submit():
	user = form.user
        s = get_serializer(form.temppassword.data)
        payload = s.dumps(user.id)
        url = url_for('forgotchange', payload=payload, _external=True)
        msg = Message('Password Reset', sender = ADMINS[0], recipients = [user.email])
        msg.body = "Follow this link to reset password: " + url
        mail.send(msg)
        flash('Password Reset Email Sent')
        return redirect(url_for('login'))
    return render_template('forgot.html',
        title = 'Forgot Password',
        form = form)
Example #55
0
def send_mail(to, subject, template, **kwargs):
    """
    :param to: user to send email to
    :param subject: subject of email
    :param template: the template to use for the email
    :param kwargs: any additional keyword arguments for templates
    :return:
    """

    msg = Message(subject,
                  sender=app_settings.DEFAULT_SEND_FROM,
                  recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    mail.send(msg)
Example #56
0
 def reset_password(self):
     p = Password_Generator()
     passwd = p.gen()
     # check email
     email = self.signup_email
     if self.profile.email in ['', None]:
         email = self.profile.email
     # mailout passwort
     reset_msg = Message("Hello",
                         sender="*****@*****.**",
                         recipients=[email])
     reset_msg.body = """Your new Passwort is: %s""" % (passwd)
     mail.send(reset_msg)
     self.password = passwd
     return passwd
Example #57
0
def jobadd():
    if not session:
        return redirect("/")
    if request.method=='POST':
        job={k:v[0] for k,v in dict(request.form).items()}
        field=['apply_date','apply_type','apply_desc','status','apply_persion']
        job['apply_date']=time.strftime('%Y-%m-%d %H:%M')
        job['status']=0
        print 'job-->',job
        data=utils.insert(table,field,job)
        msg=Message('新的工单需要处理',sender="*****@*****.**",recipients=['*****@*****.**'])
        msg.body="applyer:%s,type:%s,message:%s,time:%s"%(job['apply_persion'],job['apply_type'],job['apply_desc'],job['apply_date'])
        mail.send(msg)
        return json.dumps(data)
    return render_template("job_add.html",res=session)
Example #58
0
def send_mail(subject, body, recipients):
    # remove new lines from subject
    subject = ' '.join(subject.strip().splitlines())

    msg = Message(subject, recipients=recipients)
    msg.body = body

    try:
        mail.send(msg)
    except:
        # this is likely to be a bad recipient address
        # ... or a failure in the MTA
        # in any case, we don't want to bother the user with these errors
        # so we fail silently
        pass
Example #59
0
def create_notification_email(user, comment):
    link = custom_url_for('/project/%s/planning/ticket/%s',
                          project=str(comment.ticket.project.pk),
                          ticket=str(comment.ticket.pk))
    message = Message('Coati - Notification',
                      sender=(current_app.config.get('MAIL_SENDER_NAME'),
                              current_app.config.get('MAIL_DEFAULT_SENDER')),
                      recipients=[user.email])

    message.html = get_template('notification.html',
                                full_name=user.full_name,
                                link=link,
                                message=comment.comment,
                                title=comment.ticket.title)
    current_app.notification_handler.send(message)
Example #60
0
def send_mail(subject, recipient, template, **context):
    context.setdefault('security', _security)
    context.update(_security._run_ctx_processor('mail'))
    msg = Message(subject,
                  sender=_security.email_sender,
                  recipients=[recipient])
    ctx = ('security/email', template)
    msg.body = render_template('%s/%s.txt' % ctx, **context)
    msg.html = render_template('%s/%s.html' % ctx, **context)

    if _security._send_mail_task:
        _security._send_mail_task(msg)
        return
    mail = current_app.extensions.get('mail')
    mail.send(msg)