This week, I have a little spare time to continue to learn flask web, among which flask-mail is the biggest pit! I will pull everyone out of the pit step by step!
1. First, change the mailbox to 163
app.config['MAIL_SERVER'] = 'smtp.163.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
2. Setting environment variables
set [email protected]
set MAIL_PASSWORD=xxxx
Yes, I don't know where, I have been pitted for two days!
At the beginning, I set it in PyCharm's Terminal, no way! !
Later, I set it under the cmd command again, but every time I restart it doesn't work anymore, huh, huh!
Finally, in my computer - right click - properties - advanced system settings - environment variables, set MAIL_USERNAME, etc.
3. Set 163 mailboxes POP3/SMTP/IMAP, if not set, there will be the following errors:
File "D:\PycharmProjects\hello\venv\lib\site-packages\flask_mail.py", line 165, in configure_host
host.login(self.mail.username, self.mail.password)
File "E:\Python36\Lib\smtplib.py", line 730, in login
raise last_exception
File "E:\Python36\Lib\smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "E:\Python36\Lib\smtplib.py", line 642, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (550, b'User has no permission')
4. Create a new mail folder under the templates folder in the project, create a new_user.html, and the content is
User <b>{{ user.username }}</b> has joined.
5. Finally, the code of the previous part of hello.py
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]' app.config['FLASKY_MAIL_SENDER'] ='Flasky Admin <[email protected]>' app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')
def send_email(to, subject, template, **kwargs): msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX']+subject, sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) mail.send(msg)
@app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): # old_name = session.get('name') 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 # if app.config['FLASKY_ADMIN']: send_email(app.config['FLASKY_ADMIN'], 'New User', 'mail/new_user', user=user) else: session['known'] = True session['name'] = form.name.data form.name.data = '' # send_email(app.config['FLASKY_ADMIN'], 'New User') # send_email(app.config['FLASKY_ADMIN'], 'New User', 'mail/new_user', user=user) return redirect(url_for('index')) return render_template('index.html', form=form, name=session.get('name'), known=session.get('known', False)) if __name__ == '__main__': app.run(debug=True) # manager.run()
运行,发送成功!