3

I have a problem using Python Flask and Flask-Mail libraries.

I'm getting a error:

KeyError: 'mail'

Can someone help me resolve this?

My code is:

# -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.mail import Message
from flask.ext.mail import Mail
from ws import app


class Email():  

def __init__(self):
    ""
#
# Enviar el email
#
def enviar_mail(self,subject, sender, recipients, text_body="hola mundo txt", html_body="hola mundo html"):
    app = Flask(__name__)

    app.config.update(dict(
        MAIL_SERVER = 'smtp.gmail.com',
        MAIL_PORT = 465,
        MAIL_USE_TLS = False,
        MAIL_USE_SSL = True,
        MAIL_USERNAME = 'miaccount@gmail.com',
        MAIL_PASSWORD = 'mypasswd$%'
    ))

    mail = Mail(app)
    mail.init_app(app)
    msg = Message("Hello", sender="miaccount@gmail.com",recipients=["myrecipient@hotmail.com"])
    msg.body = "testing"
    msg.html = "<b>testing</b>"
    mail.send(msg)

And the error is

KeyError
KeyError: 'mail'
Traceback (most recent call last)
File "/home/javier/python/wszbeltia/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__

mail.send(msg)
File "/home/javier/python/wszbeltia/lib/python2.7/site-packages/flask_mail.py", line 492, in send

message.send(connection)
File "/home/javier/python/wszbeltia/lib/python2.7/site-packages/flask_mail.py", line 427, in send

connection.send(self)
File "/home/javier/python/wszbeltia/lib/python2.7/site-packages/flask_mail.py", line 190, in send

message.as_bytes() if PY3 else message.as_string(),
File "/home/javier/python/wszbeltia/lib/python2.7/site-packages/flask_mail.py", line 381, in as_string

return self._message().as_string()
File "/home/javier/python/wszbeltia/lib/python2.7/site-packages/flask_mail.py", line 307, in _message

**ascii_attachments = current_app.extensions['mail'].ascii_attachments
KeyError: 'mail'**
Celeo
  • 5,583
  • 8
  • 39
  • 41
daronwolff
  • 1,994
  • 21
  • 18

2 Answers2

13

Downgrade to flask_mail==0.9.0

This appears to be a regression in version 0.9.1.

Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120
Juan Megino
  • 146
  • 1
  • 2
  • 2
    Yes, you right I resolved doing: pip uninstall flask-mail pip install flask_mail==0.9.0 – daronwolff Jan 28 '16 at 20:00
  • 1
    @daronwolff: If this answer is what you wanted, please be sure to accept it so that other users know that the question has been satisfactorily answered. – Sylvester Kruin Oct 25 '21 at 22:38
1

I can't use flask_mail==0.9.0 with python 3.8 it gives me this error: "smtplib.server.sendmail function in python raises UnicodeEncodeError: 'ascii' codec can't encode character".

I need to use flask_mail==0.9.1. with flask_mail==0.9.1 I was getting "Email KeyError KeyError: 'mail'" error.

I resolved "Email KeyError KeyError: 'mail'" error by using "current_app" instead of "app"

from flask import current_app
mail = Mail(current_app)
# send unicode not ascii or latin 
msg.html = message.encode("utf-8")
C Halsema
  • 21
  • 3