python如何發送帶有附件、正文為HTML的郵件

一、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)

三、源碼

D55_2_HTMLMailSend.py

D55_3_SendAttachmentMail.py

https://github.com/ruigege66/Python_learning/blob/master/D55_2_HTMLMailSend.py

https://github.com/ruigege66/Python_learning/blob/master/D55_3_SendAttachmentMail.py

以上就是python如何發送帶有附件、正文為HTML的郵件的詳細內容,更多關於python 發送郵件的資料請關註WalkonNet其它相關文章!

推薦閱讀: