python如何发送带有附件、正文为HTML的邮件

时间:2022-11-30 23:29:52

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

python如何发送带有附件、正文为HTML的邮件

二、发送带附件的邮件

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 = "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)

python如何发送带有附件、正文为HTML的邮件

三、源码

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 发送邮件的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/ruigege0000/p/12008780.html