# WARNING: This software is for educational purposes only.
"""
The MIT License (MIT)

Copyright (c) 2014

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

# Improved version; original by LeXeL lexelEZ[at]gmail[dot]com

@delta24

"""
import simplejson as json
import sys
import time
import threading
import socket

from email.MIMEText import MIMEText
import mimetypes
from smtplib import (SMTP, SMTP_SSL, SMTPException, SMTPRecipientsRefused,
                     SMTPSenderRefused, SMTPServerDisconnected)


def Banner():
    print """
        ###########################################################
                     _ _   _                     _
     _ __ ___   __ _(_) | | |__   ___  _ __ ___ | |__   ___ _ __
    | '_ ` _ \ / _` | | | | '_ \ / _ \| '_ ` _ \| '_ \ / _ \ '__|
    | | | | | | (_| | | | | |_) | (_) | | | | | | |_) |  __/ |
    |_| |_| |_|\__,_|_|_| |_.__/ \___/|_| |_| |_|_.__/ \___|_|

        Ex. python bomber.py smtp.gmail.com 465

        Specify your username, password, and number of emails to be sent
        ###########################################################
        """

class MassMailer(object):
    """
    Mass Mailer class, resposible for
        + Build email
        + Conneting to mailServer
        + authentication
        and sending
    """

    def __init__(self, use_tls=None, fail_silently=False, **kwargs):
        self.SMTPserver = sys.argv[1]
        self.SMTPport = sys.argv[2]

        with open('config', 'r') as keyfile:
            data = keyfile.read()
            conf = json.loads(data)
            self.user = conf["user"]
            self.password = conf["password"]
            self.num_mails = conf["n"]

        self.use_tls = use_tls
        self.fail_silently = fail_silently

    def SMTPconnect(self):
        """
        + Checks the connection to SMTP server
           - If not, exits cleanly

        + Connects to SMTP server, authenticates.

        + Ensures we have a connection to the email server. Returns whether or
          not a new connection was required (True or False).
        """

        try:
            connection = SMTP(self.SMTPserver, self.SMTPport)
            if self.use_tls:
                connection.ehlo()
                connection.starttls()
                connection.ehlo()
            if self.username and self.password:
                connection.login(self.username, self.password)
            return True
        except:
            if not self.fail_silently:
                raise

    def close(self):
        """Closes the connection to the SMTP server."""
        try:
            try:
                connection.quit()
            except socket.sslerror:
                # This happens when calling quit() on a TLS connection
                # sometimes.
                connection.close()
            except:
                if self.fail_silently:
                    return
                raise
        finally:
            connection = None

    def build(self):
        """
        + Builds the message

          - Both formats should be supported: plaintext/HTML
        """


