The email confirmation feature in Flask-Security using Flask-Mail fails to send unless changes are made to the flask_security/utils.py file

Recently, I came across an issue while working with Flask-Security where the confirmation email was not being sent successfully. After some troubleshooting, I managed to resolve it by removing a specific line in flask_security/utils.py. The problematic line was 387, which I deleted to ensure that flask-mail uses the mail sender from app.config.

386: msg = Message(subject,
387:               sender=_security.email_sender,
388:               recipients=[recipient])

Prior to making this modification, the code would encounter a failure in flask_mail.py at line 105 within the sanitize_address method. This was due to the incoming address being just a single string instead of a tuple.

102: def sanitize_address(addr, encoding='utf-8'):
103:     if isinstance(addr, string_types):
104:         addr = parseaddr(force_text(addr))
105:     nm, addr = addr

I am seeking advice on how to avoid having to adjust flask_security/utils.py every time I install. It seems like there may be a configuration step missing, although I couldn't pinpoint it from the limited documentation provided by flask-security.

Thank you for your assistance. Here is an example of my application:

Sample application code goes here...

Answer №1

I recently stumbled upon this issue as well. Upon examining the source code, I was able to identify the root cause. Disclaimer: I am new to Python programming, so there may be mistakes in my analysis.

Within your code,

app.config['MAIL_DEFAULT_SENDER'] = app.config['MAIL_USERNAME']
. Let's dive into the Flask-Security source code to understand how this configuration is utilized.

Looking at flask-security/core.py :

