在我们的工作中,会有诸如这种需求:
Q1:我的测试用例实现自动构建了,怎么在构建完让程序通知我结果?
Q2:我的监控程序部署完了,怎么能让我在出问题时及时得到消息?
以上的问题相信大家都有了答案:那就是通过邮件和短信。下面我们就来看看怎么用Python实现发送邮件,本人已经试验多次并一直在使用,源码附上:
#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]
# 获取邮件内容
mailContent = sys.argv[2]
# 获取收件人list
receiverList = sys.argv[3]
receiverList = string.splitfields(receiverList, ",") # 收取邮件的邮箱地址,用逗号隔开
mail = Mailsender()
mail.setSmtpServer("smtp.xxxx.qq.com") # Smtp Server地址
mail.setSender('xxxxxxxxxxxx@qq.com', "xxxxxx") #发送邮件邮箱的用户名和密码
mail.setReceiver(receiverList)
mail.setSubject(mailSubject)
mail.setContent(mailContent)
mail.sendMail()