forked from saikesav-sai/dripemails_web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_smtp_auth.py
More file actions
295 lines (234 loc) · 10 KB
/
test_smtp_auth.py
File metadata and controls
295 lines (234 loc) · 10 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/env python3
"""
Test script for DripEmails SMTP server authentication.
This script tests the SMTP server authentication using the founders account.
Run this after starting the SMTP server with: python manage.py run_smtp_server
Compatible with Python 3.12.3+
"""
import smtplib
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime
import sys
def test_smtp_authentication(host='localhost', port=25, username='founders', password='your_password'):
"""Test SMTP authentication with the founders account."""
try:
print(f"Testing SMTP authentication on {host}:{port}...")
print(f"Username: {username}")
# Create SMTP connection
server = smtplib.SMTP(host, port)
server.set_debuglevel(1) # Enable debug output
# Say hello
server.helo('test-client')
# Check if authentication is supported
print("Checking authentication capabilities...")
code, response = server.docmd('EHLO', 'test-client')
print(f"EHLO response: {code} - {response}")
# Try to authenticate
print(f"Attempting authentication for user: {username}")
try:
server.login(username, password)
print("✅ Authentication successful!")
return True
except smtplib.SMTPAuthenticationError as e:
print(f"❌ Authentication failed: {e}")
return False
except Exception as e:
print(f"❌ Authentication error: {e}")
return False
finally:
server.quit()
except Exception as e:
print(f"❌ SMTP connection failed: {e}")
return False
def send_authenticated_email(host='localhost', port=25, username='founders', password='your_password',
from_email='founders@dripemails.org', to_email='test@dripemails.org'):
"""Send an email using authentication."""
try:
print(f"Sending authenticated email from {from_email} to {to_email}...")
# Create message
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = f'Authenticated Test Email - {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}'
# Email body
body = f"""
This is a test email sent using SMTP authentication.
Timestamp: {datetime.now().isoformat()}
From: {from_email}
To: {to_email}
Authenticated User: {username}
This email was sent using authenticated SMTP access.
Best regards,
DripEmails Founders
"""
msg.attach(MIMEText(body, 'plain'))
# Send email with authentication
server = smtplib.SMTP(host, port)
server.set_debuglevel(1)
# Authenticate
server.login(username, password)
# Send the email
text = msg.as_string()
server.sendmail(from_email, to_email, text)
server.quit()
print("✅ Authenticated email sent successfully!")
return True
except smtplib.SMTPAuthenticationError as e:
print(f"❌ Authentication failed: {e}")
return False
except Exception as e:
print(f"❌ Failed to send authenticated email: {e}")
return False
def test_plain_authentication(host='localhost', port=25, username='founders', password='your_password'):
"""Test PLAIN authentication mechanism."""
try:
print(f"Testing PLAIN authentication for user: {username}")
# Create SMTP connection
server = smtplib.SMTP(host, port)
server.set_debuglevel(1)
# Say hello
server.helo('test-client')
# Create PLAIN authentication credentials
credentials = f'\0{username}\0{password}'
encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
# Send AUTH PLAIN command
code, response = server.docmd('AUTH', f'PLAIN {encoded_credentials}')
print(f"AUTH PLAIN response: {code} - {response}")
if code == 235:
print("✅ PLAIN authentication successful!")
server.quit()
return True
else:
print(f"❌ PLAIN authentication failed: {response}")
server.quit()
return False
except Exception as e:
print(f"❌ PLAIN authentication error: {e}")
return False
def test_login_authentication(host='localhost', port=25, username='founders', password='your_password'):
"""Test LOGIN authentication mechanism."""
try:
print(f"Testing LOGIN authentication for user: {username}")
# Create SMTP connection
server = smtplib.SMTP(host, port)
server.set_debuglevel(1)
# Say hello
server.helo('test-client')
# Encode username and password
encoded_username = base64.b64encode(username.encode('utf-8')).decode('utf-8')
encoded_password = base64.b64encode(password.encode('utf-8')).decode('utf-8')
# Send AUTH LOGIN command
code, response = server.docmd('AUTH', f'LOGIN {encoded_username}')
print(f"AUTH LOGIN username response: {code} - {response}")
if code == 334:
# Send password
code, response = server.docmd(encoded_password)
print(f"AUTH LOGIN password response: {code} - {response}")
if code == 235:
print("✅ LOGIN authentication successful!")
server.quit()
return True
else:
print(f"❌ LOGIN authentication failed: {response}")
server.quit()
return False
else:
print(f"❌ LOGIN authentication failed at username step: {response}")
server.quit()
return False
except Exception as e:
print(f"❌ LOGIN authentication error: {e}")
return False
def test_unauthorized_access(host='localhost', port=25):
"""Test that unauthorized users cannot send emails."""
try:
print("Testing unauthorized access (should fail)...")
# Create SMTP connection
server = smtplib.SMTP(host, port)
server.set_debuglevel(1)
# Say hello
server.helo('test-client')
# Try to send email without authentication
msg = MIMEText("This should fail without authentication")
msg['From'] = 'unauthorized@example.com'
msg['To'] = 'test@dripemails.org'
msg['Subject'] = 'Unauthorized Test'
try:
server.sendmail('unauthorized@example.com', 'test@dripemails.org', msg.as_string())
print("❌ Unauthorized access succeeded (this should have failed)")
server.quit()
return False
except smtplib.SMTPResponseException as e:
if e.smtp_code == 530:
print("✅ Unauthorized access correctly blocked")
server.quit()
return True
else:
print(f"❌ Unexpected error for unauthorized access: {e}")
server.quit()
return False
except Exception as e:
print(f"❌ Unauthorized access test error: {e}")
return False
def main():
"""Run all SMTP authentication tests."""
print("🔐 DripEmails SMTP Authentication Test Suite")
print("=" * 60)
# Configuration
host = 'localhost'
port = 25
username = 'founders'
password = 'your_password' # Replace with actual password
print(f"Testing SMTP authentication on {host}:{port}")
print(f"Username: {username}")
print("Note: Replace 'your_password' with the actual founders password")
print()
# Get password from user if not provided
if password == 'your_password':
password = input("Enter the founders password: ")
if not password:
print("❌ No password provided. Exiting.")
sys.exit(1)
# Run tests
tests = [
("SMTP Authentication", lambda: test_smtp_authentication(host, port, username, password)),
("PLAIN Authentication", lambda: test_plain_authentication(host, port, username, password)),
("LOGIN Authentication", lambda: test_login_authentication(host, port, username, password)),
("Authenticated Email", lambda: send_authenticated_email(host, port, username, password)),
("Unauthorized Access", lambda: test_unauthorized_access(host, port)),
]
results = []
for test_name, test_func in tests:
print(f"\n🔍 Running: {test_name}")
print("-" * 40)
try:
result = test_func()
results.append((test_name, result))
except Exception as e:
print(f"❌ Test failed with exception: {e}")
results.append((test_name, False))
# Summary
print("\n" + "=" * 60)
print("📊 Authentication Test Results Summary")
print("=" * 60)
passed = 0
for test_name, result in results:
status = "✅ PASS" if result else "❌ FAIL"
print(f"{test_name}: {status}")
if result:
passed += 1
print(f"\nOverall: {passed}/{len(results)} tests passed")
if passed == len(results):
print("🎉 All authentication tests passed! The SMTP server is working correctly.")
else:
print("⚠️ Some authentication tests failed. Check the configuration.")
print("\n💡 Tips:")
print("- Make sure the SMTP server is running: python manage.py run_smtp_server")
print("- Ensure the 'founders' user exists in Django with correct password")
print("- Check that authentication is enabled (not using --no-auth)")
print("- Verify the server logs for authentication attempts")
print("- Use 'python manage.py createsuperuser' to create the founders account")
if __name__ == "__main__":
main()