python發送附件的郵件

這裏是代碼,attachment函數不理解的,可以參考我的另一篇blog,http://blog.csdn.net/zmj_88888888/article/details/8725768

sendmail_mime.py

# -*- coding: utf8 -*-
import smtplib
from email import Utils,Encoders
import mimetypes,sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
#############
#要發給誰,這裏發給2個人
#mailto_list=["[email protected]","[email protected]"]
#####################
#設置服務器,用戶名、口令以及郵箱的後綴
mail_host="mail.xxxxx.com"
mail_user="[email protected]"
mail_pass="password"
mail_postfix="xxxxx.com"
######################
#構造添加附件的函數attachment
def attachment(filename):
    fd = open(filename,'rb')
    mimetype,mimeencoding = mimetypes.guess_type(filename)
    if mimetype or (mimeencoding is None):
        mimetype = 'application/octet-stream'
    maintype,subtype = mimetype.split('/')
    if maintype == 'text':
        retval = MIMEText(fd.read(),_subtype=subtype)
    else:
        retval = MIMEBase(maintype,subtype)
        retval.set_payload(fd.read())
        Encoders.encode_base64(retval)
    retval.add_header('Content-Disposition','attachment',filename = filename)
    fd.close()
    return retval

def send_mail(to_list,sub,content):
    '''
    to_list:發給誰
    sub:主題
    content:內容
    send_mail("[email protected]","sub","content")
    '''
    me=mail_user
    msg = MIMEMultipart()
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = to_list
    msg['Date'] = Utils.formatdate(localtime=1)
    msg['Message-ID'] = Utils.make_msgid()
    body = MIMEText(content)
    msg.attach(body)
    for filename in sys.argv[1:]:
        msg.attach(attachment(filename))
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, to_list, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False
if __name__ == '__main__':
    if send_mail("[email protected]","hello jason","do you know me!"):
        print "發送成功"
    else:
        print "發送失敗"


python sendmail_mime.py mail.txt mail.txt.tar.gz 
這裏發送了兩個附件mail.txt和mail.txt.tar.gz

我自己寫的,在windows上測試過,可以是用的,大家可以試試看,按照自己的需求來修改。

發佈了38 篇原創文章 · 獲贊 20 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章