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

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

Harmonize sendMail method (work in progress).

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