Package moap :: Package util :: Module mail
[hide private]
[frames] | no frames]

Source Code for Module moap.util.mail

 1  # -*- Mode: Python -*- 
 2  # vi:si:et:sw=4:sts=4:ts=4 
 3   
 4  # code to send out a release announcement of the latest or specified version 
 5  # adapted from http://www.redcor.ch:8180/redcor/redcor/web/intranet_zope_plone/tutorial/faq/SendingMailWithAttachmentsViaPython 
 6   
 7  import smtplib 
 8  import MimeWriter 
 9  import base64 
10  import StringIO 
11   
12  """ 
13  Code to send out mails. 
14  """ 
15   
16 -class Message:
17 """ 18 I create e-mail messages with possible attachments. 19 """
20 - def __init__(self, subject, to, fromm):
21 """ 22 @type to: string or list of strings 23 @param to: who to send mail to 24 @type fromm: string 25 @param fromm: who to send mail as 26 """ 27 self.subject = subject 28 self.to = to 29 if isinstance(to, str): 30 self.to = [to, ] 31 self.fromm = fromm 32 self.attachments = [] # list of dicts
33
34 - def setContent(self, content):
35 self.content = content
36
37 - def addAttachment(self, name, mime, content):
38 d = { 39 'name': name, 40 'mime': mime, 41 'content': content, 42 } 43 self.attachments.append(d)
44
45 - def get(self):
46 """ 47 Get the message. 48 """ 49 50 message = StringIO.StringIO() 51 writer = MimeWriter.MimeWriter(message) 52 writer.addheader('MIME-Version', '1.0') 53 writer.addheader('Subject', self.subject) 54 writer.addheader('To', ", ".join(self.to)) 55 56 writer.startmultipartbody('mixed') 57 58 # start off with a text/plain part 59 part = writer.nextpart() 60 body = part.startbody('text/plain') 61 body.write(self.content) 62 63 # add attachments 64 for a in self.attachments: 65 part = writer.nextpart() 66 part.addheader('Content-Transfer-Encoding', 'base64') 67 body = part.startbody('%(mime)s; name=%(name)s' % a) 68 body.write(base64.encodestring(a['content'])) 69 70 # finish off 71 writer.lastpart() 72 73 return message.getvalue()
74
75 - def send(self, server="localhost"):
76 smtp = smtplib.SMTP(server) 77 result = smtp.sendmail(self.fromm, self.to, self.get()) 78 smtp.close() 79 80 return result
81