source: main/waeup.sirp/branches/henrik-bootstrap/src/waeup/sirp/utils/utils.py @ 8565

Last change on this file since 8565 was 7407, checked in by Henrik Bettermann, 13 years ago

Harmonize sendCredentials which can now be used for all kinds of users.

  • Property svn:keywords set to Id
File size: 4.4 KB
Line 
1## $Id: utils.py 7407 2011-12-20 11:05:07Z henrik $
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
30def send_mail(from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config):
31    """
32    XXX: While this method is unicode-proof (i.e. it can handle
33         non-plain-ASCII chars in names and messages) other
34         methods inhere are not and will fail silently. Some
35         reorganization of SMPT-related code is needed here.
36    """
37
38    header_charset = 'ISO-8859-1'
39    from_name = str(Header(unicode(from_name), header_charset))
40    rcpt_name = str(Header(unicode(rcpt_name), header_charset))
41    from_addr = from_addr.encode('ascii')
42    rpct_addr = rcpt_addr.encode('ascii')
43    for body_charset in ['US-ASCII', 'ISO-8859-1', 'UTF-8']:
44        try:
45            body.encode(body_charset)
46        except UnicodeError:
47            #print "FAILED: ", body_charset, body
48            pass
49        else:
50            break
51    msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
52    msg['From'] = formataddr((from_name, from_addr))
53    msg['To'] = formataddr((rcpt_name, rcpt_addr))
54    msg['Subject'] = Header(unicode(subject), header_charset)
55    server = smtplib.SMTP(config.smtp_server)
56    if config.smtp_requires_login:
57        server.login(config.smtp_username,config.smtp_password)
58    try:
59        server.sendmail(from_addr,rcpt_addr,msg.as_string())
60    except Exception, e:
61        # XXX: log error message
62        return False
63    server.quit()
64    return True
65
66
67class SIRPUtils(grok.GlobalUtility):
68    """A collection of methods subject to customization.
69    """
70    grok.implements(ISIRPUtils)
71
72    def sendContactForm(self,from_name,from_addr,rcpt_name,rcpt_addr,
73                from_username,usertype,portal,body,subject):
74        """Send an email with data provided by forms.
75        """
76        config = grok.getSite()['configuration']
77        text = """Fullname: %s
78User Id: %s
79User Type: %s
80Portal: %s
81
82%s
83"""
84        body = text % (from_name,from_username,usertype,portal,body)
85        return send_mail(
86            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
87
88    def fullname(self,firstname,lastname,middlename=None):
89        # We do not necessarily have the middlename attribute
90        if middlename:
91            return string.capwords(
92                '%s %s %s' % (firstname, middlename, lastname))
93        else:
94            return string.capwords(
95                '%s %s' % (firstname, lastname))
96
97    def genPassword(self, length=8, chars=string.letters + string.digits):
98        return ''.join([r().choice(chars) for i in range(length)])
99
100
101    def sendCredentials(self, user, password=None, login_url=None, msg=None):
102        """Send credentials as email.
103
104        Input is the applicant for which credentials are sent and the
105        password.
106
107        Returns True or False to indicate successful operation.
108        """
109        subject = 'Your SIRP credentials'
110        text = """Dear %s,
111
112%s
113Student Registration and Information Portal of
114%s.
115
116Your user name: %s
117Your password: %s
118Login page: %s
119
120Please remember your user name and keep
121your password secret!
122
123Please also note that passwords are case-sensitive.
124
125Regards
126"""
127        config = grok.getSite()['configuration']
128        from_name = config.name_admin
129        from_addr = config.email_admin
130        rcpt_name = user.title
131        rcpt_addr = user.email
132        body = text % (
133                rcpt_name, msg,config.name,user.name,password,login_url)
134        return send_mail(
135            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
Note: See TracBrowser for help on using the repository browser.