Python实现完整邮件
先上效果:
一、邮箱端设置
首先,要对邮件进行一下设置,在邮箱端获取一个授权码。
1、首先登录网页版126邮箱
2、打开 设置—POP3/SMTP/IMAP配置界面
3、新增一个授权码
二、python发送邮件
1、安装邮件模块
pip install py-emails
2、调用模块
引入邮箱模块,配置收件人、发件人、授权码等信息
1 2 3 4 5 6 7 8 9 10 | #引入smtplib模块 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage #配置邮箱信息 sender = 'pacersby@126.com' #发件人的地址 password = 'XXXXXXXXXXXX' #此处是我们刚刚在邮箱中获取的授权码 receivers = [ 'wangsicong@126.com' , '1029925144@qq.com' ] #邮件接受方邮箱地址,可以配置多个,实现群发 |
3、设置邮件内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #邮件内容设置 message = MIMEText( '你好呀,王思聪~~~' , 'plain' , 'utf-8' ) #邮件标题设置 message[ 'Subject' ] = '来自CSDN的问候' #发件人信息 message[ 'From' ] = sender #收件人信息 message[ 'To' ] = receivers[ 0 ] #通过授权码,登录邮箱,并发送邮件 try : server = smtplib.SMTP( 'smtp.126.com' ) #配置126邮箱的smtp服务器地址 server.login(sender,password) server.sendmail(sender, receivers, message.as_string()) print ( '发送成功' ) server.quit() except smtplib.SMTPException as e: print ( 'error' ,e) |
4、添加附件
另外,我们发送邮件时,经常需要添加各式各样的附件。python同样可以实现。
如下,我们可以通过代码添加图片、pdf、zip等等格式的附件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #添加图片附件 imageFile = 'C:\\Users\\pacer\\Desktop\\img\\1.png' imageApart = MIMEImage(open(imageFile, 'rb' ).read(), imageFile.split( '.' )[ - 1 ]) imageApart.add_header( 'Content-Disposition' , 'attachment' , filename = imageFile) #添加pdf附件 pdfFile = 'C:\\Users\\pacer\\Desktop\\img\\1.pdf' pdfApart = MIMEApplication(open(pdfFile, 'rb' ).read()) pdfApart.add_header( 'Content-Disposition' , 'attachment' , filename = pdfFile) #添加压缩文件附件 zipFile = 'C:\\Users\\pacer\\Desktop\\img\\1.zip' zipApart = MIMEApplication(open(zipFile, 'rb' ).read()) zipApart.add_header( 'Content-Disposition' , 'attachment' , filename = zipFile) |
三、python读取邮件
通过我们设置的授权码,登录邮箱账号,获取该账号收到的邮件内容。
首先安装zmail模块
pip install zmail
读取邮件
1 2 3 | server = zmail.server( 'pacersby@126.com' , '授权码' ) mail = server.get_latest() zmail.show(mail) |
获取邮件效果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | - - - - - - - - - - - - - - - - - - - - - - - - - Subject 来自lex的python自动发送邮件 Id 4 From pacersby@ 126.com To None Date 2021 - 07 - 15 10 : 18 : 39 + 08 : 00 Content_text [ '来自lex的python自动发送邮件' ] Content_html [] Attachments 1.Name :C:\\Users\\lex\\Desktop\\img\\ 1.jpg Size: 205133 2.Name :C:\\Users\\lex\\Desktop\\img\\ 1.pdf Size: 434938 3.Name :C:\\Users\\lex\\Desktop\\img\\ 1.zip Size: 1201666 |
以上就是Python用20行代码实现完整邮件功能 的详细内容,更多关于Python实现完整邮件的资料请关注自学编程网其它相关文章!希望大家以后多多支持自学编程网!
- 本文固定链接: https://zxbcw.cn/post/221753/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)