41: _default_config = {
...
87:     'EMAIL_SENDER': LocalProxy(lambda: current_app.config.get(
88:         'MAIL_DEFAULT_SENDER', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b050446190e1b07122b0704080a070304181f45080406">[email protected]</a>'
89:     )),

If the SECURITY_EMAIL_SENDER configuration is not set, flask-security uses a proxy of

lambda: current_app.config.get('MAIL_DEFAULT_SENDER', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="214f4e0c5344514d58614d4e42404d">[email protected]</a>')
to assign a value to SECURITY_EMAIL_SENDER. Note that SECURITY_EMAIL_SENDER currently points to a LocalProxy instance.

386: msg = Message(subject,
387:               sender=_security.email_sender,
388:               recipients=[recipient])

_security.email_sender also refers to a LocalProxy instance.

102: def sanitize_address(addr, encoding='utf-8'):
103:     if isinstance(addr, string_types):
104:         addr = parseaddr(force_text(addr))
105:     nm, addr = addr

In the above snippet, addr is treated as a LocalProxy instance. Therefore, isinstance(addr, string_types) evaluates to False, leading to issues with nm, addr = addr.

To prevent such errors when utilizing flask-security, make sure to configure the SECURITY_EMAIL_SENDER setting accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error Type: The operation `in <string>` needs a string value on the left side, not a dictionary keys

My goal is to categorize data based on a specific keyword found in a column. Here's what I have attempted: if city_dict.keys() in a.lower(): return city_dict[a.lower()] elif "cheshire" in a.lower(): ... Error Message: A TypeError Excepti ...

Unable to fetch any links through the driver.find_elements method using the href attribute

As a newcomer to Python and Selenium WebDriver, my goal is to verify all links on my webpage by checking their HTTP status codes to identify any broken links. The snippet of code I am currently using looks like this... from selenium import webdriver from ...

Pause and anticipate the setting of an object property in Squish

In my current testing environment with Squish 6.3 Qt, I have encountered an application that includes a QLabel element with constantly changing content. Is there a way to pause execution until the label displays a specific value? The usual method of usin ...

Encountering a problem while trying to deploy a Django application on Heroku

I'm encountering an error while attempting to deploy my app to Heroku. The error message I receive is as follows: Counting objects: 1907, done. Delta compression using up to 4 threads. Compressing objects: 100% (1894/1894), done. Writing objects: 100 ...

What effect does increasing the height of a floatLayout have on where subsequent blocks are positioned on the screen?

I've encountered an issue with my Kivy code where the Float Layout is adding its children from the bottom up instead of top down. I'm trying to figure out how to make it go back to adding items from top down. from kivy.app import App from kivy.l ...

Another instance of UnicodeDecodeError arises when using the format() method, yet this issue does not occur when employing

Dealing with a UnicodeDecodeError issue when trying to print text fields in a class chunk called Chunk. Interestingly, concatenating the text and title fields returns no error compared to using string formatting: class Chunk: # init, fields, ... # th ...

Implementing a function that triggers another function to generate a tuple

Trying to find a way for my results function to call the retrieve_pub_vote_summary function and generate a tuple. The goal is for the results function to then output this tuple. @application.route('/results/') def results: publication = "nyt ...

Are there some arguments that are not being converted in the string formatting process?

Here is some code I have written: print(*(i for index, i in enumerate(list(input(int()).split())) if i % 6 == 0 and (index+1) % 6 == 0), sep=' '`) Although my code looks fine, I am encountering the following error: TypeError: not all argumen ...

What is the reason that a combination of two types in a list does not result in a list of combinations of these two types?

I encountered some difficulties with using mypy in scenarios where List and Union types are combined. Although I have found the solution, I wanted to share my discoveries here. The core question that arose was: why does a list of a union of two types not ...

Selenium paired with the innovative Brave browser, a Chromium-based platform with the latest Version 1.33.106 Chromium: 96.0.4664.110 (Official Build) (64-bit)

I have just started learning Python and am currently working on a browser automation project using Selenium. Currently, I am using Brave version 96.0.4664.45 but facing issues with my Chrome driver not functioning properly. On the other hand, geckodriver i ...

Can Selenium Be Used Without the Need to Install the Chrome App?

Is it possible to utilize Selenium without having to download the entire Google Chrome application? This question crossed my mind when I noticed that Selenium runs smoothly on replit, but encounters errors when run on VS Code on my computer (which lacks Go ...

Deleting a tag from a Flask document

Styling my form has been a challenge with Flask, particularly in regards to the picture field. I'm struggling to remove the "No file chosen" text and style the upload button using CSS, despite incorporating Bootstrap into my file. When hovering over ...

Retrieving JSON data embedded within a webpage's source code

Lately, I've been delving into various web scraping techniques and solutions. My current project involves extracting specific elements from JSON code embedded within a webpage (). My main goal is to extract details from the comments section, with a ...

Discovering the ultimate progenitor

My goal is to identify the ultimate parent using Dir pandas, but I am facing a unique challenge where the graph structure may not align perfectly with my requirements. Here is the input data: Child Parent Class 1001 8888 A 1001 1002 D 1001 1002 ...

I'm wondering how I can pass an argument in the command line interface and then use it in my Python code. For example, if I were to write "pytest --headless"

How can I modify conftest.py to enable headless mode when running test.py with the command pytest --headless in the terminal? By default, it should run in regular mode (show browser). conftest.py: def pytest_addoption(parser): parser.addoption("- ...

Steps for converting a number from any number system to the decimal system by rewriting a function from C++ to Python

I am facing an issue where I have a function in C++ that converts a number from any number system to decimal. However, I now require a similar function in Python and I am unsure how to rewrite it to function properly in Python without using built-in functi ...

The ZabbixAPI class instance in Python cannot be pickled

I encountered an issue while trying to pickle a ZabbixAPI object of the pyzabbix library using the code snippet below: from pyzabbix import ZabbixAPI from pickle import dumps api = ZabbixAPI('http://platform.autuitive.com/monitoring/') print d ...

Typing in a tkinter entry box effortlessly without the need to first click on it

Every time I launch my tkinter program, I find myself having to click on the entry box before I can start typing. Is there a way to configure it so that I can type without the need to click on the entry box? Thanks in advance. ...

Seeking advice on iterating through Pandas dataframe for developing a stock market algorithm

When it comes to analyzing a trading algo on historical stock market data using Python and pandas, I encountered a problem with looping over large datasets. It's just not efficient when dealing with millions of rows. To address this issue, I started ...

Combining Graphical User Interface with Scripting

I am facing a challenge while trying to integrate two separate scripts, one with a GUI and the other being a bot script. Individually, both scripts run as expected but when combined, the bot function gets called immediately without displaying the user in ...