python3傳送郵件02(簡單例子,帶附件)
阿新 • • 發佈:2018-12-05
#!/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")