LoginSignup
2
1

More than 1 year has passed since last update.

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

Posted at

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=['masashi.kanno@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

2
1
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
2
1