前些時間,論壇上有人討論怎麼用python發送需要認證的郵件,我在我的FreeBSD在telnet到163的的smtp伺服器,分析了一下,就用python寫個了發送郵件的程式,感覺有點粗糙,但還算能工作。
import smtplib, base64
class SimpleSendMail:
def __init__(self, smtp_server, from_addr, to_addr, user, passwd):
self.from_addr = from_addr
self.to_addr = to_addr
self.username = base64.encodestring(user)
self.password = base64.encodestring(passwd)
self.mailserver = smtp_server
def send(self, msg):
server = smtplib.SMTP(self.mailserver)
server.set_debuglevel(1)
server.docmd("EHLO server")
server.docmd("AUTH LOGIN")
server.send(self.username)
server.getreply()
server.send(self.password)
server.getreply()
server.docmd("MAIL FROM:" + self.from_addr)
server.docmd("RCPT TO:" + self.to_addr)
server.docmd("DATA")
server.send(msg)
server.send("/r/n./r/n")
server.getreply()
#server.reset()
server.quit()
if __name__ == '__main__':
test = SimpleSendMail("smtp.163.com", "xxxx@163.com", "xxxx@sina.com", "xxxx", "xxxxxxxxx")
test.send("heheh/r/na test from python send mail")