-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail_utils.py
More file actions
206 lines (170 loc) · 7.03 KB
/
email_utils.py
File metadata and controls
206 lines (170 loc) · 7.03 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
#!/usr/bin/env python3
"""
Shared Email Utilities
Provides email functionality for both command-line and GUI versions of the media manager.
"""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
import json
import os
import re
class EmailConfig:
"""Email configuration container"""
def __init__(self, sender_name, sender_email, receiver_email, password, smtp_server, smtp_port):
self.sender_name = sender_name
self.sender_email = sender_email
self.receiver_email = receiver_email
self.password = password
self.smtp_server = smtp_server
self.smtp_port = smtp_port
def is_valid(self):
"""Check if all required email configuration is present and valid"""
# Check if all required fields are present
required_fields = [
self.sender_email, self.receiver_email, self.password, self.smtp_server
]
if not all(field for field in required_fields):
return False
# Validate email addresses using basic regex
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_pattern, self.sender_email):
return False
if not re.match(email_pattern, self.receiver_email):
return False
# Validate SMTP port
try:
port = int(self.smtp_port)
if not (1 <= port <= 65535):
return False
except (ValueError, TypeError):
return False
# Check for placeholder values
placeholder_values = [
"SENDER_NAME_HERE", "SENDER_EMAIL_HERE", "RECEIVER_EMAIL_HERE",
"PASSWORD_HERE", "smtp.server.com"
]
config_values = [
self.sender_email, self.receiver_email, self.password, self.smtp_server
]
if any(val in placeholder_values for val in config_values):
return False
return True
def load_email_config_from_file(config_file="media_manager_config.json"):
"""
Load email configuration from GUI config file
Args:
config_file (str): Path to the JSON configuration file
Returns:
EmailConfig or None: Email configuration object or None if loading fails
"""
try:
if os.path.exists(config_file):
with open(config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
email_config = config.get("email", {})
# Check if email is enabled
if not email_config.get("enabled", False):
return None
return EmailConfig(
sender_name=email_config.get("sender_name", ""),
sender_email=email_config.get("sender_email", ""),
receiver_email=email_config.get("receiver_email", ""),
password=email_config.get("password", ""),
smtp_server=email_config.get("smtp_server", "smtp.gmail.com"),
smtp_port=email_config.get("smtp_port", 587)
)
except Exception as e:
print(f"Error loading email config from file: {e}")
return None
def create_email_config_hardcoded():
"""
Create email configuration with hardcoded values (for command-line script)
Returns:
EmailConfig: Email configuration object with hardcoded values
Note:
Users MUST update these values before using. The default values are
intentionally invalid to prevent accidental usage.
To configure:
1. Edit this function in email_utils.py
2. Replace placeholder values with your actual email settings
3. For Gmail: use app passwords, not your regular password
"""
return EmailConfig(
sender_name="SENDER_NAME_HERE",
sender_email="SENDER_EMAIL_HERE",
receiver_email="RECEIVER_EMAIL_HERE",
password="PASSWORD_HERE",
smtp_server="smtp.server.com",
smtp_port=587
)
def send_email(email_config, subject, body, log_function=None):
"""
Send an email using the provided configuration
Args:
email_config (EmailConfig): Email configuration object
subject (str): Email subject
body (str): Email body content
log_function (callable, optional): Function to call for logging messages
Returns:
bool: True if email was sent successfully, False otherwise
"""
if not email_config or not email_config.is_valid():
error_msg = "Email configuration is incomplete or invalid"
if log_function:
log_function(error_msg)
else:
print(error_msg)
return False
try:
message = MIMEMultipart()
message["From"] = formataddr((email_config.sender_name, email_config.sender_email))
message["To"] = email_config.receiver_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
server = smtplib.SMTP(email_config.smtp_server, int(email_config.smtp_port))
server.starttls()
server.login(email_config.sender_email, email_config.password)
server.sendmail(email_config.sender_email, email_config.receiver_email, message.as_string())
server.quit()
success_msg = "Email notification sent successfully"
if log_function:
log_function(success_msg)
else:
print(success_msg)
return True
except Exception as e:
error_msg = f"Error sending email: {e}"
if log_function:
log_function(error_msg)
else:
print(error_msg)
return False
def send_missing_media_email(missing_titles, email_config=None, config_file=None, log_function=None):
"""
Send an email notification about missing media files
Args:
missing_titles (list or set): Collection of missing media titles
email_config (EmailConfig, optional): Email configuration object
config_file (str, optional): Path to config file (if email_config not provided)
log_function (callable, optional): Function to call for logging messages
Returns:
bool: True if email was sent successfully, False otherwise
"""
# Load email config if not provided
if not email_config:
if config_file:
email_config = load_email_config_from_file(config_file)
else:
email_config = create_email_config_hardcoded()
if not email_config or not email_config.is_valid():
error_msg = "Cannot send email: email configuration is incomplete"
if log_function:
log_function(error_msg)
else:
print(error_msg)
return False
subject = "Missing Media Files Detected"
body = f"The following {len(missing_titles)} media files are missing:\n\n" + '\n'.join(sorted(missing_titles))
return send_email(email_config, subject, body, log_function)