1
2
3
4
5
6
7 import smtplib
8 import MimeWriter
9 import base64
10 import StringIO
11
12 """
13 Code to send out mails.
14 """
15
17 """
18 I create e-mail messages with possible attachments.
19 """
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 = []
33
34 - def setContent(self, content):
35 self.content = content
36
38 d = {
39 'name': name,
40 'mime': mime,
41 'content': content,
42 }
43 self.attachments.append(d)
44
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
59 part = writer.nextpart()
60 body = part.startbody('text/plain')
61 body.write(self.content)
62
63
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
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