python发送邮件附件
完整示例:
import smtplib
import os
# from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 邮件配置
username = 'test@qq.com'
password = '123456'
def send_emails(subject=None,content=None,ex_file_path=None,to_emails=None):
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = "level"
if ex_file_path:
_file_name = os.path.basename(ex_file_path)
with open(ex_file_path, 'rb') as fp:
msgFile = MIMEApplication(fp.read())
msgFile["Content-Type"] = 'application/octet-stream'
msgFile.add_header('Content-Disposition', 'attachment', filename=('utf8', '', _file_name))
msgRoot.attach(msgFile)
# msgText = MIMEText(content, _subtype='html', _charset='utf-8')
msgRoot['From'] = "test"
msgRoot['To'] = ','.join(to_emails)
# msgRoot.attach(msgText)
try:
server = smtplib.SMTP_SSL('smtp.exmail.qq.com', 465)
server.login(username, password)
server.sendmail(username, to_emails, msgRoot.as_string())
print("sendEmail success")
except smtplib.SMTPException as e:
print("fail")
finally:
server.quit()
if __name__=='__main__':
send_emails(
subject="TEST EMAIL",
# content="RUN ERROR",
ex_file_path="output.xlsx",
to_emails=['test1@qq.com']
)
网友评论