예제 #1
0
파일: main.py 프로젝트: sri-jay/pypad
def send_mail(recipient,hash_code):
	mail = Mail(app)

	msg = Message("Your python snippet",sender="*****@*****.**",recipients=[recipient])
	msg.html = render_template("email.html",emailid=recipient.split('@')[0],link="http://pypad.herokuapp.com/get/"+hash_code)

	mail.send(msg)
예제 #2
0
def callmeCreate():
    jsonData = request.get_json(force=True)
    if not (jsonData and 'name' in jsonData and 'phone' in jsonData): #check not-nullable fields
        abort(400)

    #set gmail settings
    app.config.update(
    MAIL_SERVER='smtp.gmail.com',
    MAIL_PORT=465,
    MAIL_USE_SSL=True,
    MAIL_USERNAME='******',
    MAIL_PASSWORD=MAIL_PASS,
    MAIL_DEFAULT_SENDER=('ВИССОН', '*****@*****.**')
    )
    mail = Mail(app)


    #and send email to me
    try: #send to buyer
        msg = Message("ВИССОН", recipients=["*****@*****.**"])
        msg.html = "Заявка перезвонить <br> имя: %s <br> номер: %s <br>" % (jsonData.get("name"), jsonData.get("phone"))
        mail.send(msg)
    except BaseException as e:
        print(str(e))
        abort(400)

    return str(True)
예제 #3
0
    def sendMail(self, app, form):
        app.config['MAIL_SERVER']='smtp.gmail.com'
        app.config['MAIL_PORT'] = 465
        app.config['MAIL_USERNAME'] = Constants.ADMIN_MAIL_ADDR
        app.config['MAIL_PASSWORD'] = Constants.ADMIN_MAIL_PASS
        app.config['MAIL_USE_TLS'] = False
        app.config['MAIL_USE_SSL'] = True
        mail = Mail(app)

        #generate encrypt key
        encryptkey = Script.encode(form['mail'])

        # read file and prepare mail body
        txtBody = ''
        with open(Constants.MAIL_TEMPLATE_FILE) as f:
            content = f.readlines()
            #content = [x.strip() for x in content]
            for row in content:
                row = row.replace("%ACTIVATION_LINK%", "http://localhost/activate?mail={0}&encryptkey={1}".format(form['mail'], encryptkey))
                row = row.replace("%MAIL_ADDRESS%", form['mail'])
                row = row.replace("%FIRSTNAME%", form['firstname'])
                row = row.replace("%REGISTRATION_DATE%", strftime("%Y-%m-%d %H:%M:%S", gmtime()))
                txtBody +=row

        msg = Message('Registration', sender = Constants.ADMIN_MAIL_ADDR, recipients = [form['mail']])
        msg.body = txtBody
        mail.send(msg)
예제 #4
0
def send(to_mailaddr,title,text):
	result = {}
	app = Flask(__name__)
	app.config['MAIL_SERVER']='smtp.qq.com'
	app.config['MAIL_PORT']=587
	app.config['MAIL_USE_TLS']=True
	app.config['MAIL_USERNAME']='******'
	app.config['MAIL_PASSWORD']='******'
	# app.config['ADMINS'] = '*****@*****.**'
	# app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
	# app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <*****@*****.**>'
	mail = Mail(app)

	msg = Message(title,sender = '*****@*****.**', 
					recipients=[to_mailaddr])
	msg.body = 'text body'
	msg.html = text
	try:
		with app.app_context():
			mail.send(msg)
		result['code'] = 100
		result['message']='邮件发送成功'
	except:
		result['code'] = 101
		result['message']='邮件发送失败'
	return result
예제 #5
0
    def execute(self, **kwargs):
        """
        Send email message
        """
        from . import actions
        with self.act_manager.app.app_context():
            if self.act_manager.app.debug == True:
                msg = Message(sender='*****@*****.**')
            for func in [getattr(self, aa) for aa in dir(self) if aa.startswith('get_')]:
                result = func(**kwargs)
                if result:
                    head, sep, tail = func.__name__.partition('_')
                    if tail == 'attachments':
                        for attachment in result:
                            msg.add_attachment(attachment)
                    else:
                        setattr(msg, tail, result)

            mail = Mail(self.act_manager.app)
            mail.connect()
            mail.send(msg)
            if self.log_mail:
                """
                Log email to a table with a timestamp. Note, for attachements, don't only log the
                file name and content_type, not the data.
                """
                pass
        return
예제 #6
0
 def send_email(self, param1):
     """
         Method for sending the registration Email to the user
     """
     try:
         from flask_mail import Mail, Message
     except:
         log.error("Install Flask-Mail to use User registration")
         return False
     mail = Mail(self.appbuilder.get_app)
     msg = Message()
     msg.subject = "TEST VERIFICATION MAIL" + str(datetime.datetime.now())
     #url = url_for('.activation', _external=True, activation_hash=register_user.registration_hash)
     url = "asdddd"
     msg.html = self.render_template(
         "mail.html",
         url=url,
         #username=register_user.username,
         username="******",
         #first_name=register_user.first_name,
         first_name="Péter",
         #last_name=register_user.last_name)
         last_name="Nagy")
     msg.recipients = [
         "*****@*****.**", "*****@*****.**", "*****@*****.**"
     ]
     #try:
     mail.send(msg)
     #except Exception as e:
     #    log.error("Send email exception: {0}".format(str(e)))
     #    return False
     return msg.html
예제 #7
0
def send_mail(app, form):
    """
    Send email confirmation of an RSVP response,
    both to myself and to the guest. If DEBUG
    is enabled, send responses to a testing
    address instead.
    """
    mail = Mail(app)

    msg = Message("Thanks for your RSVP!",
        sender="*****@*****.**",
        reply_to="Daven and Beth <*****@*****.**>",
        extra_headers={"From":"Daven and Beth via davenquinn.com <*****@*****.**>"})

    if app.config["DEBUG"]:
        msg.recipients = ['*****@*****.**']
    else:
        msg.recipients = [form["email"]]
        msg.bcc = ["*****@*****.**"]

    _ = partial(render_template,
        form=form,
        attending=int(form["number"]) > 0)

    msg.body = _("wedding/email/thanks.txt")
    msg.html = _("wedding/email/thanks.html")
    mail.send(msg)
