3

I'm following flask tutorial to practice to do flask-mail but I encounter something that appears to be a bug. I don't understand what happen?

This is my code:

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)

This is info of bug:

Traceback (most recent call last):
  File "ch6_1.py", line 64, in <module>
    send_email(app ,MAIL_USERNAME, "test mail", "hello")
  File "ch6_1.py", line 50, in send_email
    msg.body = render_template(template + '.txt', **kwargs)
  File "D:\INSTALL\Python\lib\site-packages\flask\templating.py", line 126, in r
ender_template
    ctx.app.update_template_context(context)
AttributeError: 'NoneType' object has no attribute 'app'
J Richard Snape
  • 20,116
  • 5
  • 51
  • 79
Burger King
  • 2,945
  • 3
  • 20
  • 45
  • Whilst I can see that the underlying cause is the same - it's not immediately obvious that this is a dup (given the error message is quite different). Maybe - that should be edited into the answer... – J Richard Snape Jul 01 '15 at 15:20

1 Answers1

6

When I invoke with app.app_context():, I have solved my problem.

def send_email(to, subject, template, **kwargs):
    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
                  sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
    with app.app_context():
        msg.body = render_template(template + '.txt', **kwargs)
        msg.html = render_template(template + '.html', **kwargs)
        mail.send(msg)
Burger King
  • 2,945
  • 3
  • 20
  • 45