python smtp實例

先來個大栗子:

# Description: Simple smtp test
# Author: xumesang
# Date: 2016-11-7

import smtplib
from email.mime.text import MIMEText
mailto_list = "[email protected]"
mail_host = "smtp.163.com"
mail_user = "yyy"
mail_password = "zzz"
mail_postfix = "163.com"

def send_mail(to_list, sub, content):
	me = "zm" + "<" + mail_user + "@" + mail_postfix + ">"
	msg = MIMEText(content, _subtype = 'plain', _charset = 'gb2312')
	msg['Subject'] = sub
	msg['From'] = me
	msg['to'] = ";".join(to_list)
	try:
		server = smtplib.SMTP()
		server.connect(mail_host)
		server.login(mail_user, mail_password)
		server.sendmail(me, to_list, msg.as_string())
		server.close()
		return True
	except Exception, e:
		print str(e)
		return False

if __name__ == '__main__':
	if send_mail(mailto_list, "zm", "Hello M, Please contact me immediately when you see this email."):
		print "Success"
	else:
		print "Fail"
本實例已經經過測試,只需填寫適當郵件參數即可。

在測試的過程中如果遇到問題,可以根據下面網易提供的返回結果判斷錯誤原因:

http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html


發佈了151 篇原創文章 · 獲贊 30 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章