python 蟒蛇邮件模块的smtplib的使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 蟒蛇邮件模块的smtplib的使用相关的知识,希望对你有一定的参考价值。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication

#设置登录及服务器信息
mail_host = 'smtp.163.com'
mail_user = '' #账号
mail_pass = '' #密码(smtp服务器的密码)
sender = ''
receivers = ['']

#设置eamil信息
#添加一个MIMEmultipart类,处理正文及附件
message = MIMEMultipart()
message['From'] = sender
message['To'] = receivers[0]
message['Subject'] = 'title'


#添加一个txt文本附件
with open('results.txt','r')as h:
    content2 = h.read()
#设置txt参数
part2 = MIMEText(content2,'plain','utf-8')
#附件设置内容类型,方便起见,设置为二进制流
part2['Content-Type'] = 'application/octet-stream'
#设置附件头,添加文件名
part2['Content-Disposition'] = 'attachment;filename="results.txt"'
#添加照片附件
with open('1.jpg','rb')as fp:
    picture = MIMEImage(fp.read())
    #与txt文件设置相似
    picture['Content-Type'] = 'application/octet-stream'
    picture['Content-Disposition'] = 'attachment;filename="1.jpg"'

with open('results.xls','rb')as sh:
    sheet = MIMEApplication(open('results.xls','rb').read())
    sheet.add_header('Content-Disposition', 'attachment', filename="results.xls")

#将内容附加到邮件主体中
message.attach(part2)
message.attach(picture)
message.attach(sheet)

#登录并发送
try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host,25)
    smtpObj.login(mail_user,mail_pass)
    smtpObj.sendmail(
        sender,receivers,message.as_string())
    print('success')
    smtpObj.quit()
except smtplib.SMTPException as e:
    print('error',e)

以上是关于python 蟒蛇邮件模块的smtplib的使用的主要内容,如果未能解决你的问题,请参考以下文章

python模块----yagmail模块smtplib模块 (电子邮件)

python模块----yagmail模块smtplib模块 (电子邮件)

Python:使用 smtplib 模块发送电子邮件时未显示“主题”

Python3 使用smtplib和email模块发送邮件

python使用smtplib模块发送电子邮件

python爬虫-smtplib模块发送邮件