导航

python :简单邮件发送

Posted on 2012-09-29 10:16  moose  阅读(246)  评论(0编辑  收藏  举报

PS: util文件夹中要自行创建__init__.py文件,内容可以为空

#\util\MailSenderHelp.py
import smtplib
from email.mime.text import MIMEText
import base64

class Mailsender():
    def __init__(self):
        print "I am sending the mails..."
        
    def setSmtpServer(self, smtpServer):
        self.smtpserver = smtpServer
        
    def setSender(self, sender, password):
        self.sender = sender
        self.password = password
        
    def setReceiver(self,receiver):       
        self.receiver = receiver
    
    def setSubject(self, subject):
        self.subject = subject
    
    def setContent(self,content):
        self.content = content
        
    def sendMail(self):
        smtp = smtplib.SMTP()
        smtp.connect(self.smtpserver, 25)
        smtp.login(self.sender, self.password)
        
#        msg = MIMEText(self.content)
#        msg['From'] = self.sender
#        msg['To'] = ",".join(self.receiver)
#        msg['Subject'] = self.subject
        
        self.content = base64.b64encode(self.content)
        msg = "From:%s\nTo:%s\nSubject:%s\nContent-Type:text/html\nContent-Transfer-Encoding:base64\n\n%s"%(self.sender, self.receiver, self.subject,self.content)
        
#        smtp.sendmail(self.sender, self.receiver, msg.as_string())
        smtp.sendmail(self.sender, self.receiver, msg)
        smtp.close()
        
    def __del__(self):
        print "Finish sending mails !"

  


 


 

#mail.py

from util.MailSenderHelp import Mailsender

if __name__ == "__main__":
    receiverList = ["XXX@qq.com","XXX@qq.com","XXX@yahoo.com.cn"]
    
    mail = Mailsender()
    
    mail.setSmtpServer("smtp.126.com")
    mail.setSender("XXX@126.com", "XXXXXX")
    mail.setReceiver(receiverList)
    mail.setSubject("This is a test mail")
    mail.setContent("I have no content,do you know")
    
    mail.sendMail()