-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
166 lines (138 loc) · 6.16 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
from fastapi import FastAPI, Form, File, UploadFile, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from jinja2 import Template
import io
import csv
import re
import logging
import time
from datetime import datetime
# Logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(levelname)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# Initialize FastAPI
app = FastAPI()
# Serve static files from the assets directory
app.mount("/assets", StaticFiles(directory="assets"), name="assets")
# Email regex pattern for validation
email_regex = re.compile(r"[^@]+@[^@]+\.[^@]+")
# Global SMTP configuration variable
smtp_config = {}
# Rate limiting variables
email_send_interval = 1
retry_attempts = 3
# Helper function to validate email addresses
def is_valid_email(email: str) -> bool:
return re.fullmatch(email_regex, email) is not None
# Helper function to validate CSV format
def validate_csv(file_content: str) -> bool:
reader = csv.DictReader(io.StringIO(file_content))
required_columns = {"Email"}
return required_columns.issubset(reader.fieldnames)
# Route for the index page
@app.get("/", response_class=HTMLResponse)
async def index():
with open('Frontend/index.html', 'r') as f:
return HTMLResponse(content=f.read(), status_code=200)
# Route to configure SMTP settings
@app.post("/configure_smtp")
async def configure_smtp(smtpHost: str = Form(...), smtpPort: int = Form(...),
smtpUser: str = Form(...), smtpPass: str = Form(...)):
global smtp_config
smtp_config = {
'MAIL_SERVER': smtpHost,
'MAIL_PORT': smtpPort,
'MAIL_USERNAME': smtpUser,
'MAIL_PASSWORD': smtpPass,
'MAIL_STARTTLS': True,
'MAIL_SSL_TLS': False,
'USE_CREDENTIALS': True
}
logging.info(f"SMTP Config: {smtp_config}")
return JSONResponse(content={'success': True, 'message': 'SMTP configuration updated successfully!'})
# Route to preview CSV
@app.post("/preview_csv")
async def preview_csv(csvFile: UploadFile = File(...)):
if csvFile.filename == '':
raise HTTPException(status_code=400, detail="Empty CSV file uploaded")
content = await csvFile.read()
csv_data = csv.DictReader(io.StringIO(content.decode("UTF-8")))
preview_data = [row for idx, row in enumerate(csv_data) if idx < 5] # Preview first 5 rows
return JSONResponse(content={'preview': preview_data})
# Route to send emails
@app.post("/send_emails")
async def send_emails(subject: str = Form(...), senderName: str = Form(...),
htmlContent: str = Form(...), csvFile: UploadFile = File(...)):
if not smtp_config:
raise HTTPException(status_code=400, detail="SMTP configuration is missing")
if csvFile.filename == '':
raise HTTPException(status_code=400, detail="Empty CSV file uploaded")
# Read and validate the uploaded CSV file
content = await csvFile.read()
if not validate_csv(content.decode("UTF-8")):
raise HTTPException(status_code=400, detail="CSV validation failed: Missing required columns")
# Send emails immediately
await schedule_emails(subject, senderName, htmlContent, content)
return JSONResponse(content={'success': True, 'message': 'Emails sent successfully'})
async def schedule_emails(subject: str, senderName: str, htmlContent: str, csv_content: bytes):
csv_input = csv.DictReader(io.StringIO(csv_content.decode("UTF-8")))
invalid_emails = []
success_emails = []
for row in csv_input:
recipient_email = row['Email'].strip()
if not is_valid_email(recipient_email):
invalid_emails.append(recipient_email)
continue
# Render HTML content and subject
template = Template(htmlContent)
personalized_html = template.render(row)
subject_template = Template(subject)
personalized_subject = subject_template.render(row)
# Prepare the email message
message = MessageSchema(
subject=personalized_subject,
recipients=[recipient_email],
body=personalized_html,
subtype="html",
)
for attempt in range(retry_attempts):
try:
conf = ConnectionConfig(
MAIL_USERNAME=smtp_config['MAIL_USERNAME'],
MAIL_PASSWORD=smtp_config['MAIL_PASSWORD'],
MAIL_FROM=smtp_config['MAIL_USERNAME'],
MAIL_PORT=smtp_config['MAIL_PORT'],
MAIL_SERVER=smtp_config['MAIL_SERVER'],
MAIL_STARTTLS=smtp_config['MAIL_STARTTLS'],
MAIL_SSL_TLS=smtp_config['MAIL_SSL_TLS'],
USE_CREDENTIALS=smtp_config['USE_CREDENTIALS'],
MAIL_FROM_NAME=senderName,
VALIDATE_CERTS=False
)
mail = FastMail(conf)
# Send the email
await mail.send_message(message)
success_emails.append(recipient_email)
logging.info(f"Email successfully sent to: {recipient_email}")
# Wait for the specified interval before sending the next email
time.sleep(email_send_interval)
break
except Exception as e:
logging.error(f"Attempt {attempt + 1}/{retry_attempts} - Failed to send email to {recipient_email}: {e}")
if attempt < retry_attempts - 1:
time.sleep(email_send_interval)
else:
logging.error(f"All attempts failed for {recipient_email}")
if invalid_emails:
logging.warning(f"Invalid email addresses: {invalid_emails}")
logging.info("=" * 40)
logging.info(f"Email send operation complete. Successful: {len(success_emails)}, Failed: {len(invalid_emails)}")
logging.info("=" * 40)
# Vercel-specific function handler
@app.get("/vercel")
async def vercel():
return JSONResponse(content={"message": "FastAPI is running on Vercel!"})
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)