发送邮件的python脚本[zt]

发送邮件的python脚本 (2008-07-05 20:43:41)
http://blog.sina.com.cn/s/blog_4e808acf01009vbv.html
标签: python 邮件 杂谈 分类: python #!/usr/bin/python
# -*- coding: utf-8 -*-

import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib

def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText):

strFrom = fromAdd
strTo = ', '.join(toAdd)

server = authInfo.get('server')
user = authInfo.get('user')
passwd = authInfo.get('password')

if not (server and user and passwd) :
print 'incomplete login info, exit now'
return

# 设定root信息
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = subject
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'

# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

#设定纯文本信息
msgText = MIMEText(plainText, 'plain', 'utf-8')
msgAlternative.attach(msgText)

#设定HTML信息
msgText = MIMEText(htmlText, 'html', 'utf-8')
msgAlternative.attach(msgText)

#设定内置图片信息
fp = open('test.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '')
msgRoot.attach(msgImage)

#发送邮件
smtp = smtplib.SMTP()
#设定调试级别,依情况而定
smtp.set_debuglevel(1)
smtp.connect(server)
smtp.login(user, passwd)
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
return

if __name__ == '__main__' :
authInfo = {}
authInfo['server'] = 'smtp.somehost.com'
authInfo['user'] = 'username'
authInfo['password'] = 'password'
fromAdd = '[email protected]'
toAdd = ['[email protected]', '[email protected]']
subject = '邮件主题'
plainText = '这里是普通文本'
htmlText = ' HTML文本'
sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText)


python 实践 (2008-07-03 15:58:04) 标签: python 杂谈 分类: python 1.文件操作,字符串操作
import os
import sys
os.remove('f:\\2008-07-03.txt') #删除文件
sys.exit()

import re
import time
f=open('f:\\a.txt','r')
linelist=f.readlines()
bb=[]
for line in linelist:
ren=re.compile(r'\n') #正则匹配
aa=ren.sub('',line) #正则替换
bb.append(aa)
f.close()
ff='f:\\'+time.strftime('%Y-%m-%d') + '.txt' #格式化时间
hand=file(ff,'a')
for ll in bb:
ll=ll+"\n"
hand.write(ll)
2.压缩文件
import os
import zipfile
import time
source_dir=r'F:test'
target_file='f:\\'+time.strftime('%Y-%m-%d') + '.zip'
myZipFile=zipfile.ZipFile(target_file,'w')
for root,dirs,files in os.walk(source_dir):
for vfileName in files:
fileName = os.path.join(root,vfileName)
myZipFile.write( fileName, fileName, zipfile.ZIP_DEFLATED )

myZipFile.close()
3.删除目录
第一种:
import os
source_dir=r'F:test'
for root,dirs,files in os.walk(source_dir):
for name in files:
os.remove(os.path.join(root,name))
for name in dirs:
os.rmdir(os.path.join(root,name))

第二种:
import os
def deltree(path):
'''if path is a file, del it;else del the content in it.
'''
if not os.path.exists(path):
return

if os.path.isfile(path):
os.remove(path)
else:
for filename in os.listdir(path):
deltree(path + os.sep + filename)
os.rmdir(path)
print path, 'deleted'

4.动态生成xml
#making up a text file's data as XML

import sys

print "Content-type:text/xml\n"

#write XML declaration and processing instruction
print """
href = "name.xsl"?>"""

#open data file
try:
file = open( "test.txt","r" )
except IOError:
sys.exit( "Error opening file" )

print "" #write root element

#list of tuples:(special character,entity reference)
replaceList = [ ( "&", "&" ),
( "<", "<" ),
( ">", ">" ),
( '"', """ ),
( "'", "'" ) ]

#replace special characters with entity reference
for currentLine in file.readlines():

for oldValue, newValue in replaceList:
currentLine = currentLine.replace( oldValue, newValue )

#extract lastname and firstname
last, first = currentLine.split( "," )
first = first.strip() #在python中strip是trim掉字符串两边的空格

#write contact element
print """
%s
%s
""" % ( last, first )

file.close()

print ""

你可能感兴趣的:(#Python)