import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from config import *


""" Send a mail to only one receiver, probably with a attachment. 

DEPENDENCIES: config.py
"""


def sendto(receiver, subject, body, filepath=None):
    """
    send a mail to receiver

    :param receiver: email address like aaa@bbb.com
    :param subject:
    :param body:
    :param filepath: full path of a readable file
    :return: None or raise an exception
    """
    msg = MIMEMultipart()
    msg['From'] = smtp_user
    msg['To'] = receiver
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    if filepath is not None:
        with open(filepath, 'rb') as h:
            attach_content = h.read()
        attached = MIMEBase('application', 'octet-stream')
        attached.set_payload(attach_content)
        encoders.encode_base64(attached)
        filename = os.path.split(filepath)[-1]
        attached.add_header('Content-Disposition', 'attachment; filename={}'.format(filename))
        msg.attach(attached)

    s = smtplib.SMTP(smtp_host, smtp_port)
    s.starttls()
    s.login(smtp_user, smtp_password)
    s.sendmail(smtp_user, receiver, msg.as_string())
    s.quit()
