增加二维码发送到邮箱功能,以便人不在电脑旁登陆失效可以远程扫描登录

This commit is contained in:
IronXiao
2021-09-29 19:07:43 +08:00
parent db34583c7d
commit 6e5ceca134
3 changed files with 52 additions and 0 deletions

View File

@@ -33,6 +33,11 @@ class Notification():
self = cls()
self.send_email_by_smtp(to, title, content)
@classmethod
def send_email_with_qrcode(cls, to, title='', qrcode_path=''):
self = cls()
self.send_email_by_smtp_with_qrcode(to, title, qrcode_path)
@classmethod
def send_to_telegram(cls, content=''):
self = cls()
@@ -134,6 +139,46 @@ class Notification():
except Exception as e:
CommonLog.add_quick_log(CommonLog.MESSAGE_SEND_EMAIL_FAIL.format(e)).flush()
def send_email_by_smtp_with_qrcode(self, to, title, qrcode_path):
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
to = to if isinstance(to, list) else [to]
message = MIMEMultipart()
message['Subject'] = title
message['From'] = Config().EMAIL_SENDER
message['To'] = ", ".join(to)
htmlFile = """
<html>
<head></head>
<body>
<p>
这是你的二维码
</p>
<p>
<br /><img src="cid:0", width=200, height=200 ></p>
</body>
</html>
"""
htmlApart = MIMEText(htmlFile, 'html')
imageFile = qrcode_path
imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
imageApart.add_header('Content-ID', '<0>')
message.attach(imageApart)
message.attach(htmlApart)
try:
server = smtplib.SMTP(Config().EMAIL_SERVER_HOST)
server.ehlo()
server.starttls()
server.login(Config().EMAIL_SERVER_USER, Config().EMAIL_SERVER_PASSWORD)
server.send_message(message)
server.quit()
CommonLog.add_quick_log(CommonLog.MESSAGE_SEND_EMAIL_WITH_QRCODE_SUCCESS).flush()
self.push_bark(CommonLog.MESSAGE_SEND_EMAIL_WITH_QRCODE_SUCCESS)
except Exception as e:
CommonLog.add_quick_log(CommonLog.MESSAGE_SEND_EMAIL_FAIL.format(e)).flush()
def send_dingtalk_by_webbook(self, content):
from dingtalkchatbot.chatbot import DingtalkChatbot
webhook = Config().DINGTALK_WEBHOOK

View File

@@ -35,6 +35,8 @@ class CommonLog(BaseLog):
MESSAGE_SEND_EMAIL_SUCCESS = '邮件发送成功,请检查收件箱'
MESSAGE_SEND_EMAIL_FAIL = '邮件发送失败,请手动检查配置,错误原因 {}'
MESSAGE_SEND_EMAIL_WITH_QRCODE_SUCCESS = '二维码邮件发送成功,请检查收件箱扫描登陆'
MESSAGE_SEND_TELEGRAM_SUCCESS = 'Telegram推送成功'
MESSAGE_SEND_TELEGRAM_FAIL = 'Telegram推送失败错误原因 {}'

View File

@@ -215,11 +215,16 @@ class UserJob:
else:
print_qrcode(png_path)
UserLog.add_log(UserLog.MESSAGE_QRCODE_DOWNLOADED.format(png_path)).flush()
Notification.send_email_with_qrcode(Config().EMAIL_RECEIVER, '你有新的登录二维码啦!', png_path)
return result.get('uuid'), png_path
raise KeyError('获取二维码失败: {}'.format(result.get('result_message')))
except Exception as e:
UserLog.add_quick_log(
UserLog.MESSAGE_QRCODE_FAIL.format(e, self.retry_time)).flush()
try:
os.remove(self.get_cookie_path())
except:
pass
time.sleep(self.retry_time)
return self.download_code()