Skip to content

Commit 5ffcce9

Browse files
authored
Merge pull request #27 from mxtoai/rate-limit
Add Rate Limiting, Update docs with why to use section
2 parents 9ba3d39 + 59ed4cf commit 5ffcce9

File tree

9 files changed

+7207
-447
lines changed

9 files changed

+7207
-447
lines changed
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
# MXtoAI Use Cases
2+
3+
**The Magic: Zero Setup Required**
4+
5+
- No new apps to learn - works with your existing email
6+
- No account creation - just whitelist your email and start forwarding
7+
- No data stored - your emails are processed and immediately deleted
8+
- Works anywhere - Gmail, Outlook, Apple Mail, even your phone
9+
- Works with attachments - PDFs, images, spreadsheets all processed
10+
- Works with email threads - understands context from conversation history
11+
12+
As simple as it sounds, MXtoAI is very powerful. If you spend more than 10 minutes a day reading, understanding, or responding to emails, MXtoAI can probably save you time and mental energy. Whether you're dealing with work emails, personal correspondence, or staying informed, there's likely a use case that fits your daily routine. Here are some use-cases you can use it for.
13+
14+
## 📧 Daily Email Management
15+
16+
**"I get too many newsletters and updates"**
17+
- Forward newsletters to summarize@mxtoai.com - get key points in 2-3 sentences
18+
- Set up auto-forwarding rules so all newsletters get auto-summarized daily
19+
20+
**"I receive emails in different languages"**
21+
- Forward to translate@mxtoai.com - instantly get English translations
22+
- Perfect for international business or foreign language newsletters
23+
24+
**"Complex emails confuse me"**
25+
- Forward technical/legal emails to simplify@mxtoai.com - get plain English explanations
26+
- Great for insurance documents, contracts, or technical announcements
27+
28+
**"I'm drowning in promotional emails"**
29+
- Forward deals/offers to ask@mxtoai.com with "Is this actually a good deal?"
30+
- Get honest comparisons and price checks
31+
32+
## 🤝 Meeting & Scheduling
33+
34+
**"Coordinating meetings is a nightmare"**
35+
- Forward scheduling emails to schedule@mxtoai.com
36+
- Get back .ics calendar files with suggested meeting times
37+
- Works with "Can we meet next week?" or complex group scheduling
38+
39+
**"I need to prepare for meetings with new people"**
40+
- Forward meeting invites to background@mxtoai.com
41+
- Get LinkedIn profiles, company info, recent news about attendees
42+
43+
**"I forgot what we discussed in previous emails"**
44+
- Forward email threads to summarize@mxtoai.com
45+
- Get context and key points before the meeting
46+
47+
**"I need to follow up after meetings"**
48+
- Forward meeting notes to ask@mxtoai.com with "Draft follow-up email"
49+
- Get professional action items and next steps
50+
51+
## 💼 Business & Work
52+
53+
**"I get invoices and need to check calculations"**
54+
- Forward invoices to ask@mxtoai.com with "Check if this math is correct"
55+
- Catches billing errors automatically
56+
57+
**"I need to research companies/people quickly"**
58+
- Forward emails mentioning companies to background@mxtoai.com
59+
- Get company size, recent news, key executives, competitors
60+
61+
**"I receive reports and need quick insights"**
62+
- Forward quarterly reports to summarize@mxtoai.com
63+
- Get key metrics and trends without reading 20 pages
64+
65+
**"I receive contracts and legal documents"**
66+
- Forward to simplify@mxtoai.com - understand key terms and obligations
67+
- Forward to ask@mxtoai.com with "What are the risks here?"
68+
69+
**"I get RFPs and proposals to review"**
70+
- Forward to summarize@mxtoai.com - get key requirements and deadlines
71+
- Forward to ask@mxtoai.com with "What's our competitive advantage here?"
72+
73+
## 🔍 Information Verification & Research
74+
75+
**"I get forwarded news and want to check if it's true"**
76+
- Forward suspicious emails to factcheck@mxtoai.com
77+
- Get verification with sources - perfect for avoiding misinformation
78+
79+
**"I need to verify claims in marketing emails"**
80+
- Forward promotional content to factcheck@mxtoai.com
81+
- Check if "50% off" is really a discount or if testimonials are real
82+
83+
**"I want to research investments or financial advice"**
84+
- Forward investment newsletters to research@mxtoai.com
85+
- Get company fundamentals, recent performance, analyst opinions
86+
87+
**"I need to check competitor information"**
88+
- Forward competitor emails to background@mxtoai.com
89+
- Get market position, recent moves, customer feedback
90+
91+
## 🏠 Personal Life
92+
93+
**"I get complex medical/insurance emails"**
94+
- Forward to simplify@mxtoai.com - understand your benefits, procedures, costs
95+
- No more confusion about medical bills or insurance claims
96+
97+
**"I get travel confirmations and want to know more about destinations"**
98+
- Forward booking confirmations to background@mxtoai.com
99+
- Get weather, local attractions, cultural tips
100+
101+
**"I receive home service estimates"**
102+
- Forward contractor quotes to ask@mxtoai.com with "Is this price fair?"
103+
- Get market rates and red flags to watch for
104+
105+
**"I get tax documents and financial statements"**
106+
- Forward to simplify@mxtoai.com - understand what you owe/are owed
107+
- Forward to ask@mxtoai.com with "What deductions am I missing?"
108+
109+
**"I receive HOA notices and community updates"**
110+
- Forward lengthy community emails to summarize@mxtoai.com
111+
- Get key dates, rule changes, and action items
112+
113+
## 🎓 Education & Learning
114+
115+
**"I want to stay informed but don't have time to read everything"**
116+
- Forward industry newsletters to summarize@mxtoai.com
117+
- Set up daily digest of key news in your field
118+
119+
**"I receive academic papers or technical articles"**
120+
- Forward to simplify@mxtoai.com - get key findings in simple terms
121+
- Perfect for staying current without deep technical reading
122+
123+
**"I get course announcements and need to prioritize"**
124+
- Forward educational emails to ask@mxtoai.com with "Which courses are worth my time?"
125+
- Get recommendations based on your goals
126+
127+
**"I receive research papers and need quick insights"**
128+
- Forward to ask@mxtoai.com with "What are the practical applications?"
129+
- Understand real-world relevance quickly
130+
131+
## 🛍️ Shopping & Consumer Decisions
132+
133+
**"I get overwhelmed by product comparison emails"**
134+
- Forward to simplify@mxtoai.com - get clear feature comparisons
135+
- Perfect for software, cars, appliances
136+
137+
**"I receive warranty and service emails"**
138+
- Forward to ask@mxtoai.com with "What does this actually cover?"
139+
- Understand terms without legal jargon
140+
141+
**"I get subscription renewal notices"**
142+
- Forward to ask@mxtoai.com with "Is this still worth it?"
143+
- Get usage analysis and alternatives
144+
145+
**"I receive recall notices and safety alerts"**
146+
- Forward to ask@mxtoai.com with "How urgent is this?"
147+
- Understand if immediate action is needed
148+
149+
## 💰 Financial Management
150+
151+
**"I get bank statements and credit card bills"**
152+
- Forward to ask@mxtoai.com with "Any unusual charges or patterns?"
153+
- Spot fraud and track spending trends
154+
155+
**"I receive investment updates and market reports"**
156+
- Forward to simplify@mxtoai.com - understand impact on your portfolio
157+
- Get action recommendations in plain English
158+
159+
**"I get loan offers and financial product emails"**
160+
- Forward to ask@mxtoai.com with "Is this a good deal for my situation?"
161+
- Get personalized pros/cons analysis
162+
163+
**"I receive tax-related emails from accountants"**
164+
- Forward to simplify@mxtoai.com - understand deadlines and requirements
165+
- No more confusion about filing obligations
166+
167+
## 🏥 Healthcare & Wellness
168+
169+
**"I get lab results and medical reports"**
170+
- Forward to simplify@mxtoai.com - understand what results mean
171+
- Get context on normal ranges and next steps
172+
173+
**"I receive appointment confirmations with prep instructions"**
174+
- Forward to summarize@mxtoai.com - get clear to-do lists
175+
- Never miss pre-appointment requirements
176+
177+
**"I get emails about new treatments or procedures"**
178+
- Forward to ask@mxtoai.com with "What are the risks and benefits?"
179+
- Make informed healthcare decisions
180+
181+
**"I receive wellness newsletters with conflicting advice"**
182+
- Forward to factcheck@mxtoai.com - verify health claims
183+
- Separate science from marketing
184+
185+
## 🎯 Real-World Examples by Profession
186+
187+
**Small Business Owner:**
188+
- "I forward customer complaints to ask@mxtoai.com with 'Draft empathetic response' - turns angry customers into loyal ones"
189+
- "I forward supplier emails to background@mxtoai.com before negotiations - know their financial health"
190+
191+
**Job Seeker:**
192+
- "I forward job postings to background@mxtoai.com to research company culture before applying"
193+
- "I forward interview invites to ask@mxtoai.com with 'Help me research this role' for better preparation"
194+
195+
**Investor:**
196+
- "I forward earnings emails to summarize@mxtoai.com for quick portfolio updates"
197+
- "I forward analyst reports to ask@mxtoai.com with 'What's the contrarian view?' for balanced perspective"
198+
199+
**Consultant:**
200+
- "I forward client emails to background@mxtoai.com before meetings to understand industry challenges"
201+
- "I forward RFPs to ask@mxtoai.com with 'What's the hidden agenda here?' to win more bids"
202+
203+
**Retiree:**
204+
- "I forward Medicare emails to simplify@mxtoai.com - healthcare is confusing enough"
205+
- "I forward financial advisor emails to ask@mxtoai.com with 'Is this advice suitable for my age?'"
206+
207+
**Student:**
208+
- "I forward professor emails to summarize@mxtoai.com to catch important deadlines"
209+
- "I forward scholarship announcements to ask@mxtoai.com with 'Am I eligible for this?'"
210+
211+
**Freelancer:**
212+
- "I forward client project briefs to ask@mxtoai.com with 'What questions should I ask?'"
213+
- "I forward contract negotiations to ask@mxtoai.com with 'What am I missing in this deal?'"
214+
215+
**Real Estate Agent:**
216+
- "I forward property listings to background@mxtoai.com for neighborhood insights"
217+
- "I forward mortgage documents to simplify@mxtoai.com to explain terms to clients"
218+
219+
**Healthcare Worker:**
220+
- "I forward policy updates to summarize@mxtoai.com - regulations change constantly"
221+
- "I forward research emails to ask@mxtoai.com with 'How does this apply to my patients?'"

