python获取外网IP并发邮件的实现方法

时间:2022-09-05 20:39:14

第一步:通过ip138来爬取外网ip

第二步:通过python的smtplib模块和email来发送邮件,具体用法去网上搜索,

下面是代码示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/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发邮件的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://ckl893.blog.51cto.com/8827818/1770030