通过smtplib发邮件的客户端class
喜欢实现n多的功能,赶紧做个备份,避免以后需要再折腾。
定义邮件title(mailsub),以,或;分隔的附加文件列表(filelist),正文文本(和textype结合,可发送htm格式)等;
那个msg['To'] 和最后sendmail里面的收件人地址可以考虑分开,随便对msg['To']赋值,这样可以实现隐藏收件人的信息;
class PySendMail:
def
__init__(self,user='mailuser',userpass='mailpass',smtpserver='x.x.x.x',fro='mailuser
'):
'''注意对于某些smtp server,fro必须附有类似,可以让smtp server识别为正确存在的帐号;
'''
self.user = user
self.userpass = userpass
self.smtpserver = smtpserver
self.fro = fro
def
sendmail(self,mailto='',mailsub='',attachtext='',textype='plain',dctype='application/octet-stream',filelist='',login=1,debug=0):
'''filelist: 邮件附件文件列表,可以以","或者";"分隔;
attachtext: 邮件的文本正文;
textype: text 或者 html, 处理邮件正文;
dctype: 默认附件类型为application/octet-stream;
mailto: 要发送的邮件地址列表,可以以","或者";"分隔
login: 如果设置为1,smtp将采用指定的用户密码登陆,默认为1;
debug: 设置为1,开启debug,默认为0;
'''
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
from email.MIMEImage import MIMEImage
#处理邮件地址列表
addrlist1 = re.split('\s*[,|;]\s*',mailto)
addrlist = []
for addr in addrlist1:
if re.match('\s*\S+@\S+\.\S+',addr): addrlist.append(addr)
msg = MIMEMultipart()
msg['From'] = self.fro
msg['To'] = COMMASPACE.join(addrlist)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = mailsub
#处理文本:
maintype = 'text'
if textype == 'plain' or textype == 'html':
txtsubtype = textype
fpld = MIMEBase (maintype, txtsubtype)
fpld.set_payload(attachtext)
Encoders.encode_base64(fpld)
msg.attach(fpld)
#处理附件:
mailfilelist = []
if filelist: mailfilelist = re.split('\s*[,|;]\s*',filelist)
for adfile in mailfilelist:
ctype, encoding = mimetypes.guess_type(adfile)
if ctype is None or encoding is not None:
ctype = dctype
maintype, subtype = ctype.split('/', 1)
try:
fsock=open(adfile,'rb')
fpld = MIMEBase (maintype, subtype)
fpld.set_payload(fsock.read())
Encoders.encode_base64(fpld)
fsock.close
#if ctype != 'text/plain':
fpld.add_header('Content-Disposition', 'attachment',filename=re.split('/',adfile)[-1])
msg.attach(fpld)
except IOError:
print 'cant open file: %s ' %adfile
#邮件发送
smtp = smtplib.SMTP(self.smtpserver)
if debug: smtp.debuglevel = 5
if login: smtp.login(self.user,self.userpass)
smtp.sendmail(self.fro, addrlist, msg.as_string() )
smtp.close()
http://blog.chinaunix.net/u1/57278/showart_482145.html
阅读(1296) | 评论(0) | 转发(0) |