在我們的工作中爆办,會(huì)有諸如這種需求:
Q1:我的測試用例實(shí)現(xiàn)自動(dòng)構(gòu)建了威恼,怎么在構(gòu)建完讓程序通知我結(jié)果竹祷?
Q2:我的監(jiān)控程序部署完了擅编,怎么能讓我在出問題時(shí)及時(shí)得到消息攀细?
以上的問題相信大家都有了答案:那就是通過郵件和短信。下面我們就來看看怎么用Python實(shí)現(xiàn)發(fā)送郵件爱态,本人已經(jīng)試驗(yàn)多次并一直在使用谭贪,源碼附上:
#coding=utf-8
import smtplib
import string
from email.mime.text import MIMEText
import base64
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
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)
? ? ? ? self.content = base64.encodestring(self.content)
? ? ? ? msg = "From:%s\nTo:%s\nSubject:%s\nContent-Type:text/html;charset=UTF-8\nContent-Transfer-Encoding:base64\n\n%s" % (self.sender, self.receiver, self.subject, self.content)
??????? smtp.sendmail(self.sender, self.receiver, msg)
??????? smtp.close()
??? def __del__(self):
??????? print "Finish sending mails !"
# Main
if __name__ == "__main__":
# 獲取郵件主題
mailSubject = sys.argv[1]
# 獲取郵件內(nèi)容
mailContent = sys.argv[2]
# 獲取收件人list
receiverList = sys.argv[3]
receiverList = string.splitfields(receiverList, ",") # 收取郵件的郵箱地址,用逗號(hào)隔開
mail = Mailsender()
mail.setSmtpServer("smtp.xxxx.qq.com") # Smtp Server地址
mail.setSender('xxxxxxxxxxxx@qq.com', "xxxxxx") #發(fā)送郵件郵箱的用戶名和密碼
mail.setReceiver(receiverList)
mail.setSubject(mailSubject)
mail.setContent(mailContent)
mail.sendMail()