I am creating a contact form so that if the user have anything to say, they will submit a form to the admin using their google email.
I use Flask and smtplib to apply.
Here is my code:
MAIL_ADDRESS = os.environ.get("EMAIL_KEY")
MAIL_APP_PW = os.environ.get("PASSWORD_KEY")
@app.route("/contact", methods=["GET", "POST"])
def contact():
if request.method == "POST":
data = request.form
send_email(data["name"], data["email"], data["phone"], data["message"])
return render_template("contact.html", msg_sent=True, current_user=current_user)
return render_template("contact.html", msg_sent=False, current_user=current_user)
def send_email(name, email, phone, message):
email_message = f"Subject:New Message\n\nName: {name}\nEmail: {email}\nPhone: {phone}\nMessage:{message}"
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(user=MAIL_ADDRESS, password=MAIL_APP_PW)
connection.sendmail(from_addr=email, to_addrs=MAIL_ADDRESS, msg=email_message)
I already created an app password in my Gmail and also used the environment variables. Am I missing something or there is something in my codde that is not correct?
Here is my error:
Traceback (most recent call last):
File "/Users/daotronggiabao/Downloads/day-71-starting-files-blog-for-deployment/main.py", line 286, in send_email
connection.login(user=MAIL_ADDRESS, password=MAIL_APP_PW)
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/smtplib.py", line 739, in login
(code, resp) = self.auth(
^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/smtplib.py", line 652, in auth
authobject(challenge).encode('ascii'), eol='')
AttributeError: 'NoneType' object has no attribute 'encode'
I appreciate any suggestion.