Question:
Hey guys, I have created a form in HTML and the data is stored in a variable in Flask. However, they are in a function called ‘submit’ and they are not global. I tried using the global keyword but it doesn’t seem to work. I then tried to send an email with these variables but they give me a ‘None’ output. Can someone help me?
Repl link:
https://replit.com/@NateDhaliwal/Send-email-from-form?s=app
from flask import Flask,request
import os, smtplib # Import the smtp library
from email.mime.multipart import MIMEMultipart # Import the mime library to create multipart messages
from email.mime.text import MIMEText # Import the mime library to create text messages
app = Flask(__name__)
@app.route('/')
def index():
return '''<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Contact Form</h1>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message" rows="5" cols="30" required></textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
'''
global name
global email
global message
name=None
email=None
message=None
@app.route('/submit', methods=['POST'])
def submit():
global name
global email
global message
name= request.form['name']
email= request.form['email']
message= request.form['message']
# Do something with the form data (store in a variable, process, etc.)
# For this example, we will just print the form data
return "Form submitted successfully!",name,email,message
password = os.environ['mailPassword']
username = os.environ['mailUsername']
receiver=username
def sendMail():
email = f'''Name: {name}
Message: {message}''' # Contents of the message
server = "smtp.gmail.com" # Address of the mail server, change it to yours if you need to
port = 587 # Port of the mail server, change it to yours if you need to
s = smtplib.SMTP(host = server, port = port) # Creates the server connection using the host and port details
s.starttls() # Sets the encryption mode
s.login(username, password) # Logs into the email server for us
msg = MIMEMultipart() # Creates the message
msg['To'] = receiver # Sets the receiver's email address
msg['From'] = username # Sets the sender's email address
msg['Subject'] = "Form data" # Sets the subject of the message
msg.attach(MIMEText(email, 'html')) # Attaches the email content to the message as html
s.send_message(msg) # Sends the message
del msg # Deletes the message from memory
sendMail() # Call the subroutine to test it.
def printMe():
sendMail()
printMe()
app.run(host='0.0.0.0', port=8080)