예제 #8
0
파일: views.py 프로젝트: sci-web/w4a
def send_email():
    captcha = FlaskSessionCaptcha(app)
    cform = ContactForm(request.values)
    tmpl = tmpl_picker('contact')
    reply = tmpl_picker('autoreply')
    if request.method == 'POST':
        if cform.validate_on_submit():
            if captcha.validate():
                try:
                    mail = Mail(app)
                    msg = Message(">>> message from SciBook: " + cform.data["subject"],
                        sender=cform.data["email"],
                        recipients=[app.config["EMAIL_1"]])
                    msg.add_recipient(app.config["EMAIL_2"])
                    msg.body = cform.data["msg"] + "\n\n" + "signed as from:\n" + cform.data["email"]
                    mail.send(msg)
                    flash("Your message is sent!", category='info')
                    return render_template(reply, form=g.form, cform=cform)
                except:
                    flash("Your message is not sent fast way... Something went wrong, we are soory, but we look at your message a bit later", category='error')
                    return render_template(reply, form=g.form, cform=cform)
            else:
                flash("Captcha is wrong!", category='error')
                return render_template(tmpl, form=g.form, cform=cform, email=cform.data["email"], subject=cform.data["subject"], msg=cform.data["msg"], topics=g.topics)
        else:
            flash("All fields are necessary to fill in!", category='error')
            return render_template(tmpl, form=g.form, cform=cform, email=cform.data["email"], subject=cform.data["subject"], msg=cform.data["msg"], topics=g.topics)
    else:
        return render_template(tmpl, form=g.form, cform=cform, topics=g.topics)
예제 #9
0
파일: inits.py 프로젝트: kinyonyi/medical
def mail():
    if g.doc:
        if request.method == 'POST':
            try:
                email = request.form['email']
                body = request.form['body']

                app.config['TESTING'] = False
                app.config['MAIL_SERVER'] = 'smtp.gmail.com'
                app.config['MAIL_PORT'] = 465
                app.config['MAIL_USE_TLS'] = False
                app.config['MAIL_USE_SSL'] = True
                app.config['MAIL_DEBUG'] = True
                app.config['MAIL_USERNAME'] = '******'
                app.config['MAIL_PASSWORD'] = ''
                app.config['MAIL_DEFAULT_SENDER'] = ('E-MED',
                                                     '*****@*****.**')
                app.config['MAIL_MAX_EMAILS'] = 1
                app.config['MAIL_SUPPRESS_SEND'] = False
                app.config['MAIL_ASCII_ATTACHMENTS'] = False

                mail = Mail(app)

                msg = Message('Hello', recipients=[email])
                msg.body = body
                mail.send(msg)
                return redirect(url_for('messages'))
            except:
                return ("Message not sent!, please try again doctor")
        else:
            return render_template("messages.html")
예제 #10
0
class Email(object):

    def __init__(self, app):
        self.app = app
        self.mail = Mail(app)

    def send_welcome(self, user, passwd):
        subject = 'Bem vindo ao garupa.com!'
        recipients = [user.get_email()]
        body = 'Oi %s,\n' % user.get_name()
        body += 'Sua conta no garupa.com foi criada com sucesso!\n\n'
        body += 'Sua matricula: %s\n' % user.get_uid()
        body += 'Sua senha: %s (nao va perder em?)\n' % passwd
        self.send(subject, recipients, body)

    def send_recover_passwd(self, user, passwd):
        subject = 'Tua senha! Criatura esquecida!'
        recipients = [user.get_email()]
        body = 'Oi %s,\n' % user.get_name()
        body += 'Esquecesse tua senha num foi?\n'
        body += 'Sua senha nova: %s (nao vai esquecer de novo em?)' % passwd
        self.send(subject, recipients, body)

    def send(self, subject, recipients, text_body):
        msg = Message(subject, recipients=recipients)
        msg.body = text_body
        thr = Thread(target=self.send_async, args=[msg])
        thr.start()

    def send_async(self, msg):
        with self.app.app_context():
            self.mail.send(msg)
예제 #11
0
def send_mail(to, subject, fro=None, template_name=None, bcc=None, files=None, msg_body=None, **template_params):
    bcc = [] if bcc is None else bcc
    files = [] if files is None else files

    # ensure that email isn't sent if it is disabled
    #if not app.config.get("ENABLE_EMAIL", False):
     #   return

    assert type(to) == list
    assert type(files) == list
    if bcc and not isinstance(bcc, list):
        bcc = [bcc]

    #if app.config.get('CC_ALL_EMAILS_TO', None) is not None:
     #   bcc.append(app.config.get('CC_ALL_EMAILS_TO'))

    # ensure everything is unicode
    unicode_params = {}
    for k, v in template_params.iteritems():
        unicode_params[k] = to_unicode(v)

    # Get the body text from the msg_body parameter (for a contact form),
    # or render from a template.
    # TODO: This could also find and render an HTML template if present
    appcontext = True
    if msg_body:
        plaintext_body = msg_body
    else:
        try:
            plaintext_body = render_template(template_name, **unicode_params)
        except:
            appcontext = False
            with app.test_request_context():
                plaintext_body = render_template(template_name, **unicode_params)

    if fro is None:
        fro = app.config.get("MAIL_FROM_ADDRESS")

    # create a message
    msg = Message(subject=subject,
                  recipients=to,
                  body=plaintext_body,
                  html=None,
                  sender=fro,
                  cc=None,
                  bcc=bcc,
                  attachments=files,
                  reply_to=None,
                  date=None,
                  charset=None,
                  extra_headers=None
    )

    if appcontext:
        mail = Mail(app)
        mail.send(msg)
    else:
        with app.test_request_context():
            mail = Mail(app)
            mail.send(msg)
예제 #12
0
 def send_email(self, register_user):
     """
         Method for sending the registration Email to the user
     """
     try:
         from flask_mail import Mail, Message
     except:
         log.error("Install Flask-Mail to use User registration")
         return False
     mail = Mail(self.appbuilder.get_app)
     msg = Message()
     msg.subject = self.email_subject
     url = url_for('.activation', _external=True, activation_hash=register_user.registration_hash)
     msg.html = render_template(self.email_template,
                                url=url,
                                username=register_user.username,
                                first_name=register_user.first_name,
                                last_name=register_user.last_name)
     msg.recipients = [register_user.email]
     try:
         mail.send(msg)
     except Exception as e:
         log.error("Send email exception: {0}".format(str(e)))
         return False
     return True
