Python發送郵件

jopen 10年前發布 | 19K 次閱讀 Python Python開發

使用Python發送郵件的demo,可以帶附件。

#!/usr/bin/env python

-- coding: utf-8 --

Author: guojing

Date: 2014-10-23

Purpose: 發送郵件

''' 發送郵件 Parameters:主題、接受者(多個用','分割)、抄送(多個用','分割)、內容(可以是文件)、附件(多個用','分割) '''

author = 'guojing'

import email,sys,os import smtplib from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEImage import MIMEImage

SENDER = 'username@**.com' SMTPSERVER = 'smtpcloud.sohu.com'

RECEIVERS = ''

USERNAME = 'username@.com' APIKEY = '**'

def sendMail(subject, receivers, cc, content, atts): msg = MIMEMultipart('related') msg['Subject'] = unicode(subject, "UTF-8") msg['From'] = SENDER msg['To'] = receivers msg['Cc'] = cc

#郵件內容
if os.path.isfile(content):
    if(content.split('.')[-1]=='html'):
        cont = MIMEText(open(content).read(),'html','utf-8')
    else:
        cont = MIMEText(open(content).read(),'plain','utf-8')
else:
    cont = MIMEText(content, 'plain','utf-8')
msg.attach(cont)

#構造附件
if atts != -1 and atts != '':
    for att in atts.split(','):
        os.path.isfile(att)
        name = os.path.basename(att)
        att = MIMEText(open(att).read(), 'base64', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        #將編碼方式為utf-8的name,轉碼為unicode,然后再轉成gbk(否則,附件帶中文名的話會出現亂碼)
        att["Content-Disposition"] = 'attachment; filename=%s' % name.decode('utf-8').encode('gbk')
        msg.attach(att)

smtp = smtplib.SMTP()
smtp.connect(SMTPSERVER)
smtp.login(USERNAME, APIKEY)
for recev in receivers.split(','):
    smtp.sendmail(SENDER,recev, msg.as_string())
for c in cc.split(','):
    smtp.sendmail(SENDER,c, msg.as_string())
smtp.quit()

def main(): print "start send mail[sendmail.py]" subject = sys.argv[1] receivers = sys.argv[2]

#cc = sys.argv[3]
leng = len(sys.argv)
if leng == 3:
    cc = ""
    content = ""
    atts = -1
elif leng == 4:
    print "The parameters is not currect!"
    sys.exit(0)
elif leng == 5:
    cc = sys.argv[3]
    content = sys.argv[4]
    atts = -1
elif leng == 6:
    cc = sys.argv[3]
    content = sys.argv[4]
    atts = sys.argv[5]
sendMail(subject, receivers, cc, content, atts)
print "finish send mail[sendmail.py]"

if name=='main': main()</pre></span>參考:
http://blog.csdn.net/betry/article/details/6657429

來自:http://my.oschina.net/u/553773/blog/349327

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!