source: TI05-delivery/ows_framework/trunk/ows_server/ows_server/lib/mailer.py @ 2646

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI05-delivery/ows_framework/trunk/ows_server/ows_server/lib/mailer.py@2646
Revision 2646, 2.3 KB checked in by lawrence, 13 years ago (diff)

Interim check in for citation trackback support and
metadata correction from logged in ndg users.

Line 
1import smtplib
2from email.mime.text import MIMEText
3from email.mime.multipart import MIMEMultipart
4from email.MIMEBase import MIMEBase
5
6
7debug=0
8
9def mailHandler(recipients,subject,body,
10        xmlAttachments=[],sender='ndg@badc.nerc.ac.uk',server='localhost'):
11    ''' Provides a mailing tool for messages from within the stack.
12        If present attachments should be a list of strings with mimetypes,
13            e.g [('<blah>xml</blah>',application,xml),(...),...] '''
14   
15    assert type(recipients)==list
16    assert type(xmlAttachments)==list
17     
18    try:
19   
20        if xmlAttachments==[]:
21           
22            msg=MIMEText(body)
23           
24        else:
25           
26            msg=MIMEMultipart()
27            msg.attach(MIMEText(body))
28       
29            for a in xmlAttachments:
30               
31                part=MIMEBase('application','text/xml')
32                part.set_payload(a[0])
33                # see www.ietf.org/rfc/rfc2183.txt
34                part.add_header('Content-Disposition','attachment; filename="%s"'%a[1])
35                msg.attach(part)
36               
37        msg['From']=sender
38        msg['To']=', '.join(recipients)
39        msg['Subject']=subject
40     
41        smtp=smtplib.SMTP(server)
42        smtp.sendmail(sender,recipients,msg.as_string())
43        smtp.close()
44       
45        return 1,'ok'
46     
47    except Exception,e:
48        return 0, 'Error sending mail [%s]'%e
49       
50       
51if __name__=="__main__":
52   
53    server='outbox.rl.ac.uk'
54    recipients=['b.n.lawrence@rl.ac.uk',]
55   
56    import unittest
57   
58    class TestCase(unittest.TestCase):
59       
60        def AtestNormal(self):
61            ''' test sending a normal email message '''
62            body='test body'
63            subject='mailer test'
64            status,message=mailHandler(recipients,subject,body,server=server)
65            self.assertEqual(message,'ok')
66           
67        def testMime(self):
68            '''test sending an xml attachment '''
69            body='test body'
70            subject='mailer mime test'
71            a=('<xml><something>blah</something></blah>','trackback.xml')
72            att=[a,]
73            status,message=mailHandler(recipients,subject,body,xmlAttachments=att,server=server)
74            self.assertEqual(message,'ok')
75           
76       
77    unittest.main()
78       
Note: See TracBrowser for help on using the repository browser.