Testing Email Registration

 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
# 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)

More like this

  1. email_links by sansmojo 5 years, 11 months ago
  2. Email queue in DB by fish2000 3 years, 1 month ago
  3. Dynamic Models Revisited by Ben 5 years, 7 months ago
  4. SMTP sink server: prettier output by huwshimi 3 years ago
  5. Complex Formsets, Redux by smagala 3 years, 2 months ago

Comments

carljm (on March 10, 2009):

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:

>>> mail.outbox[-1].subject
u'inline registration'
>>> activation_url = mail.outbox[-1].body.strip()
>>> response = c.get(activation_url)

#

osborn.steven (on March 10, 2009):

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.

#

(Forgotten your password?)