搜索

python发送邮件

May 28, 2017 am 10:03 AM
python

python发送邮件

准备

python中发送邮件主要用的是smtplib和email两个模块,下面主要对这两个模块进行讲解

在讲解之前需要准备至少两个测试的邮箱,其中要在邮箱的设置中开启smtplib协议才可以进行发送和接受

smtplib

  • smtplib.SMTP( [host [, port [, local_hostname[,<a href="http://www.php.cn/wiki/1268.html" target="_blank">time</a>out]]]]) hostSMTP主机的服务器,其中163邮箱的是smtp.163.com,其他的可以在网上找到,port是端口号,这里默认的是25local_hostname是你主机的SMTP,如果SMTP在你的本机上,你只需要指定服务器地址为 localhost 即可。timeout是设置的连接的限制时间,如果超过这个时间还没有连接上那么就会出现错误

  • SMTP.<a href="http://www.php.cn/code/8209.html" target="_blank">set</a>_debuglevel(level):设置是否为调试模式。默认为False,即非调试模式,表示不输出任何调试信息。如果设置为1就表示输出调试信息

  • SMTP.connect([host[, port]]):连接到指定的smtp服务器。参数分别表示smpt主机和端口。注意: 也可以在host参数中指定端口号(如:smpt.yeah.net:25),这样就没必要给出port参数。

  • SMTP.login(user, passw<a href="http://www.php.cn/wiki/1360.html" target="_blank">ord</a>) 登录服务器,这里的user是邮箱的用户名,但是这里的password并不是你邮箱的密码,当你开启SMTP的时候会提示你设置一个密码,这里的密码就是对应的密码

  • SMTP.s<a href="http://www.php.cn/wiki/1048.html" target="_blank">end</a>mail(from_addr, [to_addrs,], msg[, mail_options, rcpt_options]) 发送邮件,from_addr是发送方也就是你的邮箱地址,to_addr是接受方的地址,当然这里的可以填上多个邮箱账号发送给多个账号,如果有多个账号需要使用列表传递参数

  • SMTP.quit()断开连接

email

emial模块用来处理邮件消息,包括MIME和其他基于RFC 2822的消息文档。使用这些模块来定义邮件的内容,是非常简单的。其包括的类有(更加详细的介绍可见:http://docs.python.org/library/email.mime.html):

  • <a href="http://www.php.cn/wiki/164.html" target="_blank">class</a> email.mime.base.MIMEBase(_<a href="http://www.php.cn/wiki/646.html" target="_blank">main</a>type, _subtype, **_params):这是MIME的一个基类。一般不需要在使用时创建实例。其中_maintype是内容类型,如text或者image。_subtype是内容的minor type类型,如plain或者g<a href="http://www.php.cn/wiki/109.html" target="_blank">if</a>**_params是一个字典,直接传递给Message.add_header()。

  • class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]MIMEBase的一个子类,多个MIME对象的集合,_subtype默认值为mixedboundaryMIMEMultipart的边界,默认边界是可数的。当需要发送附件的时候使用的就是这个类

  • 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.text.MIMEText(_text[, _subtype[, _charset]])MIME文本对象,其中_text是邮件内容,_subtype邮件类型,可以是text/plain(普通文本邮件),html/plain(html邮件), _charset编码,可以是gb2312等等。

  • 普通文本邮件发送的实现,关键是要将MIMEText_subtype设置为plain。首先导入smtplibmimetext。创建smtplib.smtp实例,connect邮件smtp服务器,login后发送,具体代码如下*


