1 #!/usr/bin/env python 2 3 from imiptools.config import MESSAGE_SENDER 4 from email.mime.message import MIMEMessage 5 from email.mime.multipart import MIMEMultipart 6 from email.mime.text import MIMEText 7 from smtplib import LMTP, SMTP 8 9 MESSAGE_SUBJECT = "Calendar system message" 10 11 MESSAGE_TEXT = """\ 12 This is a response to a calendar message sent by your calendar program. 13 """ 14 15 PREAMBLE_TEXT = """\ 16 This message contains several different parts, one of which will contain 17 calendar information that will only be understood by a suitable program. 18 """ 19 20 class Messenger: 21 22 "Sending of outgoing messages." 23 24 def __init__(self, sender=None, subject=None, body_text=None, preamble_text=None): 25 self.sender = sender or MESSAGE_SENDER 26 self.subject = subject or MESSAGE_SUBJECT 27 self.body_text = body_text or MESSAGE_TEXT 28 self.preamble_text = preamble_text or PREAMBLE_TEXT 29 30 def sendmail(self, recipients, data, sender=None, lmtp_socket=None): 31 32 """ 33 Send a mail to the given 'recipients' consisting of the given 'data', 34 using the given 'sender' identity if indicated, delivering to a local 35 mail system using LMTP if 'lmtp_socket' is provided. 36 """ 37 38 if lmtp_socket: 39 smtp = LMTP(lmtp_socket) 40 else: 41 smtp = SMTP("localhost") 42 43 smtp.sendmail(sender or self.sender, recipients, data) 44 smtp.quit() 45 46 def make_message(self, parts, recipients, sender=None): 47 48 """ 49 Make a message from the given 'parts' for the given 'recipients', using 50 the given 'sender' identity if indicated. 51 """ 52 53 message = MIMEMultipart("mixed", _subparts=parts) 54 message.preamble = self.preamble_text 55 payload = message.get_payload() 56 payload.insert(0, MIMEText(self.body_text)) 57 58 message["From"] = sender or self.sender 59 for recipient in recipients: 60 message["To"] = recipient 61 message["Subject"] = self.subject 62 63 return message 64 65 def wrap_message(self, msg, parts): 66 67 "Wrap 'msg' and provide the given 'parts' as the primary content." 68 69 message = MIMEMultipart("mixed", _subparts=parts) 70 message.preamble = self.preamble_text 71 payload = message.get_payload() 72 payload.insert(0, MIMEText(self.body_text)) 73 payload.append(MIMEMessage(msg)) 74 75 message["From"] = msg["From"] 76 message["To"] = msg["To"] 77 message["Subject"] = msg["Subject"] 78 79 return message 80 81 # vim: tabstop=4 expandtab shiftwidth=4