rss· 投稿· 设为首页· 加入收藏· 繁體版
当前位置: 火魔网 » 程序开发 » Python

python smtp发送邮件 附件

挺方便的,自己写个脚本,就不用登陆邮箱发送附件了.
summary:
1.SMTP和HTTP类似.都是头里面有一些相关信息,content-type ,encoding啊,etc.Message是基类.用字典映射的方式可以读取和设置head中选项的值.MIMEText等MIME类型继承自MIMEBase,MIMEBase继承自Message.
他们都没有自己定义方法,都是用Message的
MIMEMultipart可以通过attach添加多个MIME的文件.所以用它添加附件 2.不同附件文件类型不同,head里面有个Content-Disposition的选项,可以设置文件类型.要上传不同文件类型,就要让python通过mimestypes.guess_type()识别文件类型 3.读取二进制文件的时候,打开方式要为"rb",因为可能会有和EOF编码相同的字节.这样python认为找到了文件的结尾,停止读入. 3.lambda: 随时定义一个函数,避免许多单行的函数定义
 # -*- coding: cp936 -*- import smtplib, mimetypes  
from email.mime.text import MIMEText  
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart   msg=MIMEMultipart()
msg["From"] = "xxx@xxx.com"
msg["To"] = "xxx@xxx.com"
msg["Subject"] = "Test SMTP by Python" text=MIMEText("This is text content.")
msg.attach(text) filename=r'F:\Novel\peach.zip'
ctype,encoding = mimetypes.guess_type(filename)
if ctype is None or encoding is not None:
    ctype='application/octet-stream'
maintype,subtype = ctype.split('/',1) #att=MIMEImage(open(filename,'r').read(),subtype)
att=MIMEImage(open(filename, 'rb').read(),subtype)
print ctype,encoding
att["Content-Disposition"] = 'attachmemt;filename="peach.zip"'
msg.attach(att) smtp=smtplib.SMTP()
smtp.connect("smtp.163.com")
smtp.login("xxx@xxx.com","password")
smtp.sendmail(msg["From"],msg["To"],msg.as_string()) smtp.quit()
print 'send mail successfully'
顶一下
(0)
踩一下
(0)