下面小編就為大家帶來一篇python取得外網IP並發郵件的實作方法。小編覺得蠻不錯的,現在就分享給大家,也給大家做個參考。一起跟著小編過來看看吧
第一步:透過ip138來爬取外網ip
##第二步:透過python的smtplib模組和email來發送郵件,具體用法去網上搜索,
下面是程式碼範例:
#!/usr/bin/env python #coding:utf-8 import urllib2 import re import smtplib from email.MIMEText import MIMEText from email.Header import Header ########################################## #get ip address url = "http://1212.ip138.com/ic.asp" url_op = urllib2.urlopen(url) url_content = url_op.read() ip_content = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',url_content) ipcode = ''.join(ip_content) ################################################# # Setting mail-server, etc mail_host="smtp.sina.com" mail_user="ckl" mail_pass="woXXXX" mail_postfix="sina.com" ################################################# def send_mail(to_list, sub, content): me = mail_user + "<" + mail_user + "@" + mail_postfix + ">" msg = MIMEText(content) msg['Subject'] = sub msg['From'] = me msg['To'] = ";".join(to_list) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user, mail_pass) s.sendmail(me, to_list, msg.as_string()) s.close() return True except Exception, e: print str(e) return False ################################################# # Main process if __name__ == "__main__": mailto_list=["41145XXXX@qq.com"] if send_mail(mailto_list, "你的最新IP地址", ipcode): print "Send success!" else: print "Send failed!"
以上是python實作取得外網IP並發郵件的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!