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

2015/04/0814:47:54 1

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['From'] = self.fro
        if isinstance(self.subject,unicode):
            print 'unicode'
            self.subject = unicode(self.subject)
            msg['Subject'] = self.subject
        else:
            msg['Subject'] = self.subject
        '''
        self.subject = unicode(self.subject)
        msg['Subject'] = self.subject
        print msg['Subject']
        #os._exit(0)
        #msg['Subject'] = subject
        '''
        msg['To'] = COMMASPACE.join(self.to)
        msg['Date'] = formatdate(localtime=True)
        msg["Accept-Language"]="zh-CN"
        msg["Accept-Charset"]="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['SMTP'], self.server['Port'])
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(self.server['User'], self.server['Passwd'])
        smtp.sendmail(self.fro, self.to, msg.as_string())
        smtp.close()
    
if __name__=='__main__':
    server = {}
    server['SMTP'] = ConfigIni.read_config('D:\\Config.ini', 'Server', 'SMTP')
    server['User'] = ConfigIni.read_config('D:\\Config.ini', 'Server', 'User')
    server['Passwd'] = ConfigIni.read_config('D:\\Config.ini', 'Server', 'Passwd')
    server['Port'] = ConfigIni.read_config('D:\\Config.ini', 'Server', 'Port')
    fro = ("%s<"+ server['User'] + ">") % (Header(server['User'],'utf-8'),)
    to = ['411239339@qq.com']
    subject = u'邮件发送测试'
    text = 'mail content'
    files = ['d:\\1.html']   #支持列表发送附件
    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:
            traceback.print_exc()
            return False
        return True
def read_config(config_file_path, field, key):
    cf = ConfigParser.ConfigParser()
    try:
        cf.read(config_file_path)
        result = cf.get(field, key)
    except:
        traceback.print_exc()
        sys.exit(1)
    return result
def write_config(config_file_path, field, key, value):
    cf = ConfigParser.ConfigParser()
    try:
        cf.read(config_file_path)
        cf.set(field, key, value)
        with open(config_file_path,'w') as wfd:
            cf.write(wfd)
    except:
        traceback.print_exc()
        sys.exit(1)
    return True

配置文件示例Config.ini:

[Server]
SMTP =  smtp.gmail.com
User = chenqiin49@gmail.com
Passwd = *********
Port = 25

 

  • 微信扫码赞助
  • weinxin
  • 支付宝赞助
  • weinxin

发表评论

您必须才能发表评论!

目前评论:1   其中:访客  0   博主  0

    • 果子

      (微笑)