Forums

Sending emails with Flask-Mail and threads

I want to send emails using Flask Mail and threads. This is my code:

app = Flask(__name__)
app.config.from_object(DevelopmentConfig)
csrf = CSRFProtect()
mail = Mail()

def send_email(email, user):
    msg = Message('Message',
        sender = app.config['MAIL_USERNAME'],
        recipients = [email]
        )
    msg.html = render_template('email_for_client.html', client = user)
    mail.send(msg)

def send_email_team(email, user, message):
    msg = Message('Message',
        sender = app.config['MAIL_USERNAME'],
        recipients = ["myemail@email.com"]
        )
    msg.html = render_template('email_for_team.html', email = email, client = user, message = message)
    mail.send(msg)

@app.route('/info/', methods=['GET','POST'])
def info():
    contact_form = forms.ContactForm()
    if request.method == 'POST' and contact_form.validate_on_submit():

        @copy_current_request_context
        def send_message(email, user):
            send_email(email, user)

        sender = threading.Thread(
            name = 'mail_sender',
            target = send_message,
            args = (contact_form.email.data, contact_form.name.data),
        )
        sender.start()

        @copy_current_request_context
        def send_message_team(client_email, client_user, client_message):
            send_email_team(client_email, client_user, client_message)

        sender_team = threading.Thread(
            name = 'mail_sender_team',
            target = send_message_team,
            args = (contact_form.email.data, contact_form.name.data, contact_form.message.data)
        )
        sender_team.start()
        return redirect(url_for('success'))
    return render_template("contacto.html", form = contact_form)

@app.route('/success/')
def success():
    return render_template('success.html')

db.init_app(app)
with app.app_context():
    db.create_all()
mail.init_app(app)

if __name__ == '__main__':
    csrf.init_app(app)
    app.run()

There are no errors in the code, it but does not send emails; It only sends them every time I reload the web (reload button - Web Tab in Configuration). I'm running the app on a virtual environment and Python 2.7 Help me! please.

Threads don't work in PythonAnywhere web apps. You'll need to send your email either in the request itself, or by writing the email to the database and using a scheduled task to send the email later.