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

Source Code for Module moap.util.mail

  1  # -*- Mode: Python; test-case-name: moap.test.test_util_mail -*- 
  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   
  9  # P2.3 
 10  try: 
 11      from email import encoders 
 12  except ImportError: 
 13      from email import Encoders as encoders 
 14   
 15  # P2.3 
 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   
29 -class Message:
30 """ 31 I create e-mail messages with possible attachments. 32 """
33 - def __init__(self, subject, to, fromm):
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 = [] # list of dicts
46
47 - def setContent(self, content):
48 self.content = content
49
50 - def addAttachment(self, name, mime, content):
51 d = { 52 'name': name, 53 'mime': mime, 54 'content': content, 55 } 56 self.attachments.append(d)
57
58 - def get(self):
59 """ 60 Get the message. 61 """ 62 COMMASPACE = ', ' 63 64 # Create the container (outer) email message. 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 # add attachments 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 # Encode the payload using Base64 84 encoders.encode_base64(msg) 85 # Set the filename parameter 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