#!/usr/bin/env python#-*-coding:utf-8-*-# author:guojing# date:2014-10-23# Purpose: Send mail "send mail parameters: Subject, Recipient (multiple Use ', ' Split), CC (Multiple with ', ' split), content (can be file), attachments (multiple with ', ' split) ' ' __author__ = ' guojing ' import email,sys,osimport smtplibfrom email. Mimetext Import mimetextfrom Email. Mimemultipart Import mimemultipartfrom Email. Mimeimage Import mimeimagesender = ' [email protected]****.com ' smtpserver = ' smtpcloud.sohu.com ' #RECEIVERS = ' USERNAME = ' [email protected]****.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 (ope N (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.PA Th.basename (att) att = mimetext (open (ATT). Read (), ' base64 ', ' Utf-8 ') att["content-type"] = ' applicat Ion/octet-stream ' #将编码方式为utf-8 name, transcoding to Unicode, and then to GBK (otherwise, the attachment with the Chinese name will appear garbled) 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.SENDM Ail (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.arg V[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 ()
Reference:
http://blog.csdn.net/betry/article/details/6657429
Python Send mail