# -*- coding: utf-8 -*-

import telnetlib, struct
import time, base64, json

from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE,formatdate
from email import encoders
 
import base64, time, simplejson, os

from datetime import datetime, date

HOST = '10.10.126.221'
HOST = '10.10.127.105'
HOST = 'smtpcloud.sohu.com'
HOST = '220.181.69.174'

HOST = '10.16.2.29'
HOST = '10.10.127.107'
PORT = 25
USE_SSL = True
category = 'postmaster@liubida.sendcloud.org' #push
passwd = 'delong'
category = 'ftest5_push'
passwd = 'F2g18vYBVYJKVaTn'

category = 'liubida456_test_CQFO7T'
passwd = 'yhKUFJaC9RyZXqLr'

category = 'jiangliantest_20141029'
passwd = '123456'

category = 'postmaster@delongbat.sendcloud.org'  #push
passwd = 'longde'

category = 'postmaster@delongbat.sendcloud.org' #push
passwd = 'longde'

category = 'postmaster@delong.sendcloud.org'  #trans
passwd = 'delong'

category = 'jiangliantest_20141029'
passwd = '123456'
category = 'postmaster@delongbat.sendcloud.org'  #trans
passwd = 'longde'
#category = 'yuanabaoifaxin_WAhhL2bq'
#passwd = 'ZbOlTjQ8'

mail_from = 'test@liubida.cn'
rcpt_to = ['dada.chao.liu@qq.com', 'dayday111@126.com']
rcpt_to = ['dada.chao.liu@gmail.com'] 
rcpt_to = ['dada.chao.liu@aliyun.com'] 
rcpt_to = ['dada.chao.liu@163.com'] 
rcpt_to = ['dada.chao.liu@qq.com'] 
rcpt_to = ['i@sendcloud.im','i@sendcloud.im','i@sendcloud.im','i@sendcloud.im','i@sendcloud.im','d@sendcloud.im','d@sendcloud.im','d@sendcloud.im','d@sendcloud.im','d@sendcloud.im','lianzimi123@gmail.com'] 
rcpt_to = ['i@sendcloud.im', 'd@sendcloud.im', 'bidaliu@senwoo.com']
rcpt_to = ['472588572@qq.com']
rcpt_to = ['dada.chao.liu@gmail.com']
rcpt_to = ['lianzimi123@163.com']
rcpt_to = ['i@sendcloud.im']
rcpt_to = ['d@sendcloud.im', 'jia.xia@kiimoo.com']

def send(subject, content, files):
    s = SMTP('%s:%d' % (HOST, PORT))
    s.set_debuglevel(True)
    if USE_SSL:
        s.starttls()
    s.login(category, passwd)

    msg = MIMEMultipart('mixed')
    msg['Subject'] = subject
    msg['sesame_open'] = '3de0be30478255bab0a4c78a5a664774'
    msg['From'] = mail_from
    msg['reply-to'] = 'dada.chao.liu@qq.com'
    msg['To'] = ', '.join(rcpt_to)

    x_header = {
        #"to": ["dada.chao.liu@qq.com", "d@sendcloud.im", "a@sendcloud.im", "44192354@qq.com"],
        #"sub": {
        #    "%content%": [content, ]
        #},
        "filters": {
            "subscription_tracking": { "settings": { "enable": "1" } },
            "open_tracking"        : { "settings": { "enable": "1" } },
            "click_tracking"       : { "settings": { "enable": "1" } }
        }
    }
    msg['X-SMTPAPI'] = Header(base64.b64encode(simplejson.dumps(x_header)))

    part = MIMEText(content, 'html', 'utf8')
    msg.attach(part)

    for f in files: 
        #param = {'charset':'gb18030', 'name':os.path.basename(f)}
        part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data 
        part.set_payload(open(f, 'rb').read()) 
        encoders.encode_base64(part) 

        #注意：此处basename要转换为gb2312编码，否则中文会有乱码。  
        #      unicode basename.encode('gb2312')  
        #      utf-8   basename.decode('utf-8').encode('gb2312')  
        filename = os.path.basename(f)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename.decode('utf8').encode('gb2312')) 
        msg.attach(part)

    a = s.sendmail('test@liubida.com', rcpt_to, msg.as_string())
    print 'aa', str(a)
    b = s.quit()
    print 'bb', str(b)

def read(filepath):
    IN = open(filepath, 'rb')
    header = IN.read(4)
    length = struct.unpack('>i', header)[0]
    
    content = IN.read()
    header = content[0:length]
    content = content[length:]
    return json.loads(header), content

if __name__ == '__main__':
    #header, content = read('/home/liubida/Desktop/32367.eml')

    files = []
    files = ['/home/liubida/git/about_python/cookbook/rawfile', '/home/liubida/Desktop/你好.jpg']
    files = ['/home/liubida/Desktop/11.eml', '/home/liubida/Desktop/22.eml']
    files = ['/home/liubida/git/about_python/cookbook/1.txt', '/home/liubida/git/about_python/cookbook/2.txt']
    files = []
    #files = ['/home/liubida/Desktop/新建你好.xls']

    content = 'liubida:   '
    #content += '主要问题在setheader里面的filename参数上因为我们数据库里都是utf8的，有些名字要从数据库直接生成'
    #content += '主要问题在setheader里面的filename参数上因为我们数据库里都是utf8的，有些名字要从数据库直接生成'
    #content += '主要问题在setheader里面的filename参数上因为我们数据库里都是utf8的，有些名字要从数据库直接生成'

    #content += "<a href='http://www.baidu.com'>123</a>"
    #content += "<a href='http://www.sohu.com'>456</a>"
    #content += '尊敬的用户, 尊敬的用户, 密保'
    #content += "<a href='http://www.sohu.com'>http://www.sohu.com</a>更换"
    #content += "<img src='http://www.sohu.jpg'/>"
    #content += "<a href='http://www.sohu.com'>IPHONE</a>更换"
    #content += "<a href='http://www.sohu.com'>IPad</a>更换"
    
    send('test', content, files)

