#!/usr/bin/python

""" Send a bunch of random emails to different email accounts. """

# I, Yannick Gingras <ygingras@ygingras.net>, the author of this
# script, do not claim any copyright on it.  I hereby put it in the
# Public Domain.

import sys
import smtplib
from optparse import OptionParser
import re
import os
from random import sample, randrange, choice
from pprint import pprint

SENTENCE_RE = re.compile(r"([A-Z][a-z][^:]+?[a-z])\.", re.DOTALL)

def normspaces(text):
    return re.sub("(\s+)", " ", text)

def makemail(sentences, files=[]):
    subject = normspaces(choice(sentences))
    content = ".  ".join(map(normspaces, 
                             sample(sentences, randrange(10, 200)))) + "."
    
    if files:
        from email.mime.image import MIMEImage
        from email.mime.multipart import MIMEMultipart

        msg = MIMEMultipart()
        msg.preamble = content
        img = MIMEImage(open(choice(files)).read())
        msg.attach(img)
        
    else:
        from email.mime.text import MIMEText
        msg = msg = MIMEText(content)
    msg["Subject"] = subject
    
    return msg


def send(msg, from_addr, to_addr):
    msg["To"] = to_addr
    msg["From"] = from_addr
    server = smtplib.SMTP('localhost')
    server.sendmail(from_addr, to_addr, msg.as_string())
    server.quit()
    

def main():
    parser = OptionParser(usage=("%prog TEXT FROM EMAIL1 [EMAIL2 ...]"
                                 "\n where TEXT is the source of prose"
                                 " for message bodies "
                                 "\nFROM is the addr the emails will seem to "
                                 " come from"
                                 "\nEMAILn"
                                 " are valid email addresses"
                                 )
                          )
    
    parser.add_option("-n", dest="nb_mails", default=10, type=int,
                      help="number of mail to send")
    parser.add_option("-a", "--attach-dir", dest="attach_dir", default=None,
                      metavar="DIR",
                      help="take random attachments from dir")

    (opts, args) = parser.parse_args()
    if args < 3:
        parser.print_usage()
        sys.exit(1)

    if opts.attach_dir:
        files=filter(lambda f:os.path.isfile(f) and f.endswith(".jpg"), 
                     [os.path.join(opts.attach_dir, f) 
                      for f in os.listdir(opts.attach_dir)])
    else:
        files = None

    sentences = SENTENCE_RE.findall(open(args[0]).read())

    for i in range(opts.nb_mails):
        msg = makemail(sentences, files)
        for to_addr in args[2:]:
            send(msg, args[1], to_addr)

if __name__ == "__main__":
    main()

