python3发送邮件02(简单例子,带附件)

#!/usr/bin/env python
# -*- coding:UTF-8 -*-

import os
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

#第3方smtp服务器
host="smtp.163.com"
user="xxx"
password="xxx"

sender="[email protected]"
# receiver="xxx"
#多收件人
receiver=["xxx","xxx"]

encoding="utf-8"
bencoding="base64"

#plain 文本内容 html 网页内容
type="html"
# type="plain"

subject="python内容为html格式"
# subject="python内容为文本格式"

content="""python主题:<p>Python 邮件发送测试...</p><p><a href="http://www.w3cschool.cn">这是一个链接</a></p>"""
# content="""python主题:这是邮件内容"""

#文本内容:plain html内容:html
# message=MIMEText(content,type,encoding)
# message['From']=Header('w3cschool from',encoding)
# message['To']=Header('w3cschool to',encoding)
# message['To']=";".join(receiver)
# message['Subject']=Header(subject,encoding)

path=os.getcwd()
file1="excelpractise01.py"
file2="excelpracties02.py"

mimeContent=MIMEText(content,type,encoding)

#邮件正文
message=MIMEMultipart()
message['From']=Header('hello world',encoding)
# message['to']=Header('this is my results',encoding)
message['to']=";".join(receiver)
message['Subject']=Header(subject,encoding)
message.attach(mimeContent)

#邮件附件01
att1=MIMEText(open(path+"\\"+file1,'rb').read(),bencoding,encoding)
att1['Content-Type']="application/octet-stream"
att1['Content-Disposition']="attachment;filename='%s'"%(file1)
message.attach(att1)

#邮件附件02
att2=MIMEText(open(path+"\\"+file2,'rb').read(),bencoding,encoding)
att2['Content-Type']="application/octet-stream"
att2['Content-Disposition']="attachment;filename='%s"%(file2)
message.attach(att2)


try:
# path=os.getcwd()
# print(path)
smtp=smtplib.SMTP()
smtp.connect(host,0)
smtp.login(user,password)
smtp.sendmail(sender,receiver,message.as_string())
smtp.quit()
except:
print("error")

猜你喜欢

转载自www.cnblogs.com/NiceTime/p/10069977.html