一个月前写了个脚本,打算由Linux的cron触发,每天定时往指定的邮箱中发送一张照片。
PYTHON:
-
#!/usr/bin/python
-
# --*-- coding: utf-8 --*--
-
# 2009年 04月 21日 星期二 00:28:42 CST
-
from email.MIMEMultipart import MIMEMultipart
-
from email.MIMEText import MIMEText
-
from email.MIMEImage import MIMEImage
-
import email.Utils
-
import smtplib
-
import datetime
-
import locale
-
import os
-
import getpass
-
import Image
-
import tempfile
-
import sys
-
-
# 邮件发送者的电邮地址
-
fromAddr = 'my_address@gmail.com'
-
# 所有要发送到的电邮地址
-
toAddrs = ['target_address_1@yahoo.com.cn','target_address_2@gmail.com']
-
# 保存已发送图片信息的日志文件
-
logHistory = '/home/lenin/scripts/data/sweethome/history.log'
-
# 程序运行时输出的日志
-
logApp = '/home/lenin/scripts/data/sweethome/app.log'
-
# 图片存放文件夹
-
basePath = '/home/lenin/scripts/data/sweethome/images'
-
# 保存目录中所有可发送的图片文件路径的列表
-
files = []
-
-
# 发送邮件的函数
-
def SendMail(fromAddr, toAddrs, filePath):
-
Shout('开始发送图片……')
-
# 创建邮件
-
mail = MIMEMultipart()
-
mail['To'] = ','.join(toAddrs)
-
mail['From'] = fromAddr
-
mail['Subject'] = '每日一图'+'('+datetime.datetime.strftime(datetime.datetime.now(), '%c')+')'
-
mail['Date'] = email.Utils.formatdate(localtime=1)
-
# 创建邮件内容
-
mailContent = '''
-
hi,
-
sweethome.py每天由Linux操作系统的cron后台守护进程在指定时间触发,每次自动发送一张指定目录中的图片。
-
sweethome.py会自动检测图片的大小,并将分辨率较大的图片同比缩放至800像素以内(以最长边为准),然后再行发送,目的是减小图片大小以适应天朝糟糕的网速。
-
明儿见
-
'''
-
body = MIMEText(mailContent, 'plain', 'utf-8')
-
mail.attach(body)
-
# 创建附件
-
fp = open(filePath, 'rb')
-
try:
-
mailImage = MIMEImage(fp.read())
-
except IOError:
-
Shout('读取图片文件“'+filePath+'”失败,邮件无法发送!')
-
sys.exit()
-
else:
-
mailImage.add_header('Content-disposition', 'attachment', filename=datetime.datetime.now().__str__().replace(' ', '_')+'.jpg')
-
finally:
-
fp.close()
-
mail.attach(mailImage)
-
# 发送
-
svr = smtplib.SMTP('smtp.gmail.com', '587')
-
svr.starttls()
-
svr.login('my_address', getpass.getpass('Input the password:'))
-
svr.sendmail(fromAddr, toAddrs, mail.as_string())
-
svr.quit()
-
Shout('图片发送成功!')
-
-
# 遍历basePath,将所有可发送的图片文件的路径保存到files列表中
-
def WalkDir(basePath):
-
if os.path.isdir(basePath):
-
for item in os.listdir(basePath):
-
WalkDir(basePath+os.sep+item)
-
else:
-
if ['jpg', 'png', 'gif', 'bmp', 'tif'].count(basePath[-3:].lower()) == 1:
-
try:
-
files.append(basePath)
-
except NameError:
-
Shout('存放图片文件路径的list变量“files”未定义!')
-
sys.exit()
-
-
# 检查指定图片文件的路径在logHistory日志中是否已存在
-
def HasNotBeenSent(file):
-
if not os.path.exists(file) or not os.path.isfile(file) or not os.path.exists(logHistory):
-
return True
-
fp = open(logHistory, 'rb')
-
try:
-
oldFiles = fp.readlines()
-
except IOError:
-
print datetime.datetime.now().__str__()+':读日志失败,检查日志文件“'+logHistory+'”是否可读或存在!'
-
sys.exit()
-
else:
-
for oldFile in oldFiles:
-
if oldFile.endswith(file):
-
return False
-
return True
-
finally:
-
fp.close()
-
-
# 记录日志
-
def AppendLog(log, info):
-
fp = open(log, 'a')
-
try:
-
fp.write(info + '\r\n')
-
except IOError:
-
print datetime.datetime.now().__str__()+':写日志失败,检查日志文件“'+log+'”是否可写!'
-
finally:
-
fp.close()
-
-
# 记录日志并输出到终端
-
def Shout(msg):
-
print datetime.datetime.now().__str__()+':'+msg
-
AppendLog(logApp, datetime.datetime.now().__str__()+'|'+msg)
-
-
if __name__=='__main__':
-
# 设置区域,否则下面的日期格式化字符串是英文
-
locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')
-
# 递归遍历所有图片
-
WalkDir(basePath)
-
for file in files:
-
# 读取日志,判断当前图片是否被发送过
-
if HasNotBeenSent(file):
-
#获取图片大小
-
img = Image.open(file)
-
width = img.size[0]
-
height = img.size[1]
-
if width> height and width> 800:
-
width = 800
-
height = height*800/width
-
elif width <height and height> 800:
-
width = width*800/height
-
height = 800
-
#调整图片大小并保存为临时文件
-
img.thumbnail((width, height), Image.ANTIALIAS)
-
tmpPicPath = os.path.join(tempfile.gettempdir(), 'one_picture_per_day-' + datetime.datetime.now().__str__().replace(' ', '_') + '.jpg')
-
while os.path.exists(tmpPicPath):
-
tmpPicPath = os.path.join(tempfile.gettempdir(), 'one_picture_per_day-' + datetime.datetime.now().__str__().replace(' ', '_') + '.jpg')
-
img.save(tmpPicPath)
-
# 发送图片
-
SendMail(fromAddr, toAddrs, tmpPicPath)
-
# 记录日志
-
AppendLog(logHistory, datetime.datetime.now().__str__()+'|'+file)
-
# 清除图片
-
try:
-
os.unlink(file)
-
except:
-
Shout('成功发送“'+file+'”后删除原文件失败!')
-
#一次只发送一张图片
-
break
-
else:
-
try:
-
os.unlink(file)
-
except:
-
Shout('图片“'+file+'”曾被发送过,删除文件失败!')
-
continue
-
Shout('文件(' + file + ')曾被发送过,删除并发送下一幅新图片!')
显见,用python发送邮件是比较简单的。在完善这个程序的过程中,有些体会:
- 要善于利用“try...except...else...finally...”的异常处理机制预防程序中的隐患
- 文件的读取有可能出现异常,对这种异常的捕获应该放在“fp.read()”时,然后把“fp.close()”放在finally中
- 使用getpass模块的getpass()函数获取用户输入的密码而不回显
- 使用”os.sep“可以自动获取当前操作系统下路径的分割符,而”os.path.join()“函数可以根据当前操作系统的情况和两个路径的情况将两者连接成正确的路径格式
- gmail需要使用TLS安全连接,因此,相当于一般的电邮,要在创建SMTP对象后调用其“starttls()”方法
- 使用“locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')”设置本地环境,否则”datetime.datetime.strftime(datetime.datetime.now(), '%c')“得到的日期时间将是英文格式
- 使用PIL处理图片,应付一些常用操作绰绰有余并且相当简单
- 使用Image模块的open函数获取指定图片的对象
- 调用图片对象的thumbnail()方法获取指定大小的缩略图时,使用”Image.ANTIALIAS“常量以获取最佳图片质量
- 图片对象的save()方法能够根据指定的存储路径的后缀名转换图片格式
巧啊,昨天我写了个 python 脚本自动把log的分析结果做附件发给我,不过你这个要完善得多,哈哈。
楞,看来咱都一德性;我下了龙书第二版,准备看了。影印的不知道质量怎么样,1000多页啊,俺滴神啊。