I created an iot gas leakage and electrical load monitoring flask web app. The problem is it does not send an email when the gas_value >= 0.2 and current_value_float >= 0.2to the user that is currently logged in in the web app.
|--website | |--pychache | |--static | |--templates | |--auth.py | |--email.py | |--init.py | |--models.py | |--views.py | |--app.py |--power.py |--mq6_module.py
here are my modifications in my code
init.py:
from flask_mail import Mail
mail = Mail()
def create_app():
app = Flask(__name__)
app.config.update(dict(
MAIL_DEBUG = True,
MAIL_SERVER = 'smtp.gmail.com',
MAIL_PORT = 465,
MAIL_USE_TLS = True,
MAIL_USE_SSL = False,
MAIL_USERNAME = '[email protected]',
MAIL_PASSWORD = '****************',
))
mail.init_app(app)
email.py:
from flask_mail import Message
from flask_login import current_user
from . import mail
def send_email( subject, body, recipient_email):
msg = Message(subject,recipients=[recipient_email], sender= '[email protected]' )
msg.body = body
mail.send(msg)
To send message when it reaches certain threshold, I modify the views.py:
@views.route('/gas_value')
def gas_value():
gas_value = mq6_modules[0].mq.MQPercentage()["GAS_LPG"] # Assuming the first instance is used
if gas_value >= 0.2:
gas_reading = GasReading(value=gas_value)
db.session.add(gas_reading)
db.session.commit()
send_email( 'High Gas Value Alert', 'Gas value has exceeded 0.2.', current_user.email)
return jsonify({'gas_value': gas_value})
@views.route('/current_value')
def current_value():
current_value = powers[0].get_electricalsensor_readings()
if current_value is not None:
current_value_float = float(current_value) # Convert current_value to float
# Display the current value continuously
response = {'current_value': current_value}
# Store in the database if the value is greater than or equal to 0.2
if current_value_float >= 0.2:
current_reading = CurrentReading(value=current_value_float)
db.session.add(current_reading)
db.session.commit()
send_email( 'High Current Value Alert', 'Current value has exceeded 0.2.', current_user.email)
return jsonify(response)
else:
return jsonify({'current_value': 'Unavailable'})
I review email account security wherein I allowed access for less secure apps and set up app passwords for increased security but it states:
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
As I know, Google does not allow to use gmail smtp this way any more, at least I failed to resolve it (may be it will work for Google Workspace). https://support.google.com/accounts/answer/6010255?hl=en
Instead I used Yandex mail service. https://yandex.com/support/mail/mail-clients/others.html
May be there is email service where you host your app.