如何通过HTML按钮在Flask中运行Python发送邮件脚本
Hey there, let's get your Flask app set up so clicking a button sends an email. Here's a straightforward, step-by-step solution that ties your HTML frontend to the email-sending backend.
1. Project Structure
First, organize your project like this to keep things clean:
your_flask_app/ ├── app.py # Flask backend logic ├── templates/ │ └── index.html # HTML frontend page └── .env # (Optional) For secure credential storage
2. Flask Backend Code (app.py)
This code sets up a route to handle the button click, plus the core email-sending logic. We'll use Python's built-in smtplib for emails and keep sensitive info out of the code with environment variables.
from flask import Flask, render_template, request import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import os from dotenv import load_dotenv # Install via `pip install python-dotenv` # Load sensitive data from .env file load_dotenv() app = Flask(__name__) # Fetch email credentials from environment variables EMAIL_USER = os.getenv("EMAIL_USER") EMAIL_PASS = os.getenv("EMAIL_PASS") def send_test_email(): """Handles the actual email-sending process""" try: # Configure email details sender = EMAIL_USER receiver = "recipient@example.com" # Replace with your target email subject = "Test Email from Flask Button" body = "This email was triggered by clicking a button in a Flask web app!" # Build the email message msg = MIMEMultipart() msg["From"] = sender msg["To"] = receiver msg["Subject"] = subject msg.attach(MIMEText(body, "plain")) # Connect to your email provider's SMTP server (Gmail example below) with smtplib.SMTP("smtp.gmail.com", 587) as server: server.starttls() # Enable secure TLS connection server.login(sender, EMAIL_PASS) server.sendmail(sender, receiver, msg.as_string()) return True # Return success status to frontend except Exception as e: print(f"Email failed to send: {str(e)}") return False # Return failure status if something goes wrong @app.route("/") def home(): # Render the main page return render_template("index.html") @app.route("/send-email", methods=["POST"]) def trigger_email(): # This route runs when the button is clicked email_sent = send_test_email() # Pass the result back to the template for user feedback return render_template("index.html", email_sent=email_sent) if __name__ == "__main__": app.run(debug=True)
3. HTML Frontend (templates/index.html)
This simple page has a button that submits a form to our Flask route, plus feedback to let the user know if the email sent successfully.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Send Email with Flask</title> </head> <body> <h1>Click the Button to Send an Email</h1> <!-- Form that sends a POST request to our /send-email route --> <form method="POST" action="/send-email"> <button type="submit">Send Test Email</button> </form> <!-- Show success/failure message after submission --> {% if email_sent is defined %} {% if email_sent %} <p style="color: green; margin-top: 10px;">✅ Email sent successfully!</p> {% else %} <p style="color: red; margin-top: 10px;">❌ Failed to send email. Check server logs for details.</p> {% endif %} {% endif %} </body> </html>
4. Key Setup Steps & Notes
- Secure Credential Storage: Create a
.envfile in your project root with these lines (replace with your actual info):EMAIL_USER=your-email@gmail.com EMAIL_PASS=your-app-password # For Gmail, use an App Password if 2FA is enabled - SMTP Provider Adjustments: Tweak the SMTP server details in
send_test_email()for your email service:- Outlook/Office 365:
smtp.office365.com:587 - Yahoo:
smtp.mail.yahoo.com:587 - 163/126 Mail:
smtp.163.com:25
- Outlook/Office 365:
- Install Dependencies: Run
pip install flask python-dotenvto get the required packages. - Production Warning: Never use
debug=Truein a live production environment—it exposes sensitive data.
5. Test It Out
- Run
python app.pyto start the Flask server. - Open
http://localhost:5000in your browser. - Click the "Send Test Email" button. You'll see a success/failure message, and the email should arrive in the recipient's inbox (check spam if it doesn't show up immediately).
内容的提问来源于stack exchange,提问作者Seong
相关产品推荐
相关产品推荐

