Added some test-writing docs for plugins, but not sure if they're good. ;)
[mediagoblin.git] / mediagoblin / tools / mail.py
CommitLineData
03ae172a 1# GNU MediaGoblin -- federated, autonomous media hosting
cf29e8a8 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
03ae172a
AW
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Affero General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Affero General Public License for more details.
13#
14# You should have received a copy of the GNU Affero General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17import smtplib
18from email.MIMEText import MIMEText
02b6892c 19from mediagoblin import mg_globals, messages
03ae172a
AW
20from mediagoblin.tools import common
21
22### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
23### Special email test stuff begins HERE
24### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
25
26# We have two "test inboxes" here:
ee91c2b8 27#
03ae172a
AW
28# EMAIL_TEST_INBOX:
29# ----------------
30# If you're writing test views, you'll probably want to check this.
31# It contains a list of MIMEText messages.
32#
33# EMAIL_TEST_MBOX_INBOX:
34# ----------------------
35# This collects the messages from the FakeMhost inbox. It's reslly
36# just here for testing the send_email method itself.
37#
38# Anyway this contains:
39# - from
40# - to: a list of email recipient addresses
41# - message: not just the body, but the whole message, including
42# headers, etc.
43#
44# ***IMPORTANT!***
45# ----------------
46# Before running tests that call functions which send email, you should
ee91c2b8 47# always call _clear_test_inboxes() to "wipe" the inboxes clean.
03ae172a
AW
48
49EMAIL_TEST_INBOX = []
50EMAIL_TEST_MBOX_INBOX = []
51
ee91c2b8 52
03ae172a
AW
53class FakeMhost(object):
54 """
55 Just a fake mail host so we can capture and test messages
56 from send_email
57 """
58 def login(self, *args, **kwargs):
59 pass
60
61 def sendmail(self, from_addr, to_addrs, message):
62 EMAIL_TEST_MBOX_INBOX.append(
63 {'from': from_addr,
64 'to': to_addrs,
65 'message': message})
66
ee91c2b8 67
03ae172a
AW
68def _clear_test_inboxes():
69 global EMAIL_TEST_INBOX
70 global EMAIL_TEST_MBOX_INBOX
71 EMAIL_TEST_INBOX = []
72 EMAIL_TEST_MBOX_INBOX = []
73
ee91c2b8 74
03ae172a
AW
75### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
76### </Special email test stuff>
77### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
78
79def send_email(from_addr, to_addrs, subject, message_body):
80 """
81 Simple email sending wrapper, use this so we can capture messages
82 for unit testing purposes.
83
84 Args:
85 - from_addr: address you're sending the email from
86 - to_addrs: list of recipient email addresses
87 - subject: subject of the email
88 - message_body: email body text
89 """
90 if common.TESTS_ENABLED or mg_globals.app_config['email_debug_mode']:
91 mhost = FakeMhost()
92 elif not mg_globals.app_config['email_debug_mode']:
93 mhost = smtplib.SMTP(
94 mg_globals.app_config['email_smtp_host'],
95 mg_globals.app_config['email_smtp_port'])
96
97 # SMTP.__init__ Issues SMTP.connect implicitly if host
98 if not mg_globals.app_config['email_smtp_host']: # e.g. host = ''
99 mhost.connect() # We SMTP.connect explicitly
100
16b8e3af
BS
101 if ((not common.TESTS_ENABLED)
102 and (mg_globals.app_config['email_smtp_user']
103 or mg_globals.app_config['email_smtp_pass'])):
03ae172a
AW
104 mhost.login(
105 mg_globals.app_config['email_smtp_user'],
106 mg_globals.app_config['email_smtp_pass'])
107
108 message = MIMEText(message_body.encode('utf-8'), 'plain', 'utf-8')
109 message['Subject'] = subject
110 message['From'] = from_addr
111 message['To'] = ', '.join(to_addrs)
112
113 if common.TESTS_ENABLED:
114 EMAIL_TEST_INBOX.append(message)
115
16b8e3af 116 elif mg_globals.app_config['email_debug_mode']:
03ae172a
AW
117 print u"===== Email ====="
118 print u"From address: %s" % message['From']
119 print u"To addresses: %s" % message['To']
120 print u"Subject: %s" % message['Subject']
121 print u"-- Body: --"
122 print message.get_payload(decode=True)
123
124 return mhost.sendmail(from_addr, to_addrs, message.as_string())
0f9cf6ef
SS
125
126
127def normalize_email(email):
128 """return case sensitive part, lower case domain name
129
130 :returns: None in case of broken email addresses"""
131 try:
132 em_user, em_dom = email.split('@', 1)
133 except ValueError:
134 # email contained no '@'
135 return None
136 email = "@".join((em_user, em_dom.lower()))
137 return email
02b6892c
RE
138
139
140def email_debug_message(request):
141 """
142 If the server is running in email debug mode (which is
143 the current default), give a debug message to the user
144 so that they have an idea where to find their email.
145 """
146 if mg_globals.app_config['email_debug_mode']:
147 # DEBUG message, no need to translate
148 messages.add_message(request, messages.DEBUG,
149 u"This instance is running in email debug mode. "
150 u"The email will be on the console of the server process.")