1. 程式人生 > >python傳送郵件,含有正文,附件,正文中含有圖片(圖片直接在郵件內容中顯示)

python傳送郵件,含有正文,附件,正文中含有圖片(圖片直接在郵件內容中顯示)

#!/usr/bin/python
#coding:utf-8 


import smtplib
import mimetypes
from email.Header import Header 
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage


mailto_list=["**********@qq.com"]
mail_host="smtp.qq.com"
mail_user="909098131"
mail_pass="shijing50779wen"
mail_postfix="qq.com"

def send_mail(to_list,sub,content):
    
    #建立一個帶附件的例項
    msg = MIMEMultipart('alternative')
    msg['Subject'] = Header("subject",'utf-8')
    
    #html格式構造


    html =  """
    <html> 
      <head></head> 
      <body> 
          <p>
            %s
           <br><img src="cid:image1"></br> 
          </p>
      </body> 
    </html> 
    """ %(content)
    htm = MIMEText(html,'html','utf-8') 
    msg.attach(htm)
    
    
    
    #正文
#     txt1=MIMEText(content,_subtype='html',_charset='gb2312')
#     msg.attach(txt1)
     #新增附件
    att1 = MIMEText(open('.\\123.txt', 'rb').read(), 'base64', 'gb2312')
    att1["Content-Type"] = 'application/octet-stream'
    att1["Content-Disposition"] = \
    'attachment; filename="123.txt"'#這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
    msg.attach(att1)
    
    att2 = MIMEText(open('.\\abc.jpg', 'rb').read(), 'base64', 'gb2312')
    att2["Content-Type"] = 'application/octet-stream'
    att2["Content-Disposition"] = \
    'attachment; filename="abc.jpg"'#這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
    msg.attach(att2)
#     新增圖片
     
    file1 = ".\\abc.jpg"
    fp = open(file1,'rb')
    image = MIMEImage(fp.read())
    fp.close()
    image.add_header('Content-ID','<image1>')
    msg.attach(image)
    




    me=mail_user+"<"+mail_user+"@"+mail_postfix+">"
#     msg = MIMEText(content)
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(to_list)
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        print "connected"
        s.ehlo()
        s.starttls()
        s.ehlo
        s.login(mail_user,mail_pass)
        print "logined"
        s.sendmail(me, to_list, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False


if send_mail(mailto_list,"[RCA_FTP_Download]","TTTTTTTTTTTEEEEEEEEEESSSSSSSSSSSSSSSTTTTTTTTTTTT"):
print "send success"
else:
print "send failed"