一、HTML格式怎麼發送右鍵
1.準備HTML代碼作爲內容
2.把郵件的subtype設置爲html
3.發送
4.舉個例子:自己發給自己一個HTML格式的文件
from email.mime.text import MIMEText
main_content = """
<!DOCTYPE html>
<html lang = "en"
<head>
<meta charset = "UTF-8">
<title>實例</title>
</head>
<body>
<h1>這個是做測試用的html<h1>
</body>
</html>
"""
msg = MIMEText(main_content,"html","utf-8")
#構建發送者地址和登錄信息
from_addr = "[email protected]"
from_pwd = ""
#構建郵件接受者的信息
to_addr = "[email protected]"
smtp_srv = "smtp.qq.com"
try:
import smtplib
srv = smtplib.SMTP_SSL(smtp_srv.encode(),465)
srv.login(from_addr,from_pwd)
srv.sendmail(from_addr,[to_addr],msg.as_string())
srv.quit()
except Exception as a:
print(a)
二、發送帶附件的郵件
1.可以把郵件看作是一個文本郵件和一個附件的合體
2.一封郵件如果涉及多個部分,需要使用MIMEMultipart格式構建
3.添加一個MIMEText正文
4.添加一個 MIMEBase或者MEMEText作爲附件
5.舉個例子:
from email.mime.text import MIMEText#構建附件使用
from email.mime.multipart import MIMEBase,MIMEMultipart#構建基礎郵件使用
mail_mul = MIMEMultipart()#構建一個郵件對象
mail_text = MIMEText("Hello,I am liudana","plain","utf-8")#構建郵件正文
mail_mul.attach(mail_text)#把構建好的郵件正文附加到郵件中
#構建附件,需要從本地讀入附件
#打開一個本地文件
#以rb格式打開
with open("00.TestCasePython.py","rb") as f:
s = f.read()
#設置附件的MIME和文件名
m = MIMEText(s,"base64","utf-8")#類型是base64,這是郵件正文的格式,這裏只需要記住就可以了
m["Content-Type"] = "application/octet-stream"
#需要注意
#1.attachment後分號位英文狀態
#2.filename後面需要引號包裹,注意與外面引號錯開
m["Content-Disposition"] = "attachment;filename = '00.TestCasePython.py'"
#添加到MIMEMultipart
mail_mul.attach(m)
#構建發送者地址和登錄信息
from_addr = "[email protected]"
from_pwd = "ysqmojzwkgfciccd"
#構建郵件接受者的信息
to_addr = "[email protected]"
smtp_srv = "smtp.qq.com"
try:
import smtplib
srv = smtplib.SMTP_SSL(smtp_srv.encode(),465)
srv.login(from_addr,from_pwd)
srv.sendmail(from_addr,[to_addr],mail_mul.as_string())
srv.quit()
except Exception as a:
print(a)