mxtoai/api.py

Lines changed: 65 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
import json
22
import os
33
import shutil
4+
from contextlib import asynccontextmanager
45
from datetime import datetime
56
from email.utils import getaddresses
67
from pathlib import Path
78
from typing import Annotated, Any, Optional
89

910
import aiofiles
11+
import redis.asyncio as aioredis
1012
from dotenv import load_dotenv
1113
from fastapi import Depends, FastAPI, File, Form, HTTPException, Response, UploadFile, status
1214
from fastapi.security import APIKeyHeader
@@ -19,18 +21,73 @@
1921
generate_email_id,
2022
send_email_reply,
2123
)
22-
from mxtoai.schemas import EmailAttachment, EmailRequest
24+
from mxtoai.schemas import EmailAttachment, EmailRequest, RateLimitPlan
2325
from mxtoai.tasks import process_email_task
24-
from mxtoai.validators import validate_api_key, validate_attachments, validate_email_handle, validate_email_whitelist
26+
from mxtoai.validators import (
27+
email_provider_domain_set as validator_email_provider_domain_set,
28+
)
29+
from mxtoai.validators import (
30+
validate_api_key,
31+
validate_attachments,
32+
validate_email_handle,
33+
validate_email_whitelist,
34+
validate_rate_limits,
35+
)
36+
from mxtoai import validators
2537

