source: main/waeup.sirp/trunk/src/waeup/sirp/utils/utils.py @ 7382

Last change on this file since 7382 was 7382, checked in by uli, 13 years ago

Dirty hack to enable unicode-aware SMTP handling. This is still not
sufficient.

  • Property svn:keywords set to Id
File size: 4.6 KB
Line 
1## $Id: utils.py 7382 2011-12-18 15:32:10Z uli $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 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 General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18"""General helper utilities for SIRP.
19"""
20import grok
21import smtplib
22import string
23from random import SystemRandom as r
24from email.mime.text import MIMEText
25from waeup.sirp.interfaces import ISIRPUtils
26
27from email.Header import Header
28from email.Utils import parseaddr, formataddr
29
30
31class SIRPUtils(grok.GlobalUtility):
32    """A collection of methods subject to customization.
33    """
34    grok.implements(ISIRPUtils)
35
36    def sendMail(self,fullname,username,usertype,portal,body,
37                 email_from,email_to,subject):
38        """Send an email with data provided by forms.
39        """
40        config = grok.getSite()['configuration']
41        text = """Fullname: %s
42User Id: %s
43User Type: %s
44Portal: %s
45
46%s
47"""
48        msg = MIMEText(text % (fullname,username,usertype,portal,body))
49        msg['From'] = '%s <%s>' % (fullname,email_from)
50        msg['To'] = email_to
51        msg['Subject'] = subject
52        server = smtplib.SMTP(config.smtp_server)
53        if config.smtp_requires_login:
54            server.login(config.smtp_username,config.smtp_password)
55        try:
56            server.sendmail(email_from,email_to,msg.as_string())
57        except:
58            return False
59        server.quit()
60        return True
61
62    def fullname(self,firstname,lastname,middlename=None):
63        # We do not necessarily have the middlename attribute
64        if middlename:
65            return string.capwords(
66                '%s %s %s' % (firstname, middlename, lastname))
67        else:
68            return string.capwords(
69                '%s %s' % (firstname, lastname))
70
71    def genPassword(self, length=8, chars=string.letters + string.digits):
72        return ''.join([r().choice(chars) for i in range(length)])
73
74    def sendPassword(self,fullname,msg,username,password,login_url,
75                 email_to,subject):
76        """Send an email with user credentials.
77
78        XXX: While this method is unicode-proof (i.e. it can handle
79             non-plain-ASCII chars in names and messages) other
80             methods inhere are not and will fail silently. Some
81             reorganization of SMPT-related code is needed here.
82        """
83        config = grok.getSite()['configuration']
84        header_charset = 'ISO-8859-1'
85        text = """Dear %s,
86
87%s
88Student Registration and Information Portal of
89%s.
90
91Your user name: %s
92Your password: %s
93Login page: %s
94
95Please remember your user name and keep
96your password secret!
97
98Please also note that passwords are case-sensitive.
99
100Regards
101"""
102        from_ = '%s <%s>' % (config.name_admin,config.email_admin)
103        from_name, from_addr = parseaddr(from_)
104        rcpt_name, rcpt_addr = parseaddr(email_to)
105        from_name = str(Header(unicode(from_name), header_charset))
106        rcpt_name = str(Header(unicode(rcpt_name), header_charset))
107        from_addr = from_addr.encode('ascii')
108        rpct_addr = rcpt_addr.encode('ascii')
109
110        body = text % (
111                fullname, msg,config.name,username,password,login_url)
112        for body_charset in ['US-ASCII', 'ISO-8859-1', 'UTF-8']:
113            try:
114                body.encode(body_charset)
115            except UnicodeError:
116                print "FAILED: ", body_charset, text
117                pass
118            else:
119                break
120
121        msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
122        msg['From'] = formataddr((from_name, from_addr))
123        msg['To'] = formataddr((rcpt_name, rcpt_addr))
124        msg['Subject'] = Header(unicode(subject), header_charset)
125        server = smtplib.SMTP(config.smtp_server)
126        if config.smtp_requires_login:
127            server.login(config.smtp_username,config.smtp_password)
128        try:
129            server.sendmail(config.email_admin,email_to,msg.as_string())
130        except Exception, e:
131            # XXX: log error message
132            return False
133        server.quit()
134        return True
Note: See TracBrowser for help on using the repository browser.