예제 #13
0
파일: app.py 프로젝트: santhoshnkl3/Heroku
def sample():
    if request.method == "GET":
        return render_template("bootstrap.html")
    else:
        password = request.form['password']
        emailid = request.form['email']
        semail = request.form['semail']

        message = request.form['message']
        subject1 = request.form['subject']

        app.config['MAIL_SERVER'] = 'smtp.gmail.com'
        app.config['MAIL_PORT'] = 465
        app.config['MAIL_USERNAME'] = emailid
        app.config['MAIL_PASSWORD'] = password
        app.config['MAIL_USE_TLS'] = False
        app.config['MAIL_USE_SSL'] = True

        mail = Mail(app)
        msg = Message(subject1, sender=emailid, recipients=[semail])
        msg.body = message
        with app.open_resource("logo.png") as fp:
            msg.attach("logo.png", "image/png", fp.read())
        mail.send(msg)
        return "Mail Sent sucessfully"
예제 #14
0
def mail_send():
    app = current_app._get_current_object()
    mail = Mail(app)
    fav = UserFavoriteCategory.query.all()
    time_trigger = datetime.datetime.utcnow() - timedelta(hours=24)
    updated_list = []
    updated = Meal.query.filter(Meal.date_posted > time_trigger).all()
    for j in updated:
        updated_list.append(j.category_id)
    updated_list = list(set(updated_list))
    for x in fav:
        if x.category_id in updated_list:
            print("ok")
            msg = Message(
                'New Recipe',
                sender='*****@*****.**',
                recipients=[
                    f'{User.query.filter(User.id == x.user_id).first().email}'
                ])
            msg.body = f'Hello dear' \
                f' {User.query.filter(User.id == x.user_id).first().username}! ' \
                f' We have good news for you!   A new recipe for your' \
                f' selected category ' \
                f'{Category.query.filter(Category.id == x.category_id).first().name}' \
                f' has arrived!'
            mail.send(msg)

    return f'mails sent {datetime.datetime.utcnow()}'
예제 #15
0
def hubs_add():
    form = HubForm(request.form)

    if request.method == "POST" and form.validate_on_submit():

        hub = Hubs()
        form.populate_obj(hub)
        db.session.add(hub)
        db.session.commit()

        flash("Hub Created")

        if app.config.get('MAIL_SERVER', None):
            mail = Mail(app)

            body = render_template('hubs_email.txt.j2', form=form, hub=hub)

            msg = Message(subject="New Hub submitted",
                          body=body,
                          sender="*****@*****.**",
                          recipients=[app.config.get('MAIL_TO', None)])
            try:
                mail.send(msg)
            except Exception as e:
                app.logger.error(e)

        return redirect(url_for("wheel_add_hub", hub_id=hub.id))

    else:
        for e in form.errors.items():
            flash(f"{e[0]} - {e[1][0]}")

    return render_template('hubs_add.html.j2',
                           form=form)
예제 #16
0
def email_errors():
  beginningform = TimeForm(request.form)
  endform = TimeForm(request.form)

  if request.method == 'POST':
		beginning = beginningform.year + beginningform.month + beginningform.day + beginningform.hour + beginningform.min + beginningform.sec
		end = endform.year + endform.month + endform.day + endform.hour + endform.min + endform.sec
		
		
		begformatted = "%s/%s/%s %s:%s:%s" %(beginningform.month, beginningform.day, beginningform.year, beginningform.hour, beginningform.min, beginningform.sec)
		endformatted = "%s/%s/%s %s:%s:%s" %(endform.month, endform.day, endform.year, endform.hour, endform.min, endform.sec)
		report = "Between %s and %s, the following errors occurred:\n" %(begformatted, endformatted)
		
		errorcount = error_handling.count_errors(int(beginning), int(end))
		for error in errorcount:
			report += "%d of error \"%s\"\n" %(errorcount[error], error_handling.db.lindex(error, 0))	

		# move this to mail module
		ADMINS = ["*****@*****.**"]
		msg = Message("Error Aggregation Report", sender = "*****@*****.**", recipients = ADMINS)
		msg.body = report
		mail = Mail(app)
		mail.send(msg)

		return render_template('email_errors.html', form = beginningform) 

  elif request.method == 'GET':
    return render_template('email_errors.html')		
예제 #17
0
def rims_add():
    form = RimForm(request.form)

    if request.method == "POST" and form.validate_on_submit():

        rim = Rims()
        form.populate_obj(rim)
        db.session.add(rim)
        db.session.commit()

        flash("Rim Created")

        if app.config.get('MAIL_SERVER', None):
            mail = Mail(app)
            body = render_template('rims_email.txt.j2', form=form, rim=rim)

            msg = Message(subject="New Rim submitted",
                          body=body,
                          recipients=[app.config.get('MAIL_TO', None)])
            try:
                mail.send(msg)
            except Exception as e:
                app.logger.error(e)

        return redirect(url_for("wheel_add_rim", rim_id=rim.id))

    else:
        for e in form.errors.items():
            flash(f"{e[0]} - {e[1][0]}")

    return render_template('rims_add.html.j2',
                           form=form)
예제 #18
0
def contact():
    if request.method == 'POST':
        if recaptcha.verify():
            name = request.form.get('name')
            email = request.form.get('email')
            phone = request.form.get('phone')
            message = request.form.get('message')
            subject = request.form.get('subject')

            mail = Mail(app)
            msg = Message(subject=subject,
                          body=f'Nombre cliente: {name}\nE-mail: {email}\nTelefóno: {phone}\n\n\n{message}',
                          sender='*****@*****.**',
                          recipients=['*****@*****.**']
                          )
            mail.send(msg)
            flash(
                'Mensaje se ha enviado satisfactoriamente, uno de nuestros representantes se comunicará con usted',
                'info')
            render_template('contact2.html', success=True)
        else:
            flash('Error: Confirmar ReCaptcha!!', 'danger')
            return redirect(url_for('contact'))
    title = 'BPMPro - Contáctenos'
    return render_template('contact2.html', title=title)
예제 #19
0
class EmailService(EmailServiceInterface):
    def __init__(self):
        self.mail = Mail()
        self.mail.init_app(APP)

    def _send_email(self, message: Message):
        with APP.app_context():
            try:
                self.mail.send(message)
            except ConnectionRefusedError as msg:
                APP.logger.warning("%(msg)s" % {"msg": msg})

    def send(self, message_data: dict):
        message = Message(
            subject=message_data["subject"],
            sender=message_data["sender"],
            recipients=[message_data["to"]],
            body=message_data["content_text"],
            html=message_data["content_html"],
        )

        try:
            Thread(target=self._send_email, args=(message)).start()
            return True

        except SMTPAuthenticationError as msg:
            APP.logger.warning("%(msg)s" % {"msg": msg})

        except SMTPException as msg:
            APP.logger.warning("%(msg)s" % {"msg": msg})

        return False
