---
title: "python mail"
author: "liseor"
date: "2011-04-27T13:18:41Z"
tags: [".net", "ASP", "ASP.net", "OS", "Python"]
categories: ["编程语言"]
slug: "python-mail"
draft: false
lastmod: "2011-04-27T13:18:41Z"
id: 1019652
url: "https://liseor.iteye.com/blog/1019652"
---

```
#coding=gbk
import os
import re
import urllib2
import smtplib
import time
from time import localtime,strftime
#################参数设置######################
#邮箱用户名
username = ""
#邮箱密码
password = ""
#smtp服务器
mailserver = ""
#smtp服务器端口
port = "25"
#执行间隔,单位秒
interval = 180
#发件地址
from_addr = ""
#收件地址
to_addr = ""
#是否打开debug(0关闭,1打开)
debuglevel = 0
################################################

running = True
hostname = os.environ['COMPUTERNAME']

lastip = "0.0.0.0"
while running:
    #获得公网IP
    pagereturn = urllib2.urlopen("http://www.net.cn/static/customercare/yourIP.asp").read()
    #print pagereturn
    #截取IP地址
    obj = re.search('(\d+)\.(\d+)\.(\d+)\.(\d+)',pagereturn)
    #print obj
    ip = obj.group(0)
    print "程序运行中,主机当前广域网IP为:" + ip
    #比较当前IP与之前IP是否相同,如不同则发送邮件
    if ip <> lastip:
        lastip = ip
        now = strftime("%Y-%m-%d %H:%M:%S", localtime())
        subject = now + " 主机: " + hostname + " 当前IP地址为: " + ip
        content = now + " 主机: " + hostname + " 当前IP地址为: " + ip
        
        smtp = smtplib.SMTP()
        smtp.set_debuglevel(debuglevel)
        smtp.connect(mailserver, port)
        smtp.login(username, password)
        smtp.sendmail(from_addr, to_addr, 'From: ' + from_addr + '\r\nTo: ' + to_addr + '\r\nSubject: ' + subject + '\r\n\r\n' + content)    
        smtp.quit()
        
    time.sleep(interval)
```