《Flask Web开发》第六章 电子邮件,代码按照书上敲的,邮箱用的是163邮箱
hello.py代码如下:
import os
from flask import Flask, render_template, session, redirect, url_for, flash
from flask_script import Shell, Manager
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_mail import Mail
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'zhao xiufeng'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['MAIL_SERVER'] = 'stmp.163.com'
app.config['MAIL_PORT'] = '465'
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'AAA@163.com'
app.config['MAIL_PASSWORD'] = 'XXX'
mail = Mail(app)
manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
db = SQLAlchemy(app)
migrate = Migrate(app,db)
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role', lazy='dynamic')
def __repr__(self):
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'Users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __repr__(self):
return '<User %r>' % self.username
class NameForm(Form):
name = StringField('What is your name?', validators=[Required()])
submit = SubmitField('Submit')
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@app.route('/', methods=['GET','POST'])
def index():
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username = form.name.data)
db.session.add(user)
session['known'] = False
else:
session['known'] = True
session['name'] = form.name.data
form.name.data = ''
return redirect(url_for('index'))
return render_template('index.html', form = form,
name = session.get('name'), known = session.get('known', False))
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'),404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'),500
if __name__ == '__main__':
manager.run()
在python shell会话内容:
>>> from flask_mail import Message
>>> from hello import mail
>>> msg = Message('test subject', sender='AAA@163.com', recipients=['BBB@163.com'])
>>> msg.body = 'text body'
>>> msg.html = '<b>HTML</b> body'
>>> with app.app_context():
... mail.send(msg)
...
报错如下:
Traceback (most recent call last):
File "<console>", line 2, in <module>
File "/usr/local/lib/python2.7/dist-packages/flask_mail.py", line 491, in send
with self.connect() as connection:
File "/usr/local/lib/python2.7/dist-packages/flask_mail.py", line 144, in __enter__
self.host = self.configure_host()
File "/usr/local/lib/python2.7/dist-packages/flask_mail.py", line 156, in configure_host
host = smtplib.SMTP_SSL(self.mail.server, self.mail.port)
File "/usr/lib/python2.7/smtplib.py", line 788, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 793, in _get_socket
new_socket = socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
error: [Errno 111] Connection refused
不知道这是神马错误?
谢谢所有点进来的大神!!!
問題が発見されました
app.config['MAIL_SERVER'] = 'stmp.163.com'
写错了,正确的是app.config['MAIL_SERVER'] = 'smtp.163.com'