#!/usr/bin/env python2.3

import os
import StringIO

from email.MIMEMultipart import MIMEMultipart
from email.MIMENonMultipart import MIMENonMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm
from reportlab.lib.pagesizes import A4

recipients = 'craig@postnewspapers.com.au'
sender = 'craig@postnewspapers.com.au'

def gen_pdf():
    pdf_buf = StringIO.StringIO()
    ca = canvas.Canvas(pdf_buf)
    page_width, page_height = A4
    ca.setFont("Times-Bold", 36)
    ca.drawCentredString(page_width / 2, page_height - 1*cm - 36 , "Hello, World")
    ca.showPage()
    ca.save()
    pdf_buf.seek(0)
    return pdf_buf

def build_message(pdf_buf):
    msg = MIMEMultipart()
    msg['Subject'] = "Hello, world"
    msg['From'] = recipients
    msg['To'] = sender
    msg.preamble = 'An invoice is attached in PDF format.'
    msg.epilogue = ''

    msg_text = """A test document is attached. READ IT!
    """
    text_part = MIMEText(msg_text)

    pdf_part = MIMEBase('application','pdf')
    pdf_part.add_header('Content-Disposition', 'attachment', filename='hello_world.pdf')
    pdf_part.set_payload(pdf_buf.read())
    Encoders.encode_base64(pdf_part)

    msg.attach(text_part)
    msg.attach(pdf_part)

    return msg

def main():
    pdf_buf = gen_pdf()
    message = build_message(pdf_buf)
    os.popen("/usr/sbin/sendmail -t","w").write(message.as_string())

if __name__ == '__main__': main()
