python怎么实现利用另一台电脑python 发邮件 附件

python发送邮件的一个简单实现 - 博客频道 - CSDN.NET
予小诺的博客
分类:python
使用python发送邮件的一个简单实现:
import smtplib,io
from email.mime.text import MIMEText
from email.header import Header
mail_host=''
mail_user=''
mail_pass='XXXXXXXXXXXXXX'
mail_receiver=['','']
mail_to = ','.join(mail_receiver)
HtmlFile = "c:\\python35\\work\\result.html"
with open(HtmlFile, "rb") as fb:
message=MIMEText(fb.read(),'html','UTF-8')
message['From']=Header(sender,'UTF-8')
message['To']=mail_to
subject='python SMTP 邮件测试主题'
message['Subject']=Header(subject,'UTF-8')
smtpObj=smtplib.SMTP()
print('准备连接服务器')
smtpObj.connect(mail_host)
print('准备登录邮箱')
smtpObj.login(mail_user, mail_pass)
print('准备邮件发送')
smtpObj.sendmail(sender, mail_receiver, message.as_string())
print('邮件发送成功')
except smtplib.SMTPException:
print('error:无法发送邮件')
参考菜鸟教程:
排名:千里之外
(1)(1)(5)(1)(1)(2)(1)(1)首页 & perl/php/python/gawk/sedpython邮件发送模块 python中email模块使得处理邮件变得比较简单,今天着重学习了一下发送邮件的具体做法,python模块虽然实现简单,不过使用不正确时,也会出现“由XXXX代发”的情况,这种情况会被很多邮箱当做垃圾邮件给处理掉。具体见如下截图: 如何避免上图中的问题,后面的部分也会提到。由浅入深,我们先来了解下email 相关模块的用法。 一、python email相关模块 1、smtplib模块smtplib.SMTP([host[, port[, local_hostname[, timeout]]]]) SMTP类构造函数,表示与SMTP服务器之间的连接,通过这个连接可以向smtp服务器发送指令,执行相关操作(如:登陆、发送邮件)。所有参数都是可选的。 host:smtp服务器主机名 port:smtp服务的端口,默认是25;如果在创建SMTP对象的时候提供了这两个参数,在初始化的时候会自动调用connect方法去连接服务器。 smtplib模块还提供了SMTP_SSL类和LMTP类,对它们的操作与SMTP基本一致。smtplib.SMTP提供的方法: SMTP.set_debuglevel(level):设置是否为调试模式。默认为False,即非调试模式,表示不输出任何调试信息。 SMTP.connect([host[, port]]):连接到指定的smtp服务器。参数分别表示smpt主机和端口。注意: 也可以在host参数中指定端口号(如:smpt.yeah.net:25),这样就没必要给出port参数。 SMTP.docmd(cmd[, argstring]):向smtp服务器发送指令。可选参数argstring表示指令的参数。 SMTP.helo([hostname]) :使用"helo"指令向服务器确认身份。相当于告诉smtp服务器“我是谁”。 SMTP.has_extn(name):判断指定名称在服务器邮件列表中是否存在。出于安全考虑,smtp服务器往往屏蔽了该指令。 SMTP.verify(address) :判断指定邮件地址是否在服务器中存在。出于安全考虑,smtp服务器往往屏蔽了该指令。 SMTP.login(user, password) :登陆到smtp服务器。现在几乎所有的smtp服务器,都必须在验证用户信息合法之后才允许发送邮件。 SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) :发送邮件。这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要 注意msg的格式。这个格式就是smtp协议中定义的格式。 SMTP.quit() :断开与smtp服务器的连接,相当于发送"quit"指令。(很多程序中都用到了smtp.close(),具体与quit的区别google了一下,也没找到答案。) 2、email模块 email 模块用来处理邮件消息,包括MIME和其他基于RFC 2822 的消息文档。使用这些模块来定义邮件的内容,是非常简单的。其包括的类有(更加详细的介绍可见:http://docs.python.org/library/email.mime.html): class email.mime.base.MIMEBase(_maintype, _subtype, **_params):这是MIME的一个基类。一般不需要在使用时创建实例。其中_maintype是内容类型,如text或者image。 _subtype是内容的minor type 类型,如plain或者gif。&**_params是一个字典,直接传递给Message.add_header()。 class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]:MIMEBase的一个子类,多个MIME对象的集合,_subtype默认值为mixed。boundary是MIMEMultipart的边界,默认边界是可数的。 class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]]):MIMEMultipart的一个子类。 class email.mime.audio. MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]): MIME音频对象 class email.mime.image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]]):MIME二进制文件对象。 class email.mime.message.MIMEMessage(_msg[, _subtype]):具体的一个message实例 。 class email.mime.text.MIMEText(_text[, _subtype[, _charset]]):MIME文本对象,其中_text是邮件内容,_subtype邮件类型,可以是text/plain(普通文本邮件),html/plain(html邮件),
_charset编码,可以是gb2312等等。 message类使用方法如下:msg=mail.Message.Message()
msg['to']=''
#发送到哪里
msg['from']=''
#自己的邮件地址
msg['date']=''
msg['subject']='hello world'
//上面的时间部分,可以考虑引入time模块,如下写
msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z') 二、几种邮件的具体实现代码 1、普通文本邮件 普通文本邮件发送的实现,关键是要将MIMEText中_subtype设置为plain。首先导入smtplib和mimetext。创建smtplib.smtp实例,connect邮件smtp服务器,login后发送,具体代码如下:# -*- coding: UTF-8 -*-
发送txt文本邮件
import smtplib
from email.mime.text import MIMEText
mailto_list=[]
mail_host=""
#设置服务器
mail_user="XXXX"
mail_pass="XXXXXX"
mail_postfix=""
#发件箱的后缀
def send_mail(to_list,sub,content):
me="hello"+"&"+mail_user+"@"+mail_postfix+"&"
msg = MIMEText(content,_subtype='plain',_charset='gb2312')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(mailto_list,"hello","hello world!"):
print "发送成功"
print "发送失败" 注:14行和17行定义的 from 的响应头,如果不使用的话,会出现最开始提到的由XXX代发的问题。 2、html邮件的发送 与text邮件不同之处就是将将MIMEText中_subtype设置为html。具体代码如下:# -*- coding: utf-8 -*-
发送html文本邮件
import smtplib
from email.mime.text import MIMEText
mailto_list=[""]
mail_host=""
#设置服务器
mail_user="XXX"
mail_pass="XXXX"
mail_postfix=""
#发件箱的后缀
def send_mail(to_list,sub,content):
#to_list:收件人;sub:主题;content:邮件内容
me="hello"+"&"+mail_user+"@"+mail_postfix+"&"
#这里的hello可以任意设置,收到信后,将按照设置显示
msg = MIMEText(content,_subtype='html',_charset='gb2312')
#创建一个实例,这里设置为html格式邮件
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
s = smtplib.SMTP()
s.connect(mail_host)
#连接smtp服务器
s.login(mail_user,mail_pass)
#登陆服务器
s.sendmail(me, to_list, msg.as_string())
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(mailto_list,"hello","&a href='/'&运维之路&/a&"):
print "发送成功"
print "发送失败" 3、发送带附件的邮件 发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送。# -*- coding: cp936 -*-
发送带附件邮件
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
#创建一个带附件的实例
msg = MIMEMultipart()
#构造附件1
att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = ' filename="123.doc"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字
msg.attach(att1)
#构造附件2
att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = ' filename="123.txt"'
msg.attach(att2)
msg['to'] = ''
msg['from'] = ''
msg['subject'] = 'hello world'
server = smtplib.SMTP()
server.connect('')
server.login('XXX','XXXXX')#XXX为用户名,XXXXX为密码
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.quit()
print '发送成功'
except Exception, e:
print str(e) 4、利用MIMEimage发送图片内容的邮件#!/usr/bin/env python
#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
sender = ''
receiver = ''
subject = 'python email test'
smtpserver = ''
username = 'itybku'
password = 'password'
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
# Create the body of the message (a plain-text and an HTML version).
# 邮件中使用图片的关键是在html页面中引用了图片cid
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
&head&&/head&
&p&Hi!&br&
How are you?&br&
Here is the &a href=""&运维之路&/a& you wanted.
&font color=red&给我捐赠:&br&&img src=\"cid:juanzheng\" border=\"1\"&
def addimg(src,imgid):
fp = open(src,'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID',imgid)
return msgImage
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
#att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')
msg.attach(addimg("1.png","juanzheng"))
attach = MIMEText(open('test.xlsx', 'rb').read(), 'base64', 'utf-8')
attach["Content-Type"] = 'application/octet-stream'
# 由于qq邮箱使用gb18030编码,避免乱码这里进行了转码
attach["Content-Disposition"] = ' filename="测试EXCEL.xlsx"'.decode("utf-8").encode("gb18030")
msg.attach(attach)
smtp = smtplib.SMTP()
smtp.connect('')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit() 效果如下图:
很多人表示,在邮件正文中使用图片不成功 ,希望显示的图片结果以附件的形式出现了。成功的关键是在html 中使用img标签,将图片cid写入就行了。 5、基于ssl 的邮件发送#!/usr/bin/env python
#coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = ''
username = '***'
password = '***'
msg = MIMEText('你好','plain','utf-8')#中文需参数‘utf-8',单字节字符不需要
msg['Subject'] = Header(subject, 'utf-8')
smtp = smtplib.SMTP()
smtp.connect('')
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.set_debuglevel(1)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
本站的发展离不开您的资助,金额随意,欢迎来赏!
分类: perl/php/python/gawk/sed python模块您可能也喜欢python异步 I/O模块gevent Python win32gui调用窗口到最前面 windows下使用python发送控制键 Python+selenium启动浏览器Firefox\Chrome\IE python logging配置时间或大小轮转 捐助本站
如您感觉本博客有用,可扫码向本博客捐赠近期文章 钉钉webhook实现告警通知 raw socket traceroute权限拒绝处理 使用ssldump解密https数据包 RH5885映射管理口不能用 普通用户无法修改密码问题处理文章归档 文章归档 选择月份 2017年七月 &(4) 2017年六月 &(1) 2017年五月 &(3) 2017年三月 &(3) 2017年二月 &(2) 2017年一月 &(4) 2016年十二月 &(4) 2016年十一月 &(6) 2016年十月 &(5) 2016年九月 &(5) 2016年八月 &(9) 2016年七月 &(4) 2016年六月 &(10) 2016年五月 &(18) 2016年四月 &(5) 2016年三月 &(4) 2016年二月 &(5) 2016年一月 &(8) 2015年十二月 &(8) 2015年十一月 &(9) 2015年十月 &(17) 2015年九月 &(10) 2015年八月 &(24) 2015年七月 &(11) 2015年六月 &(15) 2015年五月 &(23) 2015年四月 &(14) 2015年三月 &(22) 2015年二月 &(15) 2015年一月 &(24) 2014年十二月 &(13) 2014年十一月 &(16) 2014年十月 &(19) 2014年九月 &(19) 2014年八月 &(18) 2014年七月 &(20) 2014年六月 &(21) 2014年五月 &(24) 2014年四月 &(17) 2014年三月 &(29) 2014年二月 &(22) 2014年一月 &(22) 2013年十二月 &(24) 2013年十一月 &(20) 2013年十月 &(18) 2013年九月 &(16) 2013年八月 &(16) 2013年七月 &(20) 2013年六月 &(21) 2013年五月 &(19) 2013年四月 &(18) 2013年三月 &(24) 2013年二月 &(21) 2013年一月 &(18) 2012年十二月 &(24) 2012年十一月 &(18) 2012年十月 &(17) 2012年九月 &(17) 2012年八月 &(18) 2012年七月 &(26) 2012年六月 &(36) 2012年五月 &(36) 2012年四月 &(28) 2012年三月 &(46) 2012年二月 &(23) 2012年一月 &(15) 2011年十二月 &(27) 2011年十一月 &(59) 2011年十月 &(19) 2011年九月 &(16) 2011年八月 &(46)如何在一台电脑上同时使用 Python 2 和 Python 3 - 知乎专栏
{"debug":false,"apiRoot":"","paySDK":"/api/js","wechatConfigAPI":"/api/wechat/jssdkconfig","name":"production","instance":"column","tokens":{"X-XSRF-TOKEN":null,"X-UDID":null,"Authorization":"oauth c3cef7c66aa9e6a1e3160e20"}}
{"database":{"Post":{"":{"title":"如何在一台电脑上同时使用 Python 2 和 Python 3","author":"crossin","content":"Python 的版本是这几年被开发者诟病的一大槽点,也让众多新手头疼不已。逐渐退居二线的老版本 2 存在不少缺陷但应用广泛,而新版本 3 为了彻底解决历史遗留问题决定另起炉灶不向后兼容。对于开发者来说,如果要更新版本,将有大量的代码移植工作,同时还得考虑外部依赖库的兼容性。而对于学习者来说,最大的问题莫过于:我要学 2 还是学 3?不过今天要说的不是 2 与 3 的选择,而是另一个事情。如果你想兼容并包地看下两个版本的教程,或是已经基本掌握一个版本,打算 get 另一个版本时,就必须要面对如何在你的电脑上同时使用 Python 2 和 Python 3 的问题。Linux如果你是 Linux 系统,通常都默认安装了 Python 2.x 版本,在命令行下查看版本:python -V\n而通过包管理或者编译安装的 Python 3 版本,会是另一个名字:python3(也有的是带小版本号如 python3.4)。再查看版本:python3 -V\n因此只要用不同的命令,就可以区分版本了。python test_v2.py\npython3 test_v3.py\n如果想要用 python3 替换默认的 python,常见的做法是修改系统 PATH 路径中的 python,让它成为一个指向 python3 的软链接,或者用 alias,将 python 指定为 python3 的别名。MacMac 系统也默认装有 Python 2.x 版本。安装3版本一种较方便的方法是使用 homebrew(需自行安装):brew install python3\n同样,它叫做 python3,与原有的 python 区别开。 Windows而在 Windows 上,默认没有 Python,需要下载安装。官网上提供有不同版本,安装后路径不同,但执行程序名称均为 python.exe。看上去好像要复杂一些。但其实官方已经很贴心地提供了一个解决方案:当你安装 Python 3 版本之后,就会同时安装一个名为 py.exe 的 Python 启动器。可以用它替代 python 命令:py test.py\n并且可以指定版本(前提是安装了对应版本):py -2 test_v2.py\npy -3 test_v3.py\n上一次说到可以通过 pip 来安装第三方模块(参见 )。如果系统里有了两个版本的 Python,用 pip 时需注意,究竟是安装在了哪个版本上。通过命令可查看 pip 默认的对应版本:pip -V\n为了防止出现版本对应混乱的情况,除了默认的 pip 之外,每个版本都有对应的副本,如 pip2、pip2.7、pip3、pip3.5。所以当需要明确安装版本时,可使用对应的命令:pip2 install ...\npip3 install ...\n除此之外,Windows 上也可以这样做:py -2 -m pip install ...\npy -3 -m pip install ...\n当然,这些的前提是将对应目录加到了系统变量 PATH 路径里,包括 Python 安装目录及其 Scripts 子目录。如果没有在安装时勾选全部可选项,让安装程序自动帮你设置好,则需要手动添加。还有种优雅的方法控制不同 Python 版本的共存,就是通过 pyenv 或者 virtualenv 创建虚拟开发环境。之后也会来说一说。其他文章及回答:Crossin的编程教室微信ID:crossincode论坛:QQ群:","updated":"T15:07:16.000Z","canComment":false,"commentPermission":"anyone","commentCount":1,"collapsedCount":0,"likeCount":23,"state":"published","isLiked":false,"slug":"","isTitleImageFullScreen":false,"rating":"none","titleImage":"/51faeffacee62_r.jpg","links":{"comments":"/api/posts//comments"},"reviewers":[],"topics":[{"url":"/topic/","id":"","name":"Python"},{"url":"/topic/","id":"","name":"编程"},{"url":"/topic/","id":"","name":"版本"}],"adminClosedComment":false,"titleImageSize":{"width":991,"height":423},"href":"/api/posts/","excerptTitle":"","column":{"slug":"crossin","name":"Crossin的编程教室"},"tipjarState":"inactivated","annotationAction":[],"sourceUrl":"","pageCommentsCount":1,"hasPublishingDraft":false,"snapshotUrl":"","publishedTime":"T23:07:16+08:00","url":"/p/","lastestLikers":[{"bio":"理工男,kindle中毒用户","isFollowing":false,"hash":"86ff2b33665a91bba40d08","uid":00,"isOrg":false,"slug":"bgcai","isFollowed":false,"description":"科普/无神论/循证医学/基因弥母机器/Kindle/反乌托邦/豆腐脑甜党/RAmen","name":"Benjamin Tsai","profileUrl":"/people/bgcai","avatar":{"id":"v2-2fa3f0d72106ccf1380978","template":"/{id}_{size}.jpg"},"isOrgWhiteList":false},{"bio":"一个想成为架构师正在学习运维知识的网管","isFollowing":false,"hash":"133ba1d55","uid":794600,"isOrg":false,"slug":"divent","isFollowed":false,"description":"","name":"Divent","profileUrl":"/people/divent","avatar":{"id":"ecec61c399","template":"/{id}_{size}.jpg"},"isOrgWhiteList":false},{"bio":"open mind","isFollowing":false,"hash":"a5c0ae00af77f015da00","uid":08,"isOrg":false,"slug":"absfree","isFollowed":false,"description":"/users/640ce09fd6ec","name":"absfree","profileUrl":"/people/absfree","avatar":{"id":"3a348f2e63b12d59ae576a","template":"/{id}_{size}.jpg"},"isOrgWhiteList":false},{"bio":"programmer","isFollowing":false,"hash":"aaa6fe11a2e368f150a8609e95eab596","uid":115500,"isOrg":false,"slug":"mao-xian-xin-14","isFollowed":false,"description":"","name":"毛显新","profileUrl":"/people/mao-xian-xin-14","avatar":{"id":"da8e974dc","template":"/{id}_{size}.jpg"},"isOrgWhiteList":false},{"bio":null,"isFollowing":false,"hash":"a7eb6fddce5cc8cb6fdcae7","uid":48,"isOrg":false,"slug":"hui-sun-36","isFollowed":false,"description":"","name":"polar sun","profileUrl":"/people/hui-sun-36","avatar":{"id":"v2-606cee20935fa0bddcb428e8d26b8b90","template":"/{id}_{size}.jpg"},"isOrgWhiteList":false}],"summary":"Python 的版本是这几年被开发者诟病的一大槽点,也让众多新手头疼不已。逐渐退居二线的老版本 2 存在不少缺陷但应用广泛,而新版本 3 为了彻底解决历史遗留问题决定另起炉灶不向后兼容。对于开发者来说,如果要更新版本,将有大量的代码移植工作,同时还得…","reviewingCommentsCount":0,"meta":{"previous":{"isTitleImageFullScreen":false,"rating":"none","titleImage":"/fcb8d24d59dbd3ae_r.jpg","links":{"comments":"/api/posts//comments"},"topics":[{"url":"/topic/","id":"","name":"Python"},{"url":"/topic/","id":"","name":"Python 入门"},{"url":"/topic/","id":"","name":"Python 库"}],"adminClosedComment":false,"href":"/api/posts/","excerptTitle":"","author":{"bio":"Crossin的编程教室 - python新手村","isFollowing":false,"hash":"3a3f8f73b5","uid":88,"isOrg":false,"slug":"crossin","isFollowed":false,"description":"每天5分钟,一起学编程。欢迎加入“Crossin的编程教室”,/home/,微信公众号 crossincode,微信加群 crossin123,QQ群 。","name":"Crossin","profileUrl":"/people/crossin","avatar":{"id":"85b47091c","template":"/{id}_{size}.jpg"},"isOrgWhiteList":false},"column":{"slug":"crossin","name":"Crossin的编程教室"},"content":"正所谓“人生苦短,我用 Python”。Python 的一大优势就是有丰富且易用的第三方模块,省去了大量重复造轮子的时间,节约了众多开发者的生命。对于已经熟悉 Python 开发的人来说,安装第三方模块是家常便饭的事情。但如果是刚入门的新手,很可能会被折腾一番。所以我来简单地科普一下,如何安装 Python 的第三方模块。(本文基于 Python 2.7 版本)安装通常有两种方式:通过包管理器、直接下载源码安装。1. 包管理器很多系统和语言都提供了包管理器。你可以把“包管理器”想象成一个类似应用商店的工具。Python 的包管理器里就是各种第三方模块。有了它,不用998,也不用98,只需要一条命令,就可以自动帮你下载并安装。Python 常用的包管理器是 pip 和 easy_install。他们会从一个叫做 PyPI 的源里搜索你要的模块,找到后自动下载安装。PyPI 是 Python 官方的第三方模块仓库,供所有开发者下载或上传代码。如果你用的是 Mac 或者 Linux,那么同 Python 一样,你的系统里应该自带了 pip。而如果你是 Windows,那么在安装 Python 的时候,勾选 pip 和 Add python.exe to Path,就会帮你同时安装好 pip 并设置好环境变量中的路径。如果无法使用 pip,确认 Python 安装目录下的 Scripts 子目录中有 pip,并且这个子目录的路径被加在了环境变量 Path 中。如果没有 pip,则要通过下载 setuptools 安装,或建议直接重新安装一遍 Python。以 IPython 为例,通过 pip 命令进行安装,只需要在命令行输入:pip install ipython\n如果一切正常,网络不抽风,只要稍微等待,就可以看到下载进度,自动安装完就可使用。如果 Mac/Linux 下提示 Permission denied 之类的权限问题,在命令前加上 sudo。IPython 是一个增强版的 Python shell,在命令行输入 ipython 就可以打开使用。比默认运行 python 进入的那个更好使,在里面调试代码会很方便。不过 windows 的话,还要再用 pip 装一个 pyreadline 的模块,才能使用 IPython 的 tab 键自动补全功能。(用 Windows 开发就是事多)如果你不是很明确要下载的模块名,也可以进行搜索,比如:pip search ipython\n再来看 easy_install。安装 easy_install 的一种简单方法是去网上下载一个的脚本文件:( /dist/ez_setup.py )下载之后运行它:python ez_setup.py\n然后 easy_install 就被安装好了。同样,需确认 Scripts 在环境变量 PATH 里。使用方法和 pip 一样简单:easy_install ipython\n一般来说,pip 和 easy_install 就可以搞定绝大多数的模块安装了。万一不行,还可以尝试下面的另一种方式。2. 源码安装几乎所有第三方模块都可以在 PyPI 或 github 上找到源码,都会提供 zip、tar 等格式的压缩包。把代码压缩包下载到本地并解压,应该会看到一个 setup.py 的文件。在命令行进入其所在目录,执行:python setup.py install\n就会安装这个第三方模块。最终效果和用包管理器是一样的。无论哪种方法,都会将第三方模块代码安装至 Python 的路径下,根据系统不同,位置有所区别,大致都是叫做 site-packages 或 dist-packages。所以对于一些没有其他依赖,不需要编译其他语言的纯 Python 代码包,也可以直接手动将源码复制到 site-packages 或 dist-packages 目录下。只要路径正确,就可以在你的代码里引入这些模块。友情提醒一些坑:安装第三方模块前,请确认它所支持的版本,是不是包含你所使用的 Python 版本。有些模块对应 Python 2 和 3 需要下载不同的版本。少数复杂的包可能无法直接一条命令安装成功,特殊情况特殊对待,搜索引擎会给你指引。如果你的电脑上装有多个版本的 Python,使用 pip 很可能会造成混乱。对于这个问题,virtualenv 是一个很好的解决方案,下次会专门来讲一讲。有一个叫做 Awesome Python 的项目,列出了各类优秀的、实用的、有意思的 Python 库:Crossin的编程教室微信ID:crossincode论坛:QQ群:","state":"published","sourceUrl":"","pageCommentsCount":0,"canComment":false,"snapshotUrl":"","slug":,"publishedTime":"T23:13:44+08:00","url":"/p/","title":"如何安装 Python 的第三方模块","summary":"正所谓“人生苦短,我用 Python”。Python 的一大优势就是有丰富且易用的第三方模块,省去了大量重复造轮子的时间,节约了众多开发者的生命。对于已经熟悉 Python 开发的人来说,安装第三方模块是家常便饭的事情。但如果是刚入门的新手,很可能会被折腾一番…","reviewingCommentsCount":0,"meta":{"previous":null,"next":null},"commentPermission":"anyone","commentsCount":9,"likesCount":83},"next":{"isTitleImageFullScreen":false,"rating":"none","titleImage":"/ec1aab151079fdc044ef_r.jpg","links":{"comments":"/api/posts//comments"},"topics":[{"url":"/topic/","id":"","name":"Python"},{"url":"/topic/","id":"","name":"编程入门"},{"url":"/topic/","id":"","name":"自学编程"}],"adminClosedComment":false,"href":"/api/posts/","excerptTitle":"","author":{"bio":"Crossin的编程教室 - python新手村","isFollowing":false,"hash":"3a3f8f73b5","uid":88,"isOrg":false,"slug":"crossin","isFollowed":false,"description":"每天5分钟,一起学编程。欢迎加入“Crossin的编程教室”,/home/,微信公众号 crossincode,微信加群 crossin123,QQ群 。","name":"Crossin","profileUrl":"/people/crossin","avatar":{"id":"85b47091c","template":"/{id}_{size}.jpg"},"isOrgWhiteList":false},"column":{"slug":"crossin","name":"Crossin的编程教室"},"content":"在用 python2 抓取网页的时候,经常会遇到抓下来的内容显示出来是乱码。发生这种情况的最大可能性就是编码问题:运行环境的字符编码和网页的字符编码不一致。比如,在 windows 的控制台(gbk)里抓取了一个 utf-8 编码的网站。或者,在 Mac / Linux 的终端(utf-8)里抓取了一个 gbk 编码的网站。因为多数网站采用 utf-8 编码,而不少人又是用 windows,所有这种情况相当常见。如果你发现你抓下来的内容,看上去英文、数字、符号都是对的,但中间夹杂了一些乱码,那基本可以断定是此情况。解决这个问题的办法就是,把结果先按网页的编码方式 decode 解码成 unicode,再输出。如果不确定网页的编码,可参照以下代码:import urllib\nreq = urllib.urlopen(\"http://some.web.site\")\ninfo = req.info()\ncharset = info.getparam('charset')\ncontent = req.read()\nprint content.decode(charset, 'ignore')\n'ignore' 参数的作用是忽略掉无法解码的字符。不过这种方法不总是有效。还有种方式就是通过正则直接匹配网页代码中的编码设置:&meta http-equiv=Content-Type content=\"text/charset=utf-8\"&\n除了编码问题造成乱码之外,还有种常被忽视的情况,就是目标网页启用了 gzip 压缩。压缩后的网页传输数据少了,打开速度更快。在浏览器中打开时,浏览器会根据网页的 header 信息自动做解压。但直接用代码抓取则不会。因此很可能就被搞糊涂了,为什么明明打开网页地址是对的,但程序抓取就不行。连我自己也曾经被这个问题坑过。这种情况的表现是抓取的内容几乎全是乱码,甚至无法显示。要判断网页是否启用了压缩并对其解压,可参考以下代码:import urllib\nimport gzip\nfrom StringIO import StringIO\nreq = urllib.urlopen(\"http://some.web.site\")\ninfo = req.info()\nencoding = info.getheader('Content-Encoding')\ncontent = req.read()\nif encoding == 'gzip':\n
buf = StringIO(content)\n
gf = gzip.GzipFile(fileobj=buf)\n
content = gf.read()\nprint content\n在我们教室的编程实例
中,这两个问题困扰了相当多人。在此特别讲解一下。最后,还有个“利器”要介绍一下。如果一开始就用它,你甚至不知道还有上述两个问题的存在。这就是 requests 模块。同样抓取网页,只需要:import requests\nprint requests.get(\"http://some.web.site\").text\n没有编码问题,没有压缩问题。This is why I love Python.至于如何安装 requests 模块,请参考之前的文章:pip install requests\n其他文章及回答:Crossin的编程教室微信ID:crossincode论坛:QQ群:","state":"published","sourceUrl":"","pageCommentsCount":0,"canComment":false,"snapshotUrl":"","slug":,"publishedTime":"T11:15:50+08:00","url":"/p/","title":"Python 抓取网页乱码原因分析","summary":"在用 python2 抓取网页的时候,经常会遇到抓下来的内容显示出来是乱码。发生这种情况的最大可能性就是编码问题:运行环境的字符编码和网页的字符编码不一致。比如,在 windows 的控制台(gbk)里抓取了一个 utf-8 编码的网站。或者,在 Mac / Linux 的终端…","reviewingCommentsCount":0,"meta":{"previous":null,"next":null},"commentPermission":"anyone","commentsCount":8,"likesCount":26}},"annotationDetail":null,"commentsCount":1,"likesCount":23,"FULLINFO":true}},"User":{"crossin":{"isFollowed":false,"name":"Crossin","headline":"每天5分钟,一起学编程。欢迎加入“Crossin的编程教室”,/home/,微信公众号 crossincode,微信加群 crossin123,QQ群 。","avatarUrl":"/85b47091c_s.jpg","isFollowing":false,"type":"people","slug":"crossin","bio":"Crossin的编程教室 - python新手村","hash":"3a3f8f73b5","uid":88,"isOrg":false,"description":"每天5分钟,一起学编程。欢迎加入“Crossin的编程教室”,/home/,微信公众号 crossincode,微信加群 crossin123,QQ群 。","profileUrl":"/people/crossin","avatar":{"id":"85b47091c","template":"/{id}_{size}.jpg"},"isOrgWhiteList":false,"badge":{"identity":null,"bestAnswerer":null}}},"Comment":{},"favlists":{}},"me":{},"global":{},"columns":{"crossin":{"following":false,"canManage":false,"href":"/api/columns/crossin","name":"Crossin的编程教室","creator":{"slug":"crossin"},"url":"/crossin","slug":"crossin","avatar":{"id":"3461ca55befed6be10512","template":"/{id}_{size}.jpeg"}}},"columnPosts":{},"columnSettings":{"colomnAuthor":[],"uploadAvatarDetails":"","contributeRequests":[],"contributeRequestsTotalCount":0,"inviteAuthor":""},"postComments":{},"postReviewComments":{"comments":[],"newComments":[],"hasMore":true},"favlistsByUser":{},"favlistRelations":{},"promotions":{},"switches":{"couldAddVideo":false},"draft":{"titleImage":"","titleImageSize":{},"isTitleImageFullScreen":false,"canTitleImageFullScreen":false,"title":"","titleImageUploading":false,"error":"","content":"","draftLoading":false,"globalLoading":false,"pendingVideo":{"resource":null,"error":null}},"drafts":{"draftsList":[],"next":{}},"config":{"userNotBindPhoneTipString":{}},"recommendPosts":{"articleRecommendations":[],"columnRecommendations":[]},"env":{"isAppView":false,"appViewConfig":{"content_padding_top":128,"content_padding_bottom":56,"content_padding_left":16,"content_padding_right":16,"title_font_size":22,"body_font_size":16,"is_dark_theme":false,"can_auto_load_image":true,"app_info":"OS=iOS"},"isApp":false},"sys":{}}

我要回帖

更多关于 python 发邮件 的文章

 

随机推荐