# -*- coding: utf-8 -*-
"""
Created on Wed Feb 20 16:08:17 2019

@author: zhouyujiang

发送有附件的 邮件

"""




import os
import smtplib
# For guessing MIME type based on file name extension
import mimetypes
from email import encoders
#from email.message import Message
#from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
#from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

#COMMASPACE = ', '


def send_file_email(file_path, data_str, email_group=['zhouyujiang@csm.com.cn'],
                    email_msg_body_str=None,
                    title_str=None,
                    cc_group=['zhouyujiang@csm.com.cn', 'hanye@csm.com.cn'],sender = None):
    directory = file_path
    # Create the enclosing (outer) message
    if email_msg_body_str == None:
        email_msg_body = '''肖老师，李赞，问好:\n    附件是我们爬虫和外部采购短视频数据源获取的与任正非BBC采访有关的短视频数据，其中，
      《任正非BBC采访相关短视频数据_{data_str}.csv》是视频明细
      《任正非BBC采访相关短视频数据summary_{data_str}.csv》是视频结果汇总 
       在summary附件中，sum_net_inc_play_count是当日新增播放量的和，sum_playcount 是视频累积播放量和
       注：梨视频（pearvideo）平台没有播放量
    '''.format(data_str=data_str)
    else:
        email_msg_body = email_msg_body_str
    outer = MIMEMultipart()
    if title_str == None:
        title = '任正非BBC采访相关短视频数据-' + data_str
    else:
        title = title_str
    outer['Subject'] = title
 
    outer['To'] = ','.join(email_group)
    outer['Cc'] = ','.join(cc_group)
    if not sender:
        outer['From'] = 'zhouyujiang@csm.com.cn'
    else:
        outer['From'] = sender
    csm_mail_service = 'mail.csm.com.cn'
    outer.attach(MIMEText(email_msg_body))

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
#        if maintype == 'text':
##            with open(path,encoding='utf-8') as fp:
###                 Note: we should handle calculating the charset
##                msg = MIMEText(fp.read(), _subtype=subtype)
#            continue
        if maintype == 'image':
#            with open(path, 'rb') as fp:
#                msg = MIMEImage(fp.read(), _subtype=subtype)
            continue 
        elif maintype == 'audio':
#            with open(path, 'rb') as fp:
#                msg = MIMEAudio(fp.read(), _subtype=subtype)
            continue 
        else:
            with open(path, 'rb') as fp:
                msg = MIMEBase(maintype, subtype,charset='gb18030')
                msg.set_payload(fp.read())
            # Encode the payload using Base64
            encoders.encode_base64(msg)
        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        outer.attach(msg)

    # Now send or store the message
#    composed = outer.as_string()
    server = smtplib.SMTP(host=csm_mail_service)
    server.send_message(outer)
    server.quit()



if __name__ == '__main__':
    send_file_email(file_path=r'D:\code\test',
                    data_str='2019-02-21',
                    cc_group=[],
                    sender='lizhiwei@csm.com.cn',
                    email_group=['lizhiwei@csm.com.cn'])


 
 




