我创建了一个物联网气体泄漏和电力负载监控烧瓶网络应用程序。问题是,当 Gas_value >= 0.2 且 current_value_float >= 0.2 时,它不会向当前登录 Web 应用程序的用户发送电子邮件。
|--网站 | |--pychache | |--静态 | |--模板 | |--auth.py | |--email.py | |--init.py | |--models.py | |--views.py | |--app.py |--power.py |--mq6_module.py
这是我对代码的修改
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)
电子邮件.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)
要在达到特定阈值时发送消息,我修改了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'})
我检查了电子邮件帐户的安全性,其中我允许访问安全性较低的应用程序,并设置应用程序密码以提高安全性,但它指出:
引发 SMTPServerDisconnected(“连接意外关闭”)
smtplib.SMTPServerDisconnected:连接意外关闭
据我所知,Google 不允许再以这种方式使用 gmail smtp,至少我没能解决它(也许它适用于 Google Workspace)。 https://support.google.com/accounts/answer/6010255?hl=zh-CN
我使用了 Yandex 邮件服务。 https://yandex.com/support/mail/mail-clients/others.html
可能有您托管应用程序的电子邮件服务。