2638
# Load environment variables
2739
load_dotenv()
40+
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
2841

2942
# Configure logging
3043
logger = get_logger(__name__)
3144

32-
app = FastAPI()
33-
if os.getenv("IS_PROD", "true").lower() == "true":
45+
46+
# Lifespan manager for app startup and shutdown
47+
@asynccontextmanager
48+
async def lifespan(app: FastAPI):
49+
# Startup
50+
logger.info("Application startup: Initializing Redis client for rate limiter...")
51+
try:
52+
validators.redis_client = aioredis.from_url(REDIS_URL, encoding="utf-8", decode_responses=True)
53+
await validators.redis_client.ping()
54+
logger.info(f"Redis client connected for rate limiting: {REDIS_URL}")
55+
except Exception as e:
56+
logger.error(f"Could not connect to Redis for rate limiting at {REDIS_URL}: {e}")
57+
validators.redis_client = None
58+
59+
# Load email provider domains
60+
global validator_email_provider_domain_set
61+
try:
62+
current_dir = Path(__file__).parent
63+
domains_file_path = current_dir / "email_provider_domains.txt"
64+
if not domains_file_path.exists():
65+
domains_file_path = Path("mxtoai/email_provider_domains.txt")
66+
67+
if domains_file_path.exists():
68+
with open(domains_file_path) as f:
69+
validator_email_provider_domain_set.update([line.strip().lower() for line in f if line.strip()])
70+
logger.info(
71+
f"Loaded {len(validator_email_provider_domain_set)} email provider domains for rate limit exclusion."
72+
)
73+
else:
74+
logger.warning(
75+
f"Email provider domains file not found at {domains_file_path}. Domain-specific rate limits might not work as expected."
76+
)
77+
except Exception as e:
78+
logger.error(f"Error loading email provider domains: {e}")
79+
80+
yield # Application runs here
81+
82+
# Shutdown
83+
logger.info("Application shutdown: Closing Redis client...")
84+
if validators.redis_client:
85+
await validators.redis_client.aclose()
86+
logger.info("Redis client closed.")
87+
88+
89+
app = FastAPI(lifespan=lifespan)
90+
if os.environ["IS_PROD"].lower() == "true":
3491
app.openapi_url = None
3592

3693
api_auth_scheme = APIKeyHeader(name="x-api-key", auto_error=True)
@@ -414,6 +471,10 @@ async def process_email(
414471
if response := await validate_api_key(api_key):
415472
return response
416473

474+
# Validate rate limits before other processing
475+
if response := await validate_rate_limits(from_email, to, subject, messageId, plan=RateLimitPlan.BETA):
476+
return response
477+
417478
if files is None:
418479
files = []
419480
parsed_headers = {}

0 commit comments

Comments
 (0)