python中关于发邮件的示例

发送邮件示例代码如下:

from WebUtils import ProperitiesLoad
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import os
class Sendmails():
    '''
      发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,
      如果有多个附件,可依次构造,最后利用smtplib.smtp发送。
    '''


    def __init__(self):
        mail=ProperitiesLoad.LodingProperities("../resources/Config.ini")
        self.sentfrom=mail.loading("mail","sentfrom")
        self.username=mail.loading("mail","username")
        self.password=mail.loading("mail","password")
        self.sentto=mail.loading("mail","sentto")
        self.smtphost=mail.loading("mail","smtphost")
        self.contect=mail.loading("mail","content")



    def send(self,attachementfilepath):
        #创建一个带附件的实例
        self.msg = MIMEMultipart()

        attachement=MIMEText(open(attachementfilepath,'rb').read(),'base64', 'gb2312')
        self.msg.add_header('Content-Disposition', 'attachment',   filename=os.path.basename(attachementfilepath))

        #加邮件头
        self.msg['to'] = self.sentto
        self.msg['from'] = self.sentfrom
        self.msg['subject'] = self.contect
        self.msg

        #发送邮件
        try:
            server = smtplib.SMTP()
            server.connect(self.smtphost)
            server.login(self.username,self.password)
            server.sendmail(self.msg['from'],self.msg['to'],self.msg.as_string())
            server.quit()
            print '发送成功'
        except Exception, e:
            print str(e)

 

posted @ 2017-01-18 23:25  浮尘~若梦  阅读(276)  评论(0编辑  收藏  举报