3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flask】 flask-mailでメールを送信する

Last updated at Posted at 2022-09-28

flask-mailでGmailを使ったメールの送信方法を確認する

Code

send_mail.py
from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587                             # TLSは587、SSLなら465
app.config['MAIL_USERNAME'] = 'your_id@gmail.com'
app.config['MAIL_PASSWORD'] = 'Gmail app password'        # GmailのApp用のmパスワード設定をしておく必要あり
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
app.config['MAIL_DEFAULT_SENDER'] = 'your_id@gmail.com'    # これがあるとsender設定が不要になる
mail = Mail(app)


@app.route('/')
def index():
    return """
    <p><a href="/send_mail">Send Mail</a></p>
    """


@app.route("/send_mail")
def send_mail():
    msg = Message('Test Mail', recipients=['xxx@gmail.com'])
    msg.body = "Hello Flask message sent from Flask-Mail"
    mail.send(msg)
    return "Sent"


if __name__ == ('__main__'):
    app.run(host='0.0.0.0', port=5050, debug=True)

送信前

index.png

送信後

send_mail.png

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?