Python Flask电子邮件表单示例

时间:2017-05-02 00:50:45

标签: python flask

我想在我的网站上建立一个联系表格。我到处都可以找到PHP电子邮件表单,但根本没有Flask示例。我不知道自己该怎么做,所以我问是否有人可以从头开始告诉我 - 如何使用Flask在网站上发送电子邮件联系表格?

1 个答案:

答案 0 :(得分:3)

假设:

  1. 您有一个html表单,将相关信息发送到/process_email
  2. 您设置的Gmail帐户可以发送电子邮件(在下面称为testaccount)
  3. 你会找到类似的东西:

    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'
    

    有关示例和更多信息,请参阅https://code.tutsplus.com/tutorials/intro-to-flask-adding-a-contact-page--net-28982https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xi-email-support