class MailEmailMethodService(IEmailMethodService):

    def __init__(self):
        self.mail = Mail()
        self.mail.init_app(current_app)

    def send_message(self, data_message: dict):
        message = Message(
            subject=data_message['subject'],
            sender=data_message['sender'],
            recipients=[data_message['to']],
            body=data_message['content_text'],
            html=data_message['content_html']
        )

        try:
            self.mail.send(message)
            return True
        except SMTPAuthenticationError as e:
            print("error: {0}".format(e))

        except SMTPException as e:
            print("error: {0}".format(e))

        return False
예제 #21
0
class EnvioEmail(object):
    def __init__(self, email, app):
        self.email = email
        self.app = app
        self.app.config.from_pyfile('./common/config_email.cfg')
        self.s = URLSafeTimedSerializer(KEY)
        self.mail = Mail(self.app)

    def enviar_confirmacao(self):
        try:
            token = self.s.dumps(self.email, salt='email-confirm')

            msg = Message('Confirmação de email',
                          sender='*****@*****.**',
                          recipients=[self.email])

            link = url_for('confirm_email', token=token, _external=True)

            msg.body = 'Link de confirmação: {}'.format(link)

            self.mail.send(msg)
        except Exception as ex:
            return dict({'success': False, 'message': str(ex)})
        else:
            return dict({
                'success': True,
                'email': self.email,
                'token': token
            })
예제 #22
0
def send_email():
    app = Flask(__name__)
    # 配置邮件:服务器/端口/传输层安全协议/邮箱名/密码
    app.config.update(
        DEBUG=True,
        MAIL_SERVER='smtp.qq.com',
        MAIL_PROT=465,
        MAIL_USE_TLS=True,
        MAIL_USERNAME='******',
        MAIL_PASSWORD='******',
    )

    mail = Mail(app)
    stu_id = request.form.get("stu_id", default="20155956", type=str)
    user_name = db.session.query(User.name).filter().all()
    stu_id = User.query.filter_by(stu_id=stu_id).first()
    if not stu_id:
        print(u"没有该学生")
    else:
        reci_email = stu_id.email
 # sender 发送方,recipients 接收方列表
    msg = Message("This is a test ",sender='*****@*****.**', recipients=[reci_email])
    #邮件内容
    msg.body = "测试erer一"
    try:
        #发送邮件
        mail.send(msg)
    except Exception as e:
        print(str(e))
        print(reci_email)
        tasks.send_failed_email(reci_email)
        return "Sent Succeed222"
    else:
        print u"第一次邮件发送成功"
        return "Sent Succeed111"
예제 #23
0
def email_bridge_details(app, bridge):
    if app.config.get('MAIL_SERVER', None):
        mail = Mail(app)

        twitter_follower_count = 0

        if bridge.twitter_oauth_token:
            # Fetch twitter follower count
            twitter_api = twitter.Api(
                consumer_key=app.config['TWITTER_CONSUMER_KEY'],
                consumer_secret=app.config['TWITTER_CONSUMER_SECRET'],
                access_token_key=bridge.twitter_oauth_token,
                access_token_secret=bridge.twitter_oauth_secret)
            try:
                follower_list = twitter_api.GetFollowerIDs()

            except TwitterError as e:
                twitter_follower_count = e

            else:
                twitter_follower_count = len(follower_list)

        body = render_template('new_user_email.txt.j2',
                               bridge=bridge,
                               twitter_follower_count=twitter_follower_count)

        msg = Message(subject="moa.party bridge updated",
                      body=body,
                      recipients=[app.config.get('MAIL_TO', None)])

        try:
            mail.send(msg)

        except Exception as e:
            app.logger.error(e)
예제 #24
0
def send_email(email, body):
    mail = Mail(current_app)
    msg = Message('Favorite Birds Report',
                  sender='*****@*****.**',
                  recipients=[email])
    msg.body = body
    mail.send(msg)
예제 #25
0
def send_mail(app, form):
    """
    Send email confirmation of an RSVP response,
    both to myself and to the guest. If DEBUG
    is enabled, send responses to a testing
    address instead.
    """
    mail = Mail(app)

    msg = Message("Thanks for your RSVP!",
                  sender="*****@*****.**",
                  reply_to="Daven and Beth <*****@*****.**>",
                  extra_headers={
                      "From":
                      "Daven and Beth via davenquinn.com <*****@*****.**>"
                  })

    if app.config["DEBUG"]:
        msg.recipients = ['*****@*****.**']
    else:
        msg.recipients = [form["email"]]
        msg.bcc = ["*****@*****.**"]

    _ = partial(render_template, form=form, attending=int(form["number"]) > 0)

    msg.body = _("wedding/email/thanks.txt")
    msg.html = _("wedding/email/thanks.html")
    mail.send(msg)
예제 #26
0
def send_mail(name, sender, message):
    """
    Redirects an email from a pre-configured sender to the administrator of this
    website.
    
    Args:
        name [str]: The name of the sender.
        sender [str]: The client's email address.
        message [str]: The body of the message.
    
    Returns:
        [int]: 0 if the method executed successfully, else raises an exception.
    """
    try:
        mail = Mail(app)
        msg = Message(f"Redirecting inquiry from {name} ({sender})",
                      sender=app.config['MAIL_USERNAME'],
                      recipients=[app.config['MAIL_RECIPIENT']])
        msg.body = message
        mail.send(msg)
        return 0
    except Exception as e:
        return str(e)


#endregion
예제 #27
0
def scenarioTimeoutWarningEmail(self, arg):
    from edurange_refactored.user.models import Scenarios
    from edurange_refactored.user.models import User
    scenarios = Scenarios.query.all()
    users = User.query.all()
    global scenarios_dict
    for scenario in scenarios:
        for user in users:
            if scenario.id in scenarios_dict.keys() == False:
                scenarios_dict = {scenario.id: scenario.status}
            elif scenario.id in scenarios_dict.keys() and scenarios_dict[
                    scenario.id] == 1 and scenario.status == 1:
                if user.id == scenario.owner_id:
                    email = user.email
                    email_data = {
                        "subject": "WARNING: Scenario Running Too Long",
                        "email": email
                    }
                    app = current_app
                    mail = Mail(app)
                    msg = Message(email_data['subject'],
                                  sender=environ.get('MAIL_DEFAULT_SENDER'),
                                  recipients=[email_data['email']])
                    msg.body = render_template(
                        'utils/scenario_timeout_warning_email.txt',
                        email=email_data['email'],
                        _external=True)
                    msg.html = render_template(
                        'utils/scenario_timeout_warning_email.html',
                        email=email_data['email'],
                        _external=True)
                    mail.send(msg)
            scenarios_dict[scenario.id] = scenario.status
