Error in python Flask-Mail, I have KeyError MAIL_DEFAULT_SENDER or other

Question:

`

import re
import os
from flask import Flask, request, render_template, current_app
from flask_mail import Mail, Message

app = Flask(__name__)

app.config['MAIL_DEFAULT_SENDER'] = os.environ['MAIL_DEFAULT_SENDER']
app.config["MAIL_PASSWORD"] = os.environ["MAIL_PASSWORD"]
app.config["MAIL_PORT"] = 587
app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USERNAME"] = os.environ["MAIL_USERNAME"]
mail = Mail(app)

SPORTS = [
    "Basketball",
    "Soccer",
    "Ultimate Frisbee"
]

@app.route("/")

def index():
    return render_template("index.html", sports=SPORTS)

@app.route("/register", methods=["POST"])

def register():
    name = request.form.get("name")
    email = request.form.get("email")
    sport = request.form.get("sport")

    if not name or not email or sport not in SPORTS:
        return render_template("failure.html")

    message = Message("You are registered!", recipients=[email])
    mail.send(email)

    return render_template("success.html")

`

$ python -m flask run
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "C:Python311Libsite-packagesflask__main__.py", line 3, in <module>
    main()
  File "C:Python311Libsite-packagesflaskcli.py", line 1047, in main
    cli.main()
  File "C:Python311Libsite-packagesclickcore.py", line 1055, in main
    rv = self.invoke(ctx)
         ^^^^^^^^^^^^^^^^
  File "C:Python311Libsite-packagesclickcore.py", line 1657, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:Python311Libsite-packagesclickcore.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:Python311Libsite-packagesclickcore.py", line 760, in invoke
    return __callback(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:Python311Libsite-packagesclickdecorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:Python311Libsite-packagesclickcore.py", line 760, in invoke
    return __callback(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:Python311Libsite-packagesflaskcli.py", line 911, in run_command
    raise e from None
  File "C:Python311Libsite-packagesflaskcli.py", line 897, in run_command
    app = info.load_app()
          ^^^^^^^^^^^^^^^
  File "C:Python311Libsite-packagesflaskcli.py", line 308, in load_app
    app = locate_app(import_name, name)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:Python311Libsite-packagesflaskcli.py", line 218, in locate_app
    __import__(module_name)
  File "C:*my_folders**my_folders*froshimsemailapp.py", line 8, in <module>
    app.config['MAIL_DEFAULT_SENDER'] = os.environ['MAIL_DEFAULT_SENDER']
                        

                ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen os>", line 678, in __getitem__
KeyError: 'MAIL_DEFAULT_SENDER'

What does error above even mean?? i am finding problem already few hours, i already uninstalled and installed it few times and checked i am on right python interpreter

Althrough this should go to the cs50 asking questions because it is from their course, but i am skeptical about how to explain my problem.

Asked By: Mr. Darkness

||

Answers:

If the environment MAIL_DEFAULT_SENDER does not exist then you will get a KeyError when running os.environ['MAIL_DEFAULT_SENDER']. I think that is what is happening here.

A solution for this may be to use os.environ.get(). Here is how you might do this

app.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEFAULT_SENDER')

This will set app.config['MAIL_DEFAULT_SENDER'] to the value of the environment variable MAIL_DEFAULT_SENDER if it exists, otherwise it is set to None.

If you want you can specify a default value as the second parameter.

app.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEFAULT_SENDER', 'default mail sender')
Answered By: Hanan F

thanks to the advice ‘Hanan F’ i got the code working after os.environ I placed .get and ‘MAIL_DEFAULT_SENDER’ bracket changed from square-shaped to round-shaped.

app.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEFAULT_SENDER')
app.config["MAIL_PASSWORD"] = os.environ.get("MAIL_PASSWORD")
app.config["MAIL_PORT"] = 587
app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USERNAME"] = os.environ.get("MAIL_USERNAME")
mail = Mail(app)
Answered By: Mr. Darkness
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.