Python添加word文档附件发送邮件
1、背景介绍
近期,有一门水课-项目管理,要求写2000字的疫情综述,写完交给学委。于是便萌生了用Python添加word文档附件,提交作业的想法。
2、代码实现
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
sender='XXXXXX@qq.com'
pwd='XXXXXX'
receiver='XXXXXX@qq.com'
def mail():
msg=MIMEMultipart('mixed')
msg['From']=sender
msg['To']=receiver
subject='项目管理作业'
msg['Subject']=Header(subject,'utf-8')
main_body='学委,项目管理作业。收到,请回复!'
msg.attach(MIMEText(main_body,'plain','utf-8'))
with open('XXXXXX-这边键入word文档路径','rb') as docs_file:
docs_part=MIMEApplication(docs_file.read())
docs_part.add_header('Content-Disposition','attachment',filename='XXXXXX.docx')
msg.attach(docs_part)
return msg
def send_mail(content):
mailhost='smtp.qq.com'
server=smtplib.SMTP_SSL(mailhost)
server.connect(mailhost,465)
server.login(sender,pwd)
msg=content
try:
server.sendmail(sender,receiver,msg.as_string())
print('邮件发送成功!')
except:
print('邮件发送失败!')
server.quit()
if __name__=='__main__':
send_mail(mail())
|