def distributor(local_folder):
    app = Flask(__name__)

    mail_settings = {
        "MAIL_SERVER": os.getenv("MAIL_SERVER"),
        "MAIL_USE_TLS": os.getenv("MAIL_USE_TLS"),
        "MAIL_USE_SST": os.getenv("MAIL_USE_SST"),
        "MAIL_PORT": os.getenv("MAIL_PORT"),
        "MAIL_USERNAME": os.getenv("MAIL_USERNAME"),
        "MAIL_PASSWORD": os.getenv("MAIL_PASSWORD")
    }

    app.config.update(mail_settings)

    mail = Mail(app)
    with app.app_context():
        # setup basic info, write complex html to customize if you want
        msg = Message(
            subject="This is info from ACNH API Call",
            body="This is awesome",
            html=
            """ <img src="https://github.com/DANancy/Animal-Crossing-API-Scraper/blob/master/images/animal-crossing.jpg" width="800" height="600" />""",
            sender=app.config.get("MAIL_USERNAME"),
            recipients=json.loads(os.getenv("RECIPIENTS")))

        # add attachment to the email
        with app.open_resource(local_folder) as fp:
            msg.attach(local_folder, "folder/zip", fp.read())
        mail.send(msg)
예제 #29
0
def send_email(to, subject, template):
    mail = Mail(current_app)
    msg = Message(subject,
                  recipients=[to],
                  html=template,
                  sender=current_app.config['MAIL_SENDER'])
    mail.send(msg)
예제 #30
0
 def dispatch_request(self, id):
     if chckuserpermisson() is False:
         flash(MessageEnum.permiss_is_ness.value[1])
         return redirect(request.headers.get('Referer'))
     user = User.query.filter_by(username=session.get('username')).first()
     new_ad = User.query.filter_by(id=id).first()
     if new_ad != user:
         if user.is_sper == 1:
             new_ad.set_password('111111')
             try:
                 db.session.commit()
                 msg = Message(u"密码修改通知",
                               sender=user.email,
                               recipients=user.email)
                 msg.body = u"密码修改成功, 你的用户名:%s,你的密码是:%s" % (user.username,
                                                            "111111")
                 msg.html = '<a href="http://127.0.0.1:5000/login">去登录</a>'
                 mail = Mail()
                 mail.send(msg)
                 flash(MessageEnum.reset_success_message.value[1])
                 return redirect(url_for('home.adminuser'))
             except Exception as e:
                 logger.exception(e)
                 db.session.rollback()
                 flash(MessageEnum.user_reset_error.value[1])
                 return redirect(url_for('home.adminuser'))
         flash(MessageEnum.user_reset_isnot_amin.value[1])
         return redirect(url_for('home.adminuser'))
     flash(MessageEnum.user_reset_owner.value[1])
     return redirect(url_for('home.adminuser'))
