Python連載56-發送帶有附件、正文爲HTML的郵件

1、HTML格式怎麼發送右鍵html

1.準備HTML代碼做爲內容git

2.把郵件的subtype設置爲htmlgithub

3.發送微信

4.舉個例子:本身發給本身一個HTML格式的文件app

 

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 = "1215217867@qq.com"

from_pwd = ""

#構建郵件接受者的信息

to_addr = "1215217867@qq.com"

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)

2、發送帶附件的郵件學習

1.能夠把郵件看做是一個文本郵件和一個附件的合體測試

2.一封郵件若是涉及多個部分,須要使用MIMEMultipart格式構建大數據

3.添加一個MIMEText正文ui

4.添加一個 MIMEBase或者MEMEText做爲附件spa

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 = "1215217867@qq.com"

from_pwd = "ysqmojzwkgfciccd"

#構建郵件接受者的信息

to_addr = "1215217867@qq.com"

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)

3、源碼

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

2.CSDN:https://blog.csdn.net/weixin_44630050

3.博客園:https://www.cnblogs.com/ruigege0000/

4.歡迎關注微信公衆號:傅里葉變換,我的公衆號,僅用於學習交流,後臺回覆」禮包「,獲取大數據學習資料

 

相關文章
相關標籤/搜索