1
2
3
4
5
6
7 import smtplib
8
9
10 try:
11 from email import encoders
12 except ImportError:
13 from email import Encoders as encoders
14
15
16 try:
17 from email.mime import multipart, text, image, audio, base
18 except ImportError:
19 from email import MIMEMultipart as multipart
20 from email import MIMEText as text
21 from email import MIMEImage as image
22 from email import MIMEAudio as audio
23 from email import MIMEBase as base
24
25 """
26 Code to send out mails.
27 """
28
30 """
31 I create e-mail messages with possible attachments.
32 """
34 """
35 @type to: string or list of strings
36 @param to: who to send mail to
37 @type fromm: string
38 @param fromm: who to send mail as
39 """
40 self.subject = subject
41 self.to = to
42 if isinstance(to, str):
43 self.to = [to, ]
44 self.fromm = fromm
45 self.attachments = []
46
47 - def setContent(self, content):
48 self.content = content
49
51 d = {
52 'name': name,
53 'mime': mime,
54 'content': content,
55 }
56 self.attachments.append(d)
57
59 """
60 Get the message.
61 """
62 COMMASPACE = ', '
63
64
65 msg = multipart.MIMEMultipart()
66 msg['Subject'] = self.subject
67 msg['From'] = self.fromm
68 msg['To'] = COMMASPACE.join(self.to)
69 msg.preamble = self.content
70
71
72 for a in self.attachments:
73 maintype, subtype = a['mime'].split('/', 1)
74 if maintype == 'text':
75 attach = text.MIMEText(a['content'], _subtype=subtype)
76 elif maintype == 'image':
77 attach = image.MIMEImage(a['content'], _subtype=subtype)
78 elif maintype == 'audio':
79 attach = audio.MIMEAudio(a['content'], _subtype=subtype)
80 else:
81 attach = base.MIMEBase(maintype, subtype)
82 attach.set_payload(a['content'])
83
84 encoders.encode_base64(msg)
85
86 attach.add_header(
87 'Content-Disposition', 'attachment', filename=a['name'])
88 msg.attach(attach)
89
90 return msg.as_string()
91
92
93 - def send(self, server="localhost"):
94 smtp = smtplib.SMTP(server)
95 result = smtp.sendmail(self.fromm, self.to, self.get())
96 smtp.close()
97
98 return result
99