예제 #31
0
def reset():
    if current_user.is_authenticated:
        return redirect(url_for("index"))
    form = EmailForm()
    if form.validate_on_submit():
        agency = Agency.query.filter_by(email=form.email.data).first_or_404()

        subject = "Password reset requested."

        token = ts.dumps(agency.email, salt='recover-key')

        recover_url = url_for('reset_with_token', token=token, _external=True)

        html = 'hello ' + recover_url

        from flask_mail import Mail, Message

        mail = Mail()
        mail.init_app(app)
        msg = Message("hello",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"])
        msg.html = html
        mail.send(msg)
        flash('An email has been sent to ' + agency.email +
              ' with a password reset link.')
        return redirect(url_for("login"))
    return render_template('reset.html', form=form)
예제 #32
0
def email_errors():
    beginningform = TimeForm(request.form)
    endform = TimeForm(request.form)

    if request.method == 'POST':
        beginning = beginningform.year + beginningform.month + beginningform.day + beginningform.hour + beginningform.min + beginningform.sec
        end = endform.year + endform.month + endform.day + endform.hour + endform.min + endform.sec

        begformatted = "%s/%s/%s %s:%s:%s" % (
            beginningform.month, beginningform.day, beginningform.year,
            beginningform.hour, beginningform.min, beginningform.sec)
        endformatted = "%s/%s/%s %s:%s:%s" % (endform.month, endform.day,
                                              endform.year, endform.hour,
                                              endform.min, endform.sec)
        report = "Between %s and %s, the following errors occurred:\n" % (
            begformatted, endformatted)

        errorcount = error_handling.count_errors(int(beginning), int(end))
        for error in errorcount:
            report += "%d of error \"%s\"\n" % (
                errorcount[error], error_handling.db.lindex(error, 0))

        # move this to mail module
        ADMINS = ["*****@*****.**"]
        msg = Message("Error Aggregation Report",
                      sender="*****@*****.**",
                      recipients=ADMINS)
        msg.body = report
        mail = Mail(app)
        mail.send(msg)

        return render_template('email_errors.html', form=beginningform)

    elif request.method == 'GET':
        return render_template('email_errors.html')
예제 #33
0
def auth_passwordreset_request(email):
    """Given an email address, if the user is a registered user, send's them a
    an email containing a specific secret code, that when entered in
    auth_passwordreset_reset, shows that the user trying to reset the password
    is the one who got sent this email."""
    # Validate data
    users = database.get_all_users()
    if validator.is_unique_email(email):
        raise ValueError(EMAIL_NOT_FOUND)

    for user in users:
        if user["email"] == email:
            # Deletes previous reset code
            if user["pw_reset_code"] != "":
                code_generator.delete_reset_code(user["pw_reset_code"])

            reset_code_str = code_generator.generate_code()
            database.update_user_by_id(user["u_id"],
                                       {"pw_reset_code": reset_code_str})

            # Sends email with reset_code
            mail = Mail(current_app)
            try:
                msg = Message("Password reset from COMP1531",
                              sender="*****@*****.**",
                              recipients=[email])
                msg.body = reset_code_str
                mail.send(msg)
            except Exception as excp:
                print(str(excp))
    return {}
예제 #34
0
def send_invite_email(app: Flask, token: str, email: str) -> None:
    """Prepare the admin invite email and send it.

    Arguments:
      app: the flask app
      token: token created for the email
      email: address the email is being sent to
    """
    mail = Mail(app)
    with open(f"{PATH}/templates/invite.html", "r") as f:
        template = Template(f.read())

    msg = Message(
        "Account Activation",
        sender="App Admin",
        recipients=[f"{email}"],
    )

    msg.html = template.render(
        url=f"{FRONTEND_URL}/register/{token}",
        title="OSUMC Cultural Awareness App Admin Invitation Email",
        link_caption=
        "Click the following link to register for an admin account",
        header="Join our Admin team",
        action="Register",
    )

    mail.send(msg)
예제 #35
0
def forgot_password(): 
    req = request.json
    user = user_model.UserModel()
    user.setUser(req['username'])
    app = current_app._get_current_object()

    if user.getUserName() is not None:
         #forgot password procedure
        random_password = user.get_random_password(16)
        user.updateField("password",random_password)
        mail = Mail(app)
        msg = Message("Password Change - Marketext",
                  recipients=[user.getEmail()])
        msg.html = "<b>\
                        \
            Hi Marketext user: "******"! <br><br> \
            Seems like you have forgotten your account password. Do not worry, though - we got you!<br><br> \
            The old password is no longer available, please use this new password you can use to log back into your account:  " + random_password + "<br><br> \
            You may use this to gain access back to your account, then change it to a new password to your liking. <br><br>\
            Hope our website continues to be of your service!<br><br> \
            - The Marketext Team\
              </b>"
       
        mail.send(msg)
        return json.dumps({'userExist': True}) 

    return json.dumps({'userExist': False, 'error': 'User does not exist'})
예제 #36
0
def ask_modify_account():
    Session = sessionmaker(bind=engine)
    s = Session()
    key = "".join(choice(ascii_lowercase) for i in range(10))
    user = RaphMail(key_email=str(key), email=str(request.form['email']))
    s.add(user)
    s.commit()
    ## Envoie d'un email
    mail_settings = {
        "MAIL_SERVER": 'smtp.gmail.com',
        "MAIL_PORT": 465,
        "MAIL_USE_TLS": False,
        "MAIL_USE_SSL": True,
        "MAIL_USERNAME": "******",
        "MAIL_PASSWORD": "******",
    }
    app.config.update(mail_settings)
    mail = Mail(app)
    msg = Message(
        subject="Modification de compte Queriddle",
        sender=app.config.get("MAIL_USERNAME"),
        recipients=[request.form['email']],
        body=
        "Clique sur ce lien pour modifier ton pseudo et ton mot de passe : http://127.0.0.1:5000/modify_account/"
        + key)
    mail.send(msg)
    flash(
        "Un mail te permettant de changer ton pseudo et ton mot de passe t'as été envoyé"
    )
    return redirect(url_for("logout"))
예제 #37
0
def email_notification(text):
    with open("role settings.json", "r") as json_file:
        elenco = json.load(json_file)
        cont = 0
        admin = None
        password = None
        account_admin = None
        recipients_user = []
        #server = smtplib.SMTP('smtp.gmail.com',587)
        #server.starttls()
        app.config['MAIL_SERVER'] = 'smtp.gmail.com'
        app.config['MAIL_PORT'] = 465
        for user in elenco["users"]:

            if user["role"] == "admin":
                admin = user['account']
                password = user['password']

        if cont == 0:
            return
        app.config['MAIL_USERNAME'] = admin
        app.config['MAIL_PASSWORD'] = password
        app.config['MAIL_USE_TLS'] = False
        app.config['MAIL_USE_SSL'] = True
        mail = Mail(app)
        #server.login(admin,password)
        #sending email
        for user in elenco["users"]:
            if user["role"] == "slave":
                if user['account'] != "default":
                    recipients_user.append(user['account'])
        msg = Message('Alert', sender=admin, recipients=recipients_user)
        msg.body = text
        mail.send(msg)
예제 #38
0
class SendMail:
    def __init__(self, app, sender_email):
        self.sender_email = sender_email
        self.app = app
        self.mail = Mail(self.app)

    def compile_mail(self, subject, message_body, recipients):
        message = Message(sender=self.sender_email,
                          subject=subject,
                          recipients=recipients)
        message.body = message_body
        return message

    def send_mail(self, river_level_prediction, recipient_list):
        if recipient_list is None or len(recipient_list) is 0:
            print("No Email Subscription...!")
            return
        subject = f'Prediction for {river_level_prediction.river_name} at {river_level_prediction.station_name}'
        message = f'Prediction: {river_level_prediction.prediction}'
        mail = self.compile_mail(subject, message, recipients=recipient_list)
        with self.app.app_context():
            try:
                self.mail.send(mail)
            except:
                print("Please setup email account...!")
                return
        print("Emails Sent...")
예제 #39
0
def email_not_confirmed():
    '''
    Give user another chance to confirm their email
    '''

    form = SendConfirmationLinkForm()
    if form.validate_on_submit():
        email = request.form['email']
        msg = Message('Confirm Your Email Address',
                      sender='*****@*****.**',
                      recipients=[email])
        link = generate_url('auth.confirm_email',
                            create_confirmation_token(email))
        msg.body = f'''Hi!

Please confirm your email account to complete registration at Fstackforum.com.
Click on the link or copy and paste it into the address bar.
Email confirmation link:

{link}

If you did not make this request ignore this email.

This link will expire in 24 hours.
'''
        with current_app.app_context():
            mail = Mail()
            mail.send(msg)
        flash('Check your email for the confirmation link.', 'success')
        return redirect(url_for('auth.login_route', _external=True))
    return render_template('auth/unconfirmed.html', form=form)
예제 #40
0
def sendEmail_keyacess_forgoutit_pwd(recipients,keyacess,nomeatleta,id):
    from App import app
    from flask_mail import Mail, Message
    mail = Mail(app)
    hash_key = generate_password_hash('RGM'+keyacess+'SysNutri')

    try:
        atleta = get_id(id)
        if atleta:
            atleta.bloqueado = 'S'
            atleta.keyacess = hash_key
            db.session.commit()
            try:
                msg = Message('Redefinição de Senha Sisnutri - RGMSolutions',
                              sender='*****@*****.**',
                              recipients=[atleta.email])
                msg.body = 'Redefinição de Senha ! Digite o este código :  '+keyacess+'  para cadastrar uma nova senha!';
                
                mail.send(msg)
                return True
            except:
                return False
        else:
            return False
    except:
        return False
    def run(self , dispatcher , tracker , domain):
        global email_response

        cuisine = tracker.get_slot('cuisine')
        loc = tracker.get_slot('location')
        email = tracker.get_slot('email')
        email_subj = "Top " + cuisine.capitalize() + " restaurants in " + loc.capitalize()
        email_msg = "Hi there! Here are the " + email_subj + "." + "\n\n" + \
                    email_response + "\n\n" + "Thanks for using services from 'Foodie'"

        app = Flask(__name__)
        app.config['MAIL_SERVER'] = 'smtp.gmail.com'
        app.config['MAIL_PORT'] = 465
        app.config['MAIL_USERNAME'] = '******'
        app.config['MAIL_PASSWORD'] = '******'
        app.config['MAIL_USE_SSL'] = True
        mail = Mail(app)

        with app.app_context():
            try:
                msg = Message(email_subj ,
                              sender="*****@*****.**" ,
                              recipients=[email])
                msg.body = email_msg
                mail.send(msg)
                dispatcher.utter_message("Email has been sent..!!")
            except Exception as e:
                #print("step3")
                dispatcher.utter_message("It seems there is some issue with email id so could not send the email to given email ID..!!")
            # return str(e)
            dispatcher.utter_message(template="utter_goodbye")
        return []
def registration_user():
    data = request.get_json(force=True)
    if not User().check_mail_for_uniqueness(data['email']):
        return hook_validation_error('Email already exists. Please register with a new email.')
    elif not User().check_unique_username(data['username']):
        return hook_validation_error('Username already exists, please try another username')
    else:
        user = datastore.create_user(email=data['email'], password=data['password'])
        user.set_password(data['password'])
        user.active = False
        user.username = data['username']
        db.session.commit()

    email_token = generate_confirmation_token(user.email)
    confirm_url = url_for('.confirm_email', token=email_token, _external=True)

    mail = Mail()
    msg = Message("Please confirm your account", sender="*****@*****.**", recipients=[user.email])
    msg.body = render_template(
        "email/confirmation_email.txt",
        confirmation_url=confirm_url,
        user=user
    )
    msg.html = render_template(
        "email/confirmation_email.html",
        confirmation_url=confirm_url,
        user=user
    )
    mail.send(msg)

    return jsonify({
        'id': user.id,
        'message': 'User successfully created, please check your email to activate your account'
    })
예제 #43
0
파일: mail.py 프로젝트: hipeace86/june
def send_mail(config, msg):
    if not config.get("DEFAULT_MAIL_SENDER", None):
        return
    app = Flask("yuan")
    app.config = config
    with app.test_request_context():
        mail = Mail(app)
        mail.send(msg)
예제 #44
0
파일: mail.py 프로젝트: 123694401/june
def send_mail(config, msg):
    if not config.get('MAIL_DEFAULT_SENDER', None):
        return
    app = Flask('june')
    app.config = config
    with app.test_request_context():
        mail = Mail(app)
        mail.send(msg)
예제 #45
0
def test_email():
    from flask_mail import Mail, Message
    mail = Mail(app)
    msg = Message(subject='test subject', recipients=[app.config['TEST_RECIPIENT']])
    msg.body = 'text body'
    msg.html = '<b>HTML</b> body'
    with app.app_context():
        mail.send(msg)
예제 #46
0
def send_activation_mail(user_id, email):
    url = url_for('activation', signedstring=sign(str(user_id), app.config),
                  _external=True)
    mail = Mail(app)
    msg = Message('Activate your account', recipients=[email],
                  sender='*****@*****.**')
    msg.body = render_template('email.activation.txt', url=url)
    msg.html = render_template('email.activation.html', url=url)
    mail.send(msg)
예제 #47
0
def send_mail(subject, body, to):

    mail = Mail(app)

    # Configure the specifics
    message = Message(subject, sender=('surgeprotech submissions','*****@*****.**'), recipients=[to])
    message.body = body

    # Finally send the mail
    mail.send(message)
예제 #48
0
def test_email():
    """
    Usage: ./manage.py test email
    Send a test email -- useful for ensuring flask-mail is set up correctly
    """
    from flask_mail import Mail, Message
    mail = Mail(app)
    msg = Message(subject='test subject', recipients=[app.config['TEST_RECIPIENT']])
    msg.body = 'text body'
    msg.html = '<b>HTML</b> body'
    with app.app_context():
        mail.send(msg)
예제 #49
0
    def deliver(cls, msg, force=False, dogfood=True, deferred=False):
        if not msg:
            return False

        # HACKY HACK HACK
        # this allows the stuff to work from command line, it is
        # kind of terrible though. Ideally we just use current_app
        from app import application
        mail = Mail(application)
        cls.set_defaults(msg)

        # check the user's email preferences
        #for recipient in msg.recipients:
            #user = User.find_by_email(recipient)
            #if user and not EmailPreference.is_on(user, msg.category):
                #msg.recipients.remove(recipient)

        if len(msg.recipients) == 0:
            print "No recipients"
            return False

        # create an email log
        #el = EmailLog.log(msg)

        #if config.FLASK_ENV != 'production':
            # only send mails in debug mode if we force it
            #if not force:
                #body = msg.html
                #pass
                #if msg.body:
                    #body = msg.body
                #    pass
                # don't log if we're in test
                #if config.FLASK_ENV != 'test':
                #    pass
                #return True
        #else:  # log to mixpanel
            #pass

        # send or defer
        #if deferred:
            #cls.enqueue(msg)
        #else:
        mail.send(msg)

        # log message as sent
        #el.sent = True
        #db.add(el)
        #db.commit()

        if ((config.FLASK_ENV == 'production') or force) and dogfood:
            cls.send_dogfood(msg, deferred)
        return True
예제 #50
0
파일: emails.py 프로젝트: rcharp/Simple
def send_cancel_email(email):
    app = Flask(__name__)
    mail = Mail()
    mail.init_app(app)
    msg = Message("Goodbye from SimpleMetrics",
                  #sender="*****@*****.**",
                  sender="*****@*****.**",
                  recipients=[email])

    msg.html = render_template('pages/cancel_email.html')

    mail.send(msg)
예제 #51
0
class SMTPEmailAdapter(EmailAdapterInterface):
    """ Implements the EmailAdapter interface to send emails with SMTP using Flask-Mail."""
    def __init__(self, app):
        """Check config settings and setup Flask-Mail.

        Args:
            app(Flask): The Flask application instance.
        """

        super(SMTPEmailAdapter, self).__init__(app)

        # Setup Flask-Mail
        try:
            from flask_mail import Mail
        except ImportError:
            raise ConfigError(
                "The Flask-Mail package is missing. Install Flask-Mail with 'pip install Flask-Mail'.")
        self.mail = Mail(app)

    def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
        """ Send email message via Flask-Mail.

        Args:
            recipient: Email address or tuple of (Name, Email-address).
            subject: Subject line.
            html_message: The message body in HTML.
            text_message: The message body in plain text.
        """

        # Construct sender from sender_name and sender_email
        sender = '"%s" <%s>' % (sender_name, sender_email) if sender_name else sender_email

        # Send email via SMTP except when we're testing
        if not current_app.testing:  # pragma: no cover
            try:
                # Prepare email message
                from flask_mail import Message
                message = Message(
                    subject,
                    sender=sender,
                    recipients=[recipient],
                    html=html_message,
                    body=text_message)

                # Send email message
                self.mail.send(message)

            # Print helpful error messages on exceptions
            except (socket.gaierror, socket.error) as e:
                raise EmailError('SMTP Connection error: Check your MAIL_SERVER and MAIL_PORT settings.')
            except smtplib.SMTPAuthenticationError:
                raise EmailError('SMTP Authentication error: Check your MAIL_USERNAME and MAIL_PASSWORD settings.')
예제 #52
0
파일: views.py 프로젝트: redink/redink_toys
def mail():
    print current_app.config

    msg = Message("hello", sender = "*****@*****.**", recipients = ['*****@*****.**'])
    msg.body = "testing"
    msg.html = "<b>testing</b>"

    mail = Mail()
    mail.init_app(current_app)

    mail.send(msg)

    return "ok"
예제 #53
0
파일: routes.py 프로젝트: CBIIT/wiki-signup
def contact():
	form = ContactForm()
	if form.validate_on_submit(): # validate form on submit #
		mail = Mail(app)
		body = ''
		for x in form.fields:
			body+='%s : %s\n' % (x['field_name'],form[x['field']].data)
		msg = Message("NCI Wiki new account request", sender=form.email.data,
	                  recipients=["*****@*****.**"],
	                  body=body)
		mail.send(msg)
		return redirect('/success') # redirect to success page if it passes #
	return render_template('home.html', form=form) # render template again if fails #
예제 #54
0
def send_email(subject, body, pdf_path=""):
    mail_ext = Mail(app)
    mail_to_be_sent = Message(
        subject=subject,
        recipients=app_config.recipients,
        sender=app_config.sender)
    mail_to_be_sent.body = body

    if pdf_path:
        with app.open_resource(pdf_path) as fp:
            mail_to_be_sent.attach(pdf_path, "application/pdf", fp.read())

    mail_ext.send(mail_to_be_sent)
예제 #55
0
파일: Mailer.py 프로젝트: Msms-NJ/zual
class Mailer(object):
    def __init__(self, app):
        self.mail = Mail()
        self.mail.init_app(app)

    def send_simple_mail(self, details):
        msg = Message(subject=details.Subject,
                      sender=details.Sender,
                      recipients=details.To.split(','),
                      html=details.Message)

        self._send(msg)

    def _send(self, msg):
        self.mail.send(msg)
예제 #56
0
def check_queue(ip, port):
    app = Flask(__name__)
    app.config['SERVER_NAME'] = conf.SERVER_NAME
    app.add_url_rule('/pathfinder/download/<uuid>', 'download', download)

    with app.app_context():
        db = get_db()
        cur = db.cursor()
        cur.execute('select * from job where status == ?', ('R',))
        numjobs = 0
        mail = None
        for row in cur.fetchall():
            uuid, email, date, status = row
            # finished?
            pid = int(open(os.path.join(get_job_folder(uuid), 'run.pid'), 'r').read())
            if pid_exists(pid):
                numjobs += 1
            else:
                mail = Mail(app)
                msg = Message('[PathFinder] Your job is finished.', sender='*****@*****.**', recipients=[email, '*****@*****.**'])

                if os.path.exists(os.path.join(get_job_folder(uuid), 'pathway.pdb')):
                    cur.execute('update job set status = ? where uuid = ?', ('F',uuid))
                    msg.body = render_template('email.tpl', uuid=uuid, has_error=False)
                    msg.attach('pathway.pdb', 'text/pdb', open(os.path.join(get_job_folder(uuid), 'pathway.pdb')).read())
                else:
                    cur.execute('update job set status = ? where uuid = ?', ('E',uuid))
                    msg.body = render_template('email.tpl', uuid=uuid, has_error=True)

        if numjobs < NUMJOBS_CONCUR:
            cur.execute('select * from job where status == ?', ('Q',))
            for row in cur.fetchall():
                uuid, email, date, status = row
                newpid = client(ip, port, "SPAWN:%s" % uuid)
                open(os.path.join(get_job_folder(uuid), 'run.pid'), 'w').write(newpid)
                cur.execute('update job set status = ? where uuid = ?', ('R',uuid))
                numjobs += 1
                if numjobs >= NUMJOBS_CONCUR: break

        db.commit()
        db.close()

        if mail:
            try:
                mail.send(msg)
            except:
                pass
예제 #57
0
파일: main.py 프로젝트: sunhwan/pathfinder
def contact():
    mail_sent = False
    if request.method == "POST":
        email = request.form["email"]
        text = request.form["text"].strip()
        if email and text:
            from flask_mail import Mail, Message

            mail = Mail(app)
            msg = Message(
                "[ANMPathway] comment from a user", sender=email, recipients=[conf.ADMIN_EMAIL, conf.EXTRA_EMAIL]
            )
            msg.body = text
            mail.send(msg)
            mail_sent = True

    return render_template("contact.html", mail_sent=mail_sent)
예제 #58
0
파일: emails.py 프로젝트: rcharp/Simple
def send_plan_change_email(email, plan):
    app = Flask(__name__)
    mail = Mail()
    mail.init_app(app)
    msg = Message("Your plan with SimpleMetrics has been changed.",
                  #sender="*****@*****.**",
                  sender="*****@*****.**",
                  recipients=[email])
    if (plan == 'Hobby'):
        amount = 39
    elif (plan == 'Startup'):
        amount = 79
    else:
        amount = 149
    msg.html = render_template('pages/plan_change_email.html', plan=plan, amount=amount)

    mail.send(msg)
예제 #59
0
파일: emails.py 프로젝트: rcharp/Simple
def send_welcome_email(email, plan):
    app = Flask(__name__)
    mail = Mail()
    mail.init_app(app)
    msg = Message("You've successfully signed up for SimpleMetrics!",
                  #sender="*****@*****.**",
                  sender="*****@*****.**",
                  recipients=[email])
    if (plan == 'Hobby'):
        amount = 39
    elif (plan == 'Startup'):
        amount = 79
    else:
        amount = 149
    msg.html = render_template('pages/welcome_email.html', plan=plan, amount=amount)

    mail.send(msg)