简体   繁体   中英

Python Flask e-mail form example

I wanted to make a contact form on my website. I can find PHP e-mail forms everywhere, but simply there are no Flask examples. I have no idea how to do it myself, so I'm asking if there is anyone who could tell me from scratch - how to make an e-mail contact form on website using Flask?

Assuming:

  1. You have an html form sending the relevant information to /process_email
  2. You have a Gmail account set up to send emails from (called testaccount in the below)

You would be looking for something like:

from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)

app.config.update(dict(
    MAIL_SERVER = 'smtp.googlemail.com',
    MAIL_PORT = 465,
    MAIL_USE_TLS = False,
    MAIL_USE_SSL = True,
    MAIL_USERNAME = 'testaccount',
    MAIL_PASSWORD = '[password]'
))

mail = Mail(app)

@app.route('/process_email', methods=['POST'])
def process_email():
    msg = Message('Test', sender='testaccount@gmail.com', recipients=['your@email.com'])
    msg.body = 'This is a test email' #Customize based on user input
    mail.send(msg)

    return 'done'

See https://code.tutsplus.com/tutorials/intro-to-flask-adding-a-contact-page--net-28982 and https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xi-email-support for examples and more information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM