python 發郵件。可以帶附件列表

python 發郵件。可以帶附件列表


#發送郵件腳本
def send_mail(to, sub, content, from_email, mail_pass, filelist = []):
    '''
    to:發給誰
    sub:主題
    content:內容
    from_email:登錄郵箱
    mail_pass:登錄密碼
    filelist:附件列表,文件路徑
    send_mail("[email protected]","subject","content","[email protected]","xxxxxx")
    '''

    mail_postfix = from_email.split('@')[1]
    mail_host="smtp.%s" % (mail_postfix,)
    mail_user= from_email.split('@')[0]

    me=mail_user+"<"+mail_user+"@"+mail_postfix+">"

    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = sub.encode('gbk')
    msgRoot['Form'] = me
    msgRoot['To'] = to
    msgRoot.preamble = 'this is a multi-part message IN MIME format'

    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    msgText = MIMEText(content, 'html','gbk')
    msgAlternative.attach(msgText)
    for onefile in filelist:
        att = MIMEText(open(onefile,'rb').read(),'base64','gb2312')
        att["Content-Type"] = 'application/octet-stream'
        att["Content-Disposition"] = 'attachment;filename=%s' % onefile
        msgAlternative.attach(att)

    message = msgRoot.as_string()
    try:
        s = smtplib.SMTP()
        try:
            s.connect(mail_host)
        except Exception,e:
            print str(e)
        s.starttls()
        s.login(mail_user,mail_pass)
        s.sendmail(me, to, message)
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章