import smtplib
import traceback
import os
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.message import EmailMessage
import codecs
import jinja2
import re
import random as rd
from personal_settings import *


def mail2(mailobj):


    gmail_user = mailobj['gmail_user']
    gmail_password = mailobj['gmail_password']
    toaddr = mailobj['toaddr']
    to_text = mailobj['totext']

    to = [toaddr]
    sent_from = gmail_user
    
    

    msg = MIMEMultipart()
    msg['Subject'] = mailobj['title']
    msg['From'] = gmail_user
    msg['To'] = toaddr
    msg.attach(MIMEText(to_text))



    path = './templates/index.html'
    fr=codecs.open(path,'r','utf-8')
    html_=fr.read()
    image_paths=[]
    initial_count = 0
    dir_ = "./templates/images/"
    def sorted_alphanumeric(data):
        convert = lambda text: int(text) if text.isdigit() else text.lower()
        alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] 
        return sorted(data, key=alphanum_key)
    image_cate =[]
    for path in sorted_alphanumeric(os.listdir(dir_)):
        image_paths.append(dir_+path)
        image_cate.append(path.split(".")[-1])
    image_cate=set(image_cate)
    body_use=re.findall(r'<body.*?>',html_)[0]
    html_ =re.sub(r'<body.*?>', r"%s<img src='http://www.google-analytics.com/collect?v=1&tid=UA-153100602-5&cid=%d&t=event&ec=email&ea=open&el=%s&cs=newsletter&cm=email&cn=%d&dt=%d'>"%(body_use,rd.randint(1000,9999),toaddr,rd.randint(1000,9999),rd.randint(1000,9999)), html_)
    
    
   
    for j in image_cate:
        dir_2 ="images/image-%s.%s"
        for i in range(len(image_paths)):
            # print(dir_2%(i+1,j))
            html_ = html_.replace(dir_2%(i+1,j), "cid:image%s"%(i+1))
    msgAlternative = MIMEMultipart('alternative')
    msg.attach(msgAlternative)
    content=html_
    
    
    text = MIMEText(content,'html','utf-8')

    counter = 1
    for fp in image_paths:
        fp = open(fp, 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        # Define the image's ID as referenced above
        msgImage.add_header('Content-ID', '<image'+str(counter)+'>')
        msgAlternative.attach(msgImage)
        counter += 1

    msgAlternative.attach(text)
    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_password)
        server.sendmail(sent_from, to,  msg.as_string())
        server.close()
        print ('Email sent!')
    except:
        traceback.print_exc()
        print ('Something went wrong...')







if __name__ == "__main__":
	mailobj={}
	mailobj['toaddr']=gmail_toaddr
	mailobj['gmail_user']=gmail_user
	mailobj['gmail_password']=gmail_password
	mailobj['title'] = gmail_title
	mailobj['totext'] = gmail_totext
	mail2(mailobj)
