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

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

Rename sendMail method to be more precise and not confuse with the send_mail function.

  • Property svn:keywords set to Id
File size: 4.5 KB
Line 
1## $Id: utils.py 7404 2011-12-20 09:33:10Z 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, applicant, password, login_url):
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        username = applicant.applicant_id
110        subject = 'Your SIRP credentials'
111        msg = 'You have successfully been registered for the'
112        text = """Dear %s,
113
114%s
115Student Registration and Information Portal of
116%s.
117
118Your user name: %s
119Your password: %s
120Login page: %s
121
122Please remember your user name and keep
123your password secret!
124
125Please also note that passwords are case-sensitive.
126
127Regards
128"""
129        config = grok.getSite()['configuration']
130        from_name = config.name_admin
131        from_addr = config.email_admin
132        rcpt_name = applicant.display_fullname
133        rcpt_addr = applicant.email
134        body = text % (
135                rcpt_name, msg,config.name,username,password,login_url)
136        return send_mail(
137            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
Note: See TracBrowser for help on using the repository browser.