python :简单邮件发送

By | 2012/09/29

使用smtplib来实现邮件发送

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 !"

下面是一个测试方法:

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()

Leave a Reply

Your email address will not be published. Required fields are marked *