邮件发送是普通业务开拓以及自动化运维中一个常用的功能,python供应了smtplib组件用于发送邮件。下面给出一个结合django框架实现的邮件发送案例:
from __future__ import unicode_literalsfrom django.shortcuts import HttpResponseimport smtplibimport string# Create your views here.def send(request):Host = \"大众smtp.163.com\公众Subject = \公众email test\"大众To = \"大众demo@example.com\公众From = \"大众php_coder@163.com\公众text = \公众Python send email\"大众Body = string.join((\"大众from:%s\"大众 % From,\"大众to:%s\"大众 % To,\公众subject:%s\"大众 % Subject,\公众\公众,text), \"大众\r\n\"大众)server = smtplib.SMTP()server.connect(Host, \公众25\"大众)server.starttls()server.login(\公众php_coder@163.com\公众, \"大众your163emailpassword\公众)result = server.sendmail(From, [To], Body)server.quit()return HttpResponse(\公众OK\公众)
在浏览器中实行发送要求,会报错:“getaddrinfo() argument 2 must be integer or string”,这是说getaddrinfo这个方法的第二个参数必须是整数或者字符串。我们找到getaddrinfo这个方法的参数声明:getaddrinfo(host, port, family=None, socktype=None, proto=None, flags=None),可以知道,第二个参数是端口,也便是我们传给connect方法的\"大众25\"大众。从表面来看,我们传的确实是string(对付PHP、Java开拓工程师更是拍胸脯地自傲是string),但是我们引入了这样一段代码:from __future__ import unicode_literals。在python中:
从Python 2.7到Python 3.x就不兼容的一些改动,比如2.x里的字符串用'xxx'表示string,Unicode字符串用u'xxx'表示unicode,而在3.x中,所有字符串都被视为unicode,因此,写u'xxx'和'xxx'是完备同等的,而在3.x中以'xxx'表示的string就必须写成b'xxx',以此表示“二进制字符串”

为了适应Python 3.x的新的字符串的表示方法,在2.7版本的代码中,可以通过
unicode_literals
来利用Python 3.x的新的语法:在python3中默认的编码采取了unicode, 并取消了前缀u通过上面的剖析,就可以知道了,我们传的port参数值“25”在当前是unicode编码,而getaddrinfo方法哀求端口号参数值是string或者int型,以是我们可以将上述的代码这样修正(任选其一):
将server.connect(Host, \"大众25\"大众)改为:server.connect(Host, 25)
将server.connect(Host, \"大众25\"大众)改为:server.connect(Host, b\公众25\"大众)
将server.connect(Host, \"大众25\"大众)改为:server.connect(Host, str(\"大众25\公众))
这样就不会报错了,办理了getaddrinfo() argument 2 must be integer or string问题。python中的编码问题特殊要把稳。