python发送邮件模块(支持读写ini配置文件)

1、支持ini配置文件读写 2、支持中文编码邮件 邮件发送主体部分SendMail.py:#!/usr/bin/env python # -*- coding: UTF-8 -*- from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText   from email.utils import COMMASPACE,formatdate from email import encoders from email.header import Header   import os import ConfigIni class class_smtp():     def __init__(self,server, fro, to, subject, text, files):         self.server = server         self.fro = fro         self.to = to         self.subject = subject         self.text = text         self.files = files     def send_mail(self):         assert type(self.server) == dict         assert type(self.to) == list         assert type(self.files) == list         msg = MIMEMultipart()         msg = self.fro         if isinstance(self.subject,unicode):             print 'unicode'             self.subject = unicode(self.subject)             msg = self.subject         else:             msg = self.subject         '''         self.subject = unicode(self.subject)         msg = self.subject         print msg         #os._exit(0)         #msg = subject         '''         msg = COMMASPACE.join(self.to)         msg = formatdate(localtime=True)         msg="zh-CN"         msg="ISO-8859-1,utf-8"         msg.attach(MIMEText(self.text))         if len(self.files):             print "Come here. ",len(self.files)             for f in self.files:                 part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data                 part.set_payload(open(f, 'rb').read())                 encoders.encode_base64(part)                 part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))                 msg.attach(part)         else:             print 'Attachment list is empty.'         import smtplib         smtp = smtplib.SMTP(self.server, self.server)         smtp.ehlo()         smtp.starttls()         smtp.ehlo()         smtp.login(self.server, self.server)         smtp.sendmail(self.fro, self.to, msg.as_string())         smtp.close()      if __name__=='__main__':     server = {}     server = ConfigIni.read_config('D:\\Config.ini', 'Server', 'SMTP')     server = ConfigIni.read_config('D:\\Config.ini', 'Server', 'User')     server = ConfigIni.read_config('D:\\Config.ini', 'Server', 'Passwd')     server = ConfigIni.read_config('D:\\Config.ini', 'Server', 'Port')     fro = ("%s<"+ server + ">") % (Header(server,'utf-8'),)     to =      subject = u'邮件发送测试'     text = 'mail content'     files =    #支持列表发送附件     smtp = class_smtp(server, fro, to, subject, text, files)     smtp.send_mail() 配置文件读写ConfigIni.py:__author__ = 'Chenqin' import ConfigParser import traceback import sys class ClassConfig:     def __init__(self, path):         self.path = path         self.cf = ConfigParser.ConfigParser()         self.cf.read(self.path)     def get(self, field, key):         result = ""         try:             result = self.cf.get(field, key)         except:             result = ""         return result     def set(self, filed, key, value):         try:             self.cf.set(field, key, value)             with open(self.path,'w') as wfd:                 cf.write(wfd)         except:...
阅读全文

python时间函数和常用格式化

使用之前import: import time,datetime 下面的函数在python2.7里可以正常运行,但python2.4可能不支持某些方法。比如python2.4.3中报错: AttributeError: type object 'datetime.datetime' has no attribute 'strptime'   格式化当前时间则为: 首选:time.strftime('%Y-%m-%d %H:%M:%S') 其次:datetime.datetime.strftime(datetime.d atetime.now(), '%Y-%m-%d %H:%M:%S') 最后:str(datetime.datetime.now())   获取日期差: oneday = datetime.timedelta(days=1) today = datetime.date.today() yesterday  = datetime.date.today() - oneday tomorrow = datetime.date.today() + oneday 获取今天零点的时间: today_zero_time = datetime.datetime.strftime(today, '%Y-%m-%d %H:%M:%S') print today_zero_time 2013-05-21 00:00:00   获取时间差: oneday = datetime.timedelta(days=1) today_time = datetime.datetime.now() yesterday_time = datetime.datetime.now() - oneday tomorrow_time  = datetime.datetime.now() + oneday 注意时间是浮点数,带毫秒。如下: print tomorrow_time 2013-05-22 10:34:43.873844 那么要获取当前时间,需要格式化一下: oneday = datetime.timedelta(days=1) today_time = datetime.datetime.now() yesterday_time = datetime.datetime.now() - oneday tomorrow_time  = datetime.datetime.now() + oneday tomorrow_time = datetime.datetime.strftime(today_time, '%Y-%m-%d %H:%M:%S') 运行结果如下所示: print tomorrow_time 2013-05-21 10:34:43   获取上个月最后一天: last_month_last_day = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)    字符串格式转秒数:...
阅读全文

Python与其他语言结合的参数转换函数PyArg_ParseTuple()

The PyArg_ParseTuple() function is declared as follows: int PyArg_ParseTuple(PyObject *arg, char *format, ...); The arg argument must be a tuple object containing an argument list passed from Python to a C function. The format argument must be a format string, whose syntax is explained below. The remaining arguments must be addresses of variables whose type is determined by the format string. For the conversion to succeed, the arg object must match the format and the format must be exhausted. Note that while PyArg_ParseTuple() checks that the Python arguments have the required types, it cannot check the validity of the addresses...
阅读全文

python获取系统信息

import platform import os import sys import platform def machine():     """Return type of machine."""     if os.name == 'nt' and sys.version_info < (2,7):         return os.environ.get("PROCESSOR_ARCHITEW6432",                os.environ.get('PROCESSOR_ARCHITECTURE', ''))     else:         return platform.machine() def os_bits(machine=machine()):     """Return bitness of operating system, or None if unknown."""     machine2bits = {'AMD64': 64, 'x86_64': 64, 'i386': 32, 'x86': 32}     return machine2bits.get(machine, None) if __name__ == '__main__':     print(platform.machine())     print(platform.node())     print(platform.platform(True))     print(platform.system())     print(platform.uname())     print(platform.architecture())     print(platform.platform() + ' ' + platform.architecture())     print (os_bits())   输入内容可能如下:i686localhost.localdomainLinux-3.12.11-201.nk.1.i686.PAE-i686-with-redhat-6.0Linux('Linux', 'localhost.localdomain', '3.12.11-201.nk.1.i686.PAE', '#1 SMP Sun Jun 8 19:40:47 CST 2014', 'i686', 'i686')32bitLinux-3.12.11-201.nk.1.i686.PAE-i686-with-redhat-6.0 32bitNone
阅读全文

python学习之:socket模块初探

import socket import sys import zlib def tcpSend(sock):     print 'send' def tcpConnect(svrIP,svrHost):     try:         clisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)         clisock.connect((svrIP, svrHost))         return clisock     except socket.error, arg:         (errno, err_msg) = arg         print "Connect server failed: %s, errno=%d" % (err_msg, errno) if __name__ == "__main__":     sock = tcpConnect('192.168.46.142',37527)     if sock <> -1:         tcpSend(sock)
阅读全文