-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug_email_sending.py
More file actions
242 lines (194 loc) · 8.31 KB
/
Copy pathdebug_email_sending.py
File metadata and controls
242 lines (194 loc) · 8.31 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
#!/usr/bin/env python3
"""
Debug script for email sending issues
This script helps debug why emails are not being sent when inviting users.
"""
import frappe
import sys
import os
# Add the CRM module to the path
sys.path.append(os.path.join(os.path.dirname(__file__), 'crm'))
def check_email_configuration():
"""Check current email configuration"""
print("🔍 Checking email configuration...")
try:
# Check if email account exists
email_accounts = frappe.get_all("Email Account", filters={"default_outgoing": 1}, limit=1)
if not email_accounts:
print("❌ No default email account configured")
return False
email_account = frappe.get_doc("Email Account", email_accounts[0].name)
print(f"✅ Found email account: {email_account.name}")
print(f" SMTP Server: {email_account.smtp_server}")
print(f" SMTP Port: {email_account.smtp_port}")
print(f" Email ID: {email_account.email_id}")
print(f" SSL: {email_account.use_ssl_for_outgoing}")
print(f" TLS: {email_account.use_tls}")
print(f" Default Outgoing: {email_account.default_outgoing}")
return True
except Exception as e:
print(f"❌ Error checking email configuration: {str(e)}")
return False
def check_email_template():
"""Check if email template exists"""
print("\n🔍 Checking email template...")
try:
template_exists = frappe.db.exists("Email Template", "crm_invitation")
if template_exists:
print("✅ Email template 'crm_invitation' exists")
template = frappe.get_doc("Email Template", "crm_invitation")
print(f" Subject: {template.subject}")
print(f" Use HTML: {template.use_html}")
else:
print("❌ Email template 'crm_invitation' does not exist")
return False
return True
except Exception as e:
print(f"❌ Error checking email template: {str(e)}")
return False
def force_email_configuration():
"""Force email configuration"""
print("\n🔧 Forcing email configuration...")
try:
from crm.utils.email_config import force_email_configuration
success = force_email_configuration()
if success:
print("✅ Email configuration forced successfully")
else:
print("❌ Failed to force email configuration")
return success
except Exception as e:
print(f"❌ Error forcing email configuration: {str(e)}")
return False
def test_email_sending():
"""Test email sending functionality"""
print("\n🧪 Testing email sending...")
try:
from crm.utils.email_config import send_invitation_email
# Test with a dummy invitation
test_email = "test@example.com"
test_link = "https://example.com/test"
print(f" Sending test email to: {test_email}")
email_sent = send_invitation_email(test_email, test_link, "Test Role", "System Administrator")
if email_sent:
print("✅ Test email sent successfully")
else:
print("❌ Test email failed to send")
return email_sent
except Exception as e:
print(f"❌ Error testing email sending: {str(e)}")
return False
def create_test_invitation():
"""Create a test invitation to trigger email sending"""
print("\n📧 Creating test invitation...")
try:
# Check if test invitation already exists
existing_invitation = frappe.db.exists("CRM Invitation", {"email": "test@example.com"})
if existing_invitation:
print(" Test invitation already exists, using existing one")
invitation = frappe.get_doc("CRM Invitation", existing_invitation)
else:
print(" Creating new test invitation")
invitation = frappe.get_doc({
"doctype": "CRM Invitation",
"email": "test@example.com",
"role": "Sales User"
})
invitation.insert(ignore_permissions=True)
print(f" Invitation created: {invitation.name}")
print(f" Status: {invitation.status}")
print(f" Email sent at: {invitation.email_sent_at}")
# Manually trigger email sending
print(" Manually triggering email sending...")
email_sent = invitation.invite_via_email()
if email_sent:
print("✅ Invitation email sent successfully")
invitation.db_set("email_sent_at", frappe.utils.now())
else:
print("❌ Invitation email failed to send")
return email_sent
except Exception as e:
print(f"❌ Error creating test invitation: {str(e)}")
return False
def check_email_queue():
"""Check email queue for recent emails"""
print("\n📬 Checking email queue...")
try:
# Get recent email queue entries
email_queue = frappe.get_all("Email Queue",
filters={"creation": [">", frappe.utils.add_days(frappe.utils.now(), -1)]},
fields=["name", "recipients", "status", "error", "creation"]
)
if email_queue:
print(f" Found {len(email_queue)} recent email queue entries:")
for email in email_queue:
print(f" - {email['recipients']} - Status: {email['status']}")
if email['error']:
print(f" Error: {email['error']}")
else:
print(" No recent email queue entries found")
return email_queue
except Exception as e:
print(f"❌ Error checking email queue: {str(e)}")
return []
def main():
"""Run all debug checks"""
print("🚀 Starting Email Sending Debug")
print("=" * 50)
# Initialize Frappe
try:
frappe.init(site="localhost")
frappe.connect()
except Exception as e:
print(f"❌ Failed to initialize Frappe: {str(e)}")
return False
try:
# Run debug checks
checks = [
("Email Configuration", check_email_configuration),
("Email Template", check_email_template),
("Force Email Configuration", force_email_configuration),
("Test Email Sending", test_email_sending),
("Create Test Invitation", create_test_invitation),
("Check Email Queue", check_email_queue),
]
results = {}
for check_name, check_func in checks:
print(f"\n📋 Running {check_name}...")
try:
result = check_func()
results[check_name] = result
if result:
print(f"✅ {check_name} passed")
else:
print(f"❌ {check_name} failed")
except Exception as e:
print(f"❌ {check_name} error: {str(e)}")
results[check_name] = False
# Summary
print("\n" + "=" * 50)
print("📊 Debug Results:")
for check_name, result in results.items():
status = "✅ PASS" if result else "❌ FAIL"
print(f" {check_name}: {status}")
# Recommendations
print("\n💡 Recommendations:")
if not results.get("Email Configuration", False):
print(" - Configure email account in Email Account doctype")
print(" - Set default_outgoing = 1 for the email account")
if not results.get("Email Template", False):
print(" - Create email template 'crm_invitation'")
print(" - Ensure template has proper HTML content")
if not results.get("Test Email Sending", False):
print(" - Check SMTP server settings")
print(" - Verify email credentials")
print(" - Check firewall/network settings")
if not results.get("Create Test Invitation", False):
print(" - Check CRM Invitation doctype permissions")
print(" - Verify after_insert method is working")
return True
finally:
frappe.destroy()
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)