Regular mail
[[email protected] checksalt]# cat python_email.py #!/usr/bin/python# -*- CODING: UTF-8 -*-IMPORT SYSDEF SMTP (title,file): import Smtplib from email.mime.text import mimetext from email.header import header with open (file, ' r ') as f: content = f.read () #加邮件头 msg=mimetext (content, ' plain ', ' utf-8 ') to_list=[' [email protected] ', [email protected]] msg[' from '] = ' [email protected] ' msg[' subject '] = title #发送邮件 try: server = Smtplib. SMTP () &nbsP; server.connect (' smtp.exmail.qq.com ') server.login (' [email protected] ', ' xxxxx ') #XXX为用户名, xxxxx for password server.sendmail (msg[' from '],to_list,msg.as_string ()) server.quit () print ' send Success ' Except exception, e: print str (e) If __name__ == ' __main__ ': smtp (sys.argv[1],sys.argv[2]) [[email protected] checksalt]#
Mail with Attachments
#!/usr/bin/python# -*- coding: utf-8 -*-import smtplibimport datetimefrom Email.mime.text import mimetextfrom email.mime.multipart import mimemultipartfrom email.header import headeroneday = datetime.timedelta (days=1) today = Datetime.date.today () yesterday = datetime.date.today () - onedayyesterday_time = datetime.datetime.strftime (yesterday, '%y-%m-%d ') sender = ' [email protected] ' # #发送者receivers = [' [email protected] ', ' [email protected] '] # Receive mail, can be set as your QQ mailbox or other mailbox # Create an instance with an attachment Message = mimemultipart () message[' from '] = header (" SOURCE ", ' Utf-8 ') message[' to '] = header (" purpose ", ' utf-8 ') subject = ' xxxx log ' message[' Subject '] = header (subject, ' utf-8 ') #邮件正文内容message. attach (mimetext ('%sxxxx log info, See attachment!! '% yesterday_time, 'Plain ', ' utf-8 ')) # construct attachment, transfer test.txt file in current directory try: file = ' file.log.%s ' % yesterday_time print file att1 = mimetext (open (file, ' RB '). read (), ' base64 ', ' Utf-8 ') att1[" Content-type "] = ' application/octet-stream ' # here filename can be arbitrarily written, what name to write, What name is displayed in the message att1["content-disposition"] = "attachment; filename= extprofile.log.%s " %yesterday_time message.attach (att1) Smtpobj = smtplib. SMTP () smtpobj.connect (' smtp.exmail.qq.com ') smtpobj.login (' [ email protected] ', ' xxxxxxxxxxxx ') # xxx for username, xxxxx for password Smtpobj.sendmail (sender, receivers, message.as_string ()) smtpobj.quit () print "mail sent successfully" except smtplib. Smtpexception as e : print str (e) print "error: cannot send mail" except ioerror as e: print str (e) print "error: Cannot send mail"
This article is from the "struggle bar" blog, please be sure to keep this source http://lvnian.blog.51cto.com/7155281/1854515
Python E-mail