# 一个格式化邮件的函数,可以用来使用def _format_addr(s):
    name, addr = parseaddr(s)    return formataddr((
        Header(name, &#39;utf-8&#39;).encode(),
        addr.encode(&#39;utf-8&#39;) if isinstance(addr, unicode) else addr))

from_addr=&#39;××××××××&#39;   #你的邮箱地址from_password=&#39;×××××××&#39;   #你的密码# to_email=&#39;chenjiabing666@yeah.net&#39;to_email=&#39;××××××&#39;    #要发送的邮箱地址msg=MIMEText(&#39;乔装打扮,不择手段&#39;,&#39;plain&#39;,&#39;utf-8&#39;)  #这里text=乔装打扮,不择手段msg[&#39;From&#39;] = _format_addr(u&#39;Python爱好者 <%s>&#39; % from_addr)  #格式化发件人msg[&#39;To&#39;] = _format_addr(u&#39;管理员 <%s>&#39; % to_email)    #格式化收件人msg[&#39;Subject&#39;] = Header(u&#39;来自SMTP的问候……&#39;, &#39;utf-8&#39;).encode()    #格式化主题stmp=&#39;smtp.163.com&#39;server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password)    #登录server.set_debuglevel(1)        #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string())   #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表


发送html邮件

还是用MIMEText来发送,不过其中的_subType设置成html即可,详细代码如下:


def _format_addr(s):
    name, addr = parseaddr(s)    return formataddr((
        Header(name, &#39;utf-8&#39;).encode(),
        addr.encode(&#39;utf-8&#39;) if isinstance(addr, unicode) else addr))

from_addr=&#39;××××××××&#39;   #你的邮箱地址from_password=&#39;×××××××&#39;   #你的密码# to_email=&#39;chenjiabing666@yeah.net&#39;to_email=&#39;××××××&#39;    #要发送的邮箱地址html="""<p><h1 style="color:red">大家好</h1></p>"""msg=MIMEText(html,&#39;html&#39;,&#39;utf-8&#39;)  #这里text=html,设置成html格式的msg[&#39;From&#39;] = _format_addr(u&#39;Python爱好者 <%s>&#39; % from_addr)  #格式化发件人msg[&#39;To&#39;] = _format_addr(u&#39;管理员 <%s>&#39; % to_email)    #格式化收件人msg[&#39;Subject&#39;] = Header(u&#39;来自SMTP的问候……&#39;, &#39;utf-8&#39;).encode()    #格式化主题stmp=&#39;smtp.163.com&#39;server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password)    #登录server.set_debuglevel(1)        #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string())   #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表


附件的发送

发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送,具体实力如下:


from email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport smtplibfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.header import Headerdef _format_addr(s):
    name, addr = parseaddr(s)    return formataddr((
        Header(name, &#39;utf-8&#39;).encode(),
        addr.encode(&#39;utf-8&#39;) if isinstance(addr, unicode) else addr))

from_addr=&#39;××××××××&#39;   #你的邮箱地址from_password=&#39;×××××××&#39;   #你的密码# to_email=&#39;chenjiabing666@yeah.net&#39;to_email=&#39;××××××&#39;    #要发送的邮箱地址msg=MIMEMultipart()   #创建实例text=MIMEText(&#39;<h2 style="color:red">陈加兵</h2><br/><p>大家好</p>&#39;,&#39;html&#39;,&#39;utf-8&#39;)
msg.attach(text)   #添加一个正文信息,这里实在正文中显示的信息#创建一个文本附件,这里是从指定文本中读取信息,然后创建一个文本信息att1=MIMEText(open(&#39;/home/chenjiabing/文档/MeiZi_img/full/file.txt&#39;,&#39;rb&#39;).read(),&#39;plain&#39;,&#39;utf-8&#39;)
att1["Content-Type"] = &#39;application/octet-stream&#39;  #指定类型att1["Content-Disposition"] = &#39;attachment; filename="123.txt"&#39;#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1)     #向其中添加附件img_path=&#39;/home/chenjiabing/文档/MeiZi_img/full/file.jpg&#39;  #图片路径image=MIMEImage(open(img_path,&#39;rb&#39;).read())     #创建一个图片附件image.add_header(&#39;Content-ID&#39;,&#39;<0>&#39;)   #指定图片的编号,这个会在后面用到image.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename=&#39;test.jpg&#39;)        
image.add_header(&#39;X-Attachment-Id&#39;, &#39;0&#39;)
msg.attach(image)    #添加附件stmp=&#39;smtp.163.com&#39;server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password)    #登录server.set_debuglevel(1)        #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string())   #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表


将图片嵌入到正文信息中


from email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport smtplibfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.header import Headerdef _format_addr(s):
    name, addr = parseaddr(s)    return formataddr((
        Header(name, &#39;utf-8&#39;).encode(),
        addr.encode(&#39;utf-8&#39;) if isinstance(addr, unicode) else addr))

from_addr=&#39;××××××××&#39;   #你的邮箱地址from_password=&#39;×××××××&#39;   #你的密码# to_email=&#39;chenjiabing666@yeah.net&#39;to_email=&#39;××××××&#39;    #要发送的邮箱地址msg=MIMEMultipart()   #创建实例html="""<html><head></head><body><p>下面演示嵌入图片</p><section><img src=&#39;cid:0&#39; style=&#39;float:left&#39;/><img src=&#39;cid:1&#39; style=&#39;float:left&#39;/></setcion></body></html>"""text=MIMEText(&#39;<h2 style="color:red">陈加兵</h2><br/><p>大家好</p>&#39;,&#39;html&#39;,&#39;utf-8&#39;)
msg.attach(text)   #添加一个正文信息,这里实在正文中显示的信息#创建一个文本附件,这里是从指定文本中读取信息,然后创建一个文本信息att1=MIMEText(open(&#39;/home/chenjiabing/文档/MeiZi_img/full/file.txt&#39;,&#39;rb&#39;).read(),&#39;plain&#39;,&#39;utf-8&#39;)
att1["Content-Type"] = &#39;application/octet-stream&#39;  #指定类型att1["Content-Disposition"] = &#39;attachment; filename="123.txt"&#39;#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1)     #向其中添加附件## 创建一个图片附件img_path=&#39;/home/chenjiabing/文档/MeiZi_img/full/file.jpg&#39;  #图片路径image=MIMEImage(open(img_path,&#39;rb&#39;).read())     #创建一个图片附件image.add_header(&#39;Content-ID&#39;,&#39;<0>&#39;)   #指定图片的编号,image.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename=&#39;test.jpg&#39;)        
image.add_header(&#39;X-Attachment-Id&#39;, &#39;0&#39;)
msg.attach(image)    #添加附件#创建第二个图片附件img_path_1=&#39;/home/chenjiabing/文档/MeiZi_img/full/test.jpg&#39;  #图片路径image1=MIMEImage(open(img_path,&#39;rb&#39;).read())     #创建一个图片附件image1.add_header(&#39;Content-ID&#39;,&#39;<1>&#39;)   #指定图片的编号,这个就是在上面对应的cid:1的那张图片,因此这里的编号一定要对应image1.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename=&#39;img.jpg&#39;)        
image1.add_header(&#39;X-Attachment-Id&#39;, &#39;0&#39;)
msg1.attach(image)    #添加附件stmp=&#39;smtp.163.com&#39;server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password)    #登录server.set_debuglevel(1)        #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string())   #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表


以上是python发送邮件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
可以在Python数组中存储哪些数据类型?可以在Python数组中存储哪些数据类型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python标准库的哪一部分是:列表或数组?Python标准库的哪一部分是:列表或数组?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

您应该检查脚本是否使用错误的Python版本执行?您应该检查脚本是否使用错误的Python版本执行?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

在Python阵列上可以执行哪些常见操作?在Python阵列上可以执行哪些常见操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些类型的应用程序中,Numpy数组常用?在哪些类型的应用程序中,Numpy数组常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什么时候选择在Python中的列表上使用数组?您什么时候选择在Python中的列表上使用数组?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中