imip-agent

Change of imiptools/mail.py

83:302a73f826d1
imiptools/mail.py
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/imiptools/mail.py	Tue Oct 28 16:55:26 2014 +0100
     1.3 @@ -0,0 +1,71 @@
     1.4 +#!/usr/bin/env python
     1.5 +
     1.6 +from email.mime.message import MIMEMessage
     1.7 +from email.mime.multipart import MIMEMultipart
     1.8 +from email.mime.text import MIMEText
     1.9 +from smtplib import LMTP, SMTP
    1.10 +
    1.11 +MESSAGE_SENDER = "resources+agent@example.com"
    1.12 +
    1.13 +MESSAGE_SUBJECT = "Calendar system message"
    1.14 +
    1.15 +MESSAGE_TEXT = """\
    1.16 +This is a response to a calendar message sent by your calendar program.
    1.17 +"""
    1.18 +
    1.19 +class Messenger:
    1.20 +
    1.21 +    "Sending of outgoing messages."
    1.22 +
    1.23 +    def __init__(self, sender=None, subject=None, body_text=None):
    1.24 +        self.sender = sender or MESSAGE_SENDER
    1.25 +        self.subject = subject or MESSAGE_SUBJECT
    1.26 +        self.body_text = body_text or MESSAGE_TEXT
    1.27 +
    1.28 +    def sendmail(self, recipients, data, lmtp_socket=None):
    1.29 +
    1.30 +        """
    1.31 +        Send a mail to the given 'recipients' consisting of the given 'data',
    1.32 +        delivering to a local mail system using LMTP if 'lmtp_socket' is
    1.33 +        provided.
    1.34 +        """
    1.35 +
    1.36 +        if lmtp_socket:
    1.37 +            smtp = LMTP(lmtp_socket)
    1.38 +        else:
    1.39 +            smtp = SMTP("localhost")
    1.40 +
    1.41 +        smtp.sendmail(self.sender, recipients, data)
    1.42 +        smtp.quit()
    1.43 +
    1.44 +    def make_message(self, parts, recipients):
    1.45 +
    1.46 +        "Make a message from the given 'parts' for the given 'recipients'."
    1.47 +
    1.48 +        message = MIMEMultipart("mixed", _subparts=parts)
    1.49 +        message.preamble = self.body_text
    1.50 +        payload = message.get_payload()
    1.51 +        payload.insert(0, MIMEText(self.body_text))
    1.52 +
    1.53 +        message["From"] = self.sender
    1.54 +        for recipient in recipients:
    1.55 +            message["To"] = recipient
    1.56 +        message["Subject"] = self.subject
    1.57 +
    1.58 +        return message
    1.59 +
    1.60 +    def wrap_message(self, msg, parts):
    1.61 +
    1.62 +        "Wrap 'msg' and provide the given 'parts' as the primary content."
    1.63 +
    1.64 +        message = MIMEMultipart("mixed", _subparts=parts)
    1.65 +        message.preamble = self.body_text
    1.66 +        message.get_payload().append(MIMEMessage(msg))
    1.67 +
    1.68 +        message["From"] = msg["From"]
    1.69 +        message["To"] = msg["To"]
    1.70 +        message["Subject"] = msg["Subject"]
    1.71 +
    1.72 +        return message
    1.73 +
    1.74 +# vim: tabstop=4 expandtab shiftwidth=4