-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
265 lines (217 loc) · 8.28 KB
/
Copy pathmain.py
File metadata and controls
265 lines (217 loc) · 8.28 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/env python3
"""
Bulk Personalized Email System with PDF Attachments
Main entry point for sending bulk personalized emails with PDF attachments.
Usage:
python main.py <input_file>
python main.py data/recipients.csv
python main.py data/recipients.xlsx
python main.py data/recipients.json
Environment Variables:
SMTP_USERNAME: SMTP authentication username (email address)
SMTP_PASSWORD: SMTP authentication password (app password for Gmail)
"""
import argparse
import sys
from pathlib import Path
from src.bulk_mailer import BulkMailer
from src.config_loader import ConfigLoader, ConfigError
from src.data_parser import DataParserError
from src.email_renderer import EmailRenderer
from src.email_sender import EmailSender
from src.logger import EmailLog, setup_logging
from src.docx_pdf_generator import DocxPDFGenerator
from src.validator import DataValidator
def parse_args() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Send bulk personalized emails with PDF attachments",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python main.py data/recipients.csv
python main.py data/recipients.xlsx --dry-run
python main.py data/recipients.json --config custom_config.yaml
Before running:
1. Copy .env.example to .env
2. Set SMTP_USERNAME and SMTP_PASSWORD in .env
3. For Gmail, use an App Password (https://myaccount.google.com/apppasswords)
"""
)
parser.add_argument(
"input_file",
help="Path to input file (CSV, Excel, or JSON)"
)
parser.add_argument(
"--config", "-c",
default="./config/config.yaml",
help="Path to configuration file (default: ./config/config.yaml)"
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Validate input and show preview without sending emails"
)
parser.add_argument(
"--verbose", "-v",
action="store_true",
help="Enable verbose logging"
)
return parser.parse_args()
def progress_callback(current: int, total: int) -> None:
"""Display progress to console."""
percentage = (current / total) * 100
bar_length = 40
filled = int(bar_length * current / total)
bar = "=" * filled + "-" * (bar_length - filled)
print(f"\rProgress: [{bar}] {current}/{total} ({percentage:.1f}%)", end="", flush=True)
if current == total:
print() # New line at completion
def main() -> int:
"""Main entry point."""
args = parse_args()
# Setup logging
log_level = "DEBUG" if args.verbose else "INFO"
logger = setup_logging(
log_file="./logs/email_sender.log",
log_level=log_level
)
logger.info("=" * 60)
logger.info("Bulk Email System Starting")
logger.info("=" * 60)
try:
# Load configuration
logger.info(f"Loading configuration from {args.config}")
config_loader = ConfigLoader(args.config)
config = config_loader.load()
# Check for credentials
smtp_config = config_loader.get_smtp_config(config)
if not smtp_config['username'] or not smtp_config['password']:
logger.error(
"SMTP credentials not configured. "
"Please set SMTP_USERNAME and SMTP_PASSWORD in .env file"
)
return 1
# Initialize components
pdf_config = config_loader.get_pdf_config(config)
retry_config = config_loader.get_retry_config(config)
throttling_config = config_loader.get_throttling_config(config)
pdf_generator = DocxPDFGenerator(
template_path=pdf_config.get('template_path', './certificate_template.docx'),
output_dir=pdf_config['output_dir']
)
email_renderer = EmailRenderer(
template_dir="./templates",
template_name="email_template.html"
)
email_sender = EmailSender(
**smtp_config,
**retry_config
)
validator = DataValidator(
required_fields=config.get('input', {}).get('required_fields', ['name', 'email'])
)
subject_template = config.get('email', {}).get('subject', 'Your Document, {{name}}')
# Dry run mode
if args.dry_run:
logger.info("DRY RUN MODE - No emails will be sent")
return dry_run(args.input_file, validator, email_renderer, pdf_generator)
# Create bulk mailer
bulk_mailer = BulkMailer(
email_sender=email_sender,
pdf_generator=pdf_generator,
email_renderer=email_renderer,
validator=validator,
delete_pdfs_after_send=pdf_config['delete_after_send'],
subject_template=subject_template,
**throttling_config
)
# Send emails
logger.info(f"Processing input file: {args.input_file}")
result = bulk_mailer.send_from_file(
args.input_file,
progress_callback=progress_callback
)
# Print summary
print("\n" + "=" * 60)
print("SENDING COMPLETE")
print("=" * 60)
print(f"Total records: {result.total_records}")
print(f"Valid records: {result.valid_records}")
print(f"Sent successfully: {result.sent_successfully}")
print(f"Failed: {result.failed}")
print(f"Skipped: {result.skipped}")
print(f"Success rate: {result.success_rate:.1f}%")
print(f"Duration: {result.duration_seconds:.1f} seconds")
print("=" * 60)
# Log failed emails
if result.failed_emails:
logger.warning("Failed emails:")
email_log = EmailLog()
for failure in result.failed_emails:
logger.warning(f" - {failure['email']}: {failure['error']}")
email_log.log_failure(failure['email'], failure['error'])
return 0 if result.failed == 0 else 1
except ConfigError as e:
logger.error(f"Configuration error: {e}")
return 1
except DataParserError as e:
logger.error(f"Input file error: {e}")
return 1
except KeyboardInterrupt:
logger.info("Operation cancelled by user")
return 130
except Exception as e:
logger.exception(f"Unexpected error: {e}")
return 1
def dry_run(
input_file: str,
validator: DataValidator,
email_renderer: EmailRenderer,
pdf_generator: DocxPDFGenerator
) -> int:
"""Run validation and preview without sending."""
from src.data_parser import DataParser
print("\n" + "=" * 60)
print("DRY RUN - VALIDATION ONLY")
print("=" * 60)
# Parse input
parser = DataParser(input_file)
records = parser.parse()
print(f"\nTotal records: {len(records)}")
# Validate
result = validator.validate_batch(records)
print(f"Valid records: {result.valid_count}")
print(f"Invalid records: {result.invalid_count}")
if result.invalid_records:
print("\nInvalid records:")
for invalid in result.invalid_records[:5]: # Show first 5
print(f" - {invalid.record.get('email', 'N/A')}: {', '.join(invalid.errors)}")
if len(result.invalid_records) > 5:
print(f" ... and {len(result.invalid_records) - 5} more")
if result.duplicate_emails:
print(f"\nDuplicate emails: {result.duplicate_emails}")
# Preview first valid record
if result.valid_records:
print("\n" + "-" * 40)
print("PREVIEW (First recipient)")
print("-" * 40)
first = result.valid_records[0]
print(f"Name: {first.get('name')}")
print(f"Email: {first.get('email')}")
# Generate sample PDF
print("\nGenerating sample PDF...")
pdf_path = pdf_generator.generate(first)
print(f"Sample PDF saved: {pdf_path}")
# Show email preview
print("\nEmail HTML preview saved to: ./output/email_preview.html")
html = email_renderer.render(first)
Path("./output").mkdir(parents=True, exist_ok=True)
with open("./output/email_preview.html", 'w', encoding='utf-8') as f:
f.write(html)
print("\n" + "=" * 60)
print("DRY RUN COMPLETE - No emails sent")
print("=" * 60)
return 0
if __name__ == "__main__":
sys.exit(main())