#由於今年要開展郵件測試,所以研究一下郵件的東東,順便學習一下python,始終認為解釋性語言是自動化測試的利器,
但是由於一般指令碼語言都存在物件導向不易的缺陷,不容易在大的項目中使用,根據初步學習python具備良好的物件導向特性,
而且根據學習,發現這門語言的確相當好玩,很吸引我,特抄錄了一段代碼驗證了一下,測試通過,發帖如下。
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib
def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText):
strFrom = fromAdd
strTo = ', '.join(toAdd)
server = authInfo.get('server')
user = authInfo.get('user')
passwd = authInfo.get('password')
if not (server and user and passwd) :
print 'incomplete login info, exit now'
return
# 設定root資訊
msgRoot = email.MIMEMultipart.MIMEMultipart('related')
msgRoot['Subject'] = subject
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
#設定純文字資訊
# msgText = MIMEText(plainText, 'plain', 'utf-8')
# msgAlternative.attach(msgText)
#設定HTML資訊
msgText = email.MIMEText.MIMEText(htmlText, 'html', 'utf-8')
msgAlternative.attach(msgText)
#設定內建圖片資訊
# fp = open('test.jpg', 'rb')
# msgImage = MIMEImage(fp.read())
# fp.close()
# msgImage.add_header('Content-ID', '<image1>')
# msgRoot.attach(msgImage)
#發送郵件
smtp = smtplib.SMTP()
#設定調試層級,依情況而定
smtp.set_debuglevel(1)
smtp.connect(server)
smtp.login(user, passwd)
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
# smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
return
if __name__ == '__main__' :
authInfo = {}
authInfo['server'] = 'smtp.163.com'
authInfo['user'] = '****@163.com'
authInfo['password'] = '*****'//寫上你的密碼
fromAdd = '****@163.com'
toAdd = ['****@163.com','elbert.chenh@gamil.com']
subject = 'hello ,boy title'
plainText = '這裡是普通文本'
htmlText = '<B>HTML文本</B>'
sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText)