Rikuo2000
@Rikuo2000 (Rikuo Tsuchida)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

内部サーバエラーでメール送信できない

解決したいこと

Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

このような文面が実行するとでます

ターミナル画面

[2023-01-06 19:30:51,183] ERROR in app: Exception on /contact/complete [POST]
Traceback (most recent call last):
  File "C:\Users\tsuch\venv\Lib\site-packages\flask_mail.py", line 492, in send
    message.send(connection)
  File "C:\Users\tsuch\venv\Lib\site-packages\flask_mail.py", line 427, in send
    connection.send(self)
  File "C:\Users\tsuch\venv\Lib\site-packages\flask_mail.py", line 177, in send
    assert message.sender, (
AssertionError: The message does not specify a sender and a default sender has not been configured

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\tsuch\venv\Lib\site-packages\flask\app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\tsuch\venv\Lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\tsuch\venv\Lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\tsuch\venv\Lib\site-packages\flask\app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\tsuch\flaskbook\apps\minimalapp\app.py", line 109, in contact_complete
    send_email(
  File "C:\Users\tsuch\flaskbook\apps\minimalapp\app.py", line 129, in send_email
    mail.send(msg)
  File "C:\Users\tsuch\venv\Lib\site-packages\flask_mail.py", line 491, in send
    with self.connect() as connection:
  File "C:\Users\tsuch\venv\Lib\site-packages\flask_mail.py", line 152, in __exit__
    self.host.quit()
  File "C:\Users\tsuch\AppData\Local\Programs\Python\Python311\Lib\smtplib.py", line 1004, in quit
    res = self.docmd("quit")
          ^^^^^^^^^^^^^^^^^^
  File "C:\Users\tsuch\AppData\Local\Programs\Python\Python311\Lib\smtplib.py", line 431, in docmd
    self.putcmd(cmd, args)
  File "C:\Users\tsuch\AppData\Local\Programs\Python\Python311\Lib\smtplib.py", line 378, in putcmd
    self.send(f'{s}{CRLF}')
  File "C:\Users\tsuch\AppData\Local\Programs\Python\Python311\Lib\smtplib.py", line 365, in send
    raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first
127.0.0.1 - - [06/Jan/2023 19:30:51] "POST /contact/complete HTTP/1.1" 500 -

pyhon Flask でwebアプリでフォームの確認メールを送ろうとしているのですがこのようなエラーが出たのでどうやったら解決するか教えてください。
初心者につき低レベルな質問なことをお許しください

該当するソースコード

# loggingをインポート
import logging
import os

from email_validator import EmailNotValidError, validate_email

# Flaskクラスをインポート
from flask import (
    Flask,
    current_app,
    flash,
    g,
    redirect,
    render_template,
    request,
    url_for,
)
from flask_debugtoolbar import DebugToolbarExtension
from flask_mail import Mail, Message

# Flaskクラスをインスタンス化
app = Flask(__name__)
# secret_keyの追加
app.config["SECRET_KEY"] = "2AZSMss3p5QPbcY2hBsJ"
# ログレベルの設定
app.logger.setLevel(logging.DEBUG)

app.logger.debug("DEBUG")
app.logger.info("INFO")
app.logger.warning("WARNING")
app.logger.error("ERROR")
app.logger.critical("CRITICAL")


app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False
toolbor = DebugToolbarExtension(app)

# URLと実行する関数をマッピング
@app.route("/")
def index():
    return "Hello,Flaskbook!"


@app.route("/hello/<name>", methods=["GET", "POST"], endpoint="hello-endpoint")
def hello(name):
    return f"Hello, {name}!"


@app.route("/name/<name>")
def show_name(name):
    return render_template("index.html", name=name)


with app.test_request_context():
    # /
    print(url_for("index"))
    # /hello/world
    print(url_for("hello-endpoint", name="world"))
    # /name/Rikuo?page=1
    print(url_for("show_name", name="Rikuo", page="1"))

ctx = app.app_context()
ctx.push()

print(current_app.name)

g.connection = "connection"
print(g.connection)

with app.test_request_context("/users?update=ture"):
    print(request.args.get("updated"))


@app.route("/contact")
def contact():
    return render_template("contact.html")


@app.route("/contact/complete", methods=["GET", "POST"])
def contact_complete():
    if request.method == "POST":
        username = request.form["username"]
        email = request.form["email"]
        description = request.form["description"]
        is_valid = True

        if not username:
            flash("ユーザ名は必須です")
            is_valid = False

        if not email:
            flash("メールアドレスは必須です")
            is_valid = False

        try:
            validate_email(email)
        except EmailNotValidError:
            flash("メールアドレスの形式で入力してください")
            is_valid = False

        if not description:
            flash("問い合わせ内容は必須です")
            is_valid = False

        if not is_valid:
            return redirect(url_for("contact"))

        # メールを送る
        send_email(
            email,
            "お問い合わせありがとうございました。",
            "contact_mail",
            username=username,
            description=description,
        )

        flash("問い合わせ内容はメールにて送信しました。問い合わせありがとうございます。")

        return redirect(url_for("contact_complete"))

    return render_template("contact_complete.html")


def send_email(to, subject, template, **kwargs):
    """メールを送信する関数"""
    msg = Message(subject, recipients=[to])
    msg.body = render_template(template + ".txt", **kwargs)
    msg.html = render_template(template + ".html", **kwargs)
    mail.send(msg)


# Mailクラスのコンフィグを追加
app.config["MAIL_SERVER"] = os.environ.get("MAIL_SERVER")
app.config["MAIL_PORT"] = os.environ.get("MAIL_PORT")
app.config["MAIL_USE_TLS"] = os.environ.get("MAIL_USE_TLS")
app.config["MAIL_USERNAME"] = os.environ.get("MAIL_USERNAME")
app.config["MAIL_PASSWORD"] = os.environ.get("MAIL_PASSWORD")
app.config["MAIL_DEFAULT_SENDER"] = os.environ.get("MAIL_DEFAULT_SENDER")

mail = Mail(app)

自分で試したこと

さっぱりなので何も試せていません

0

2Answer

  • 画像の文字が読めないのでテキストで載せてみませんか?
  • エラーログはどうなってますか?
1Like

Comments

  1. @Rikuo2000

    Questioner

    Internal Server Error
    The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
  2. @Rikuo2000

    Questioner

    画面ではこうなってます
  3. @Rikuo2000

    Questioner

    [2023-01-06 17:20:34,551] ERROR in app: Exception on /contact/complete [POST]
    Traceback (most recent call last):
    File "C:\Users\tsuch\venv\Lib\site-packages\flask_mail.py", line 492, in send
    message.send(connection)
    File "C:\Users\tsuch\venv\Lib\site-packages\flask_mail.py", line 427, in send
    connection.send(self)
    File "C:\Users\tsuch\venv\Lib\site-packages\flask_mail.py", line 177, in send
    assert message.sender, (
    AssertionError: The message does not specify a sender and a default sender has not been configured

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
    File "C:\Users\tsuch\venv\Lib\site-packages\flask\app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\tsuch\venv\Lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\tsuch\venv\Lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
    ^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\tsuch\venv\Lib\site-packages\flask\app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tsuch\flaskbook\apps\minimalapp\app.py", line 109, in contact_complete
    send_email(
    File "C:\Users\tsuch\flaskbook\apps\minimalapp\app.py", line 129, in send_email
    mail.send(msg)
    File "C:\Users\tsuch\venv\Lib\site-packages\flask_mail.py", line 491, in send
    with self.connect() as connection:
    File "C:\Users\tsuch\venv\Lib\site-packages\flask_mail.py", line 152, in __exit__
    self.host.quit()
    File "C:\Users\tsuch\AppData\Local\Programs\Python\Python311\Lib\smtplib.py", line 1004, in quit
    res = self.docmd("quit")
    ^^^^^^^^^^^^^^^^^^
    File "C:\Users\tsuch\AppData\Local\Programs\Python\Python311\Lib\smtplib.py", line 431, in docmd
    self.putcmd(cmd, args)
    File "C:\Users\tsuch\AppData\Local\Programs\Python\Python311\Lib\smtplib.py", line 378, in putcmd
    self.send(f'{s}{CRLF}')
    File "C:\Users\tsuch\AppData\Local\Programs\Python\Python311\Lib\smtplib.py", line 365, in send
    raise SMTPServerDisconnected('please run connect() first')
    smtplib.SMTPServerDisconnected: please run connect() first
    127.0.0.1 - - [06/Jan/2023 17:20:34] "POST /contact/complete HTTP/1.1" 500 -
yum  install -y telnet
telnet  サーバip  ポート番号
EHLO サーバ名
AUTH LOGIN
QUIT

でクライアント環境がFWを含め接続可能な環境であるか確認してはどうでしょう?

1Like

Comments

  1. @Rikuo2000

    Questioner

    ありがとうございます
    サーバip等がわからないです
    すいません
  2. nslookup -q=mx ドメイン
    nslookup -q=A メールサーバ名
    で調べることができます。digでもok

Your answer might help someone💌