# Put this code somewhere like util/__init__.py and add the
# util app to your INSTALLED_APPS in settings.py. Then
# instead of using the send_mail function in django.core.mail,
# use the wrapper we created in util.
from django.core.mail import send_mail as send_real_mail
from django.conf import settings
def send_mail(subject, message, sender, to):
"""
Send email
"""
if settings.DEBUG:
send_debug_mail(subject, message, sender, to)
send_real_mail(subject, message, sender, to)
def send_debug_mail(subject, message, sender, to):
"""
Save outgoing mail to a file for testing
"""
if not os.path.exists(settings.DEBUG_MAILDIR):
os.mkdir(settings.DEBUG_MAILDIR)
fp = open('%s/%s' % (settings.DEBUG_MAILDIR, str(time.time())) , "w")
fp.writelines([
'From: %s\n' % sender,
'To: %s\n' % ", ".join(to),
'Subject: %s\n\n' % subject,
message
])
fp.close()
# Put this in one of your apps under
# <your app>/management/commands/email_reg.py
from glob import glob
import webbrowser
import re
from django.core.management.base import NoArgsCommand
from django.conf import settings
class Command(NoArgsCommand):
help = "Follow first link in the latest debug email"
requires_model_validation = False
def handle_noargs(self, **options):
latest = ''
for x in glob(settings.DEBUG_MAILDIR + '/*'):
if x > latest:
latest = x
f = open(latest).read()
link = re.search('http:\/\/.*', f).group()
webbrowser.open_new_tab(link)
Comments
I don't get it. Django's test runner automatically sandboxes email for you in mail.outbox rather than sending it. Testing email registration is about this hard:
#
carljm, thanks I wasn't aware of that.
I might still find this useful for manual testing. The email_reg command follows the first link in the email and opens it in your browser which is handy which works for registration and account recovery when I'm just poking around with new features on the site.
Thanks again for the tip.
#