diff --git a/app/__init__.py b/app/__init__.py index 6e84235..79b1dcb 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,6 @@ from flask import Flask, request, jsonify from .config import Config -from .utils import get_latest_emails +from .utils import get_latest_emails, get_latest_email_with_code def create_app(): app = Flask(__name__) @@ -15,4 +15,14 @@ def create_app(): emails = get_latest_emails(recipient, limit) return jsonify(emails) + @app.route('/latest_email', methods=['GET']) + def get_latest_email(): + recipient = request.args.get('recipient') + if not recipient: + return jsonify({'error': 'Recipient email is required'}), 400 + email_data = get_latest_email_with_code(recipient) + if email_data: + return jsonify(email_data) + return jsonify({'error': 'No emails found for this recipient'}), 404 + return app \ No newline at end of file diff --git a/app/utils.py b/app/utils.py index a85fc4d..a5ebb88 100644 --- a/app/utils.py +++ b/app/utils.py @@ -227,4 +227,31 @@ def get_latest_emails(recipient, limit=10): return emails except Exception as e: logger.error(f'Error fetching emails: {e}') - return [] \ No newline at end of file + return [] + + +def get_latest_email_with_code(recipient): + """获取指定收件人的最新邮件并提取验证码""" + try: + recipient_key = f'recipient:{recipient}' + email_key = redis_client.lindex(recipient_key, 0) # 获取最新邮件的键 + if email_key: + email_data = redis_client.hgetall(email_key.decode()) + if email_data: + email_data = {k.decode(): v.decode() for k, v in email_data.items()} + body = email_data.get('body', '') + # 假设验证码是以某种格式存在于邮件正文中,例如 "验证码: 123456" + code = extract_code_from_body(body) + email_data['code'] = code # 将验证码添加到返回数据中 + return email_data + return None + except Exception as e: + logger.error(f'Error fetching latest email with code: {e}') + return None + + +def extract_code_from_body(body): + """从邮件正文中提取验证码""" + import re + match = re.search(r'\b(\d{6})\b', body) + return match.group(1) if match else None \ No newline at end of file