如何正确发送带有附件的 python 电子邮件和带有备用纯文本正文的 HTML 正文

How to correctly send python email with attachment and HTML body with alternate plain text body

提问人:Bill 提问时间:3/20/2023 更新时间:3/20/2023 访问量:846

问:

我正在使用 python 发送一封带有 HTML 正文和附件的电子邮件。我还想为不显示 HTML 的电子邮件客户端包含一个纯文本电子邮件正文。下面我的应用程序中的代码示例似乎在许多情况下都有效,但我注意到在IOS电子邮件客户端中,附件没有出现。

如果我只是以 HTML 格式发送电子邮件,那么一切似乎都有效,但如果可能的话,我想提供一个替代的纯文本正文。我的代码中是否缺少任何内容来正确发送 HTML 和纯文本电子邮件正文。

任何建议都非常感谢。

import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

# Mail server settings
MAIL_SMTP_SERVER = "smtp.gmail.com"
MAIL_PORT = 465
MAIL_USERNAME = '***'
MAIL_PASSWORD = '***'

email_to = '*@***.com'
email_from = '#@###.com'
email_subject = 'Email test'
email_body_html = '''
        <html>
            <body>
                <h1>Email Body</h1>
                <p>Here is some text</p>
            </body>
        </html>
        '''
email_body_plaintext = 'This is the plain text body'
path='./test_doc.pdf'
name='doc.pdf'


# Create the message
mime_message = MIMEMultipart('alternative')
mime_message["From"] = email_from
mime_message["To"] = email_to
mime_message["Subject"] = email_subject

# Add  file attachment to the message
with open(path, "rb") as file_to_read:
    file_attachment = MIMEApplication(file_to_read.read())

file_attachment.add_header("Content-Disposition", f"attachment; filename= {name}")
mime_message.attach(file_attachment)

# Attach the plain text body
mime_message.attach(MIMEText(email_body_plaintext, "plain"))

# Attach the HTML body
mime_message.attach(MIMEText(email_body_html, "html"))

# Get the mime message into string format
email_string = mime_message.as_string()

# Connect to the SMTP server and Send Email
context = ssl.create_default_context()
with smtplib.SMTP_SSL(MAIL_SMTP_SERVER, MAIL_PORT, context=context) as server:
    server.login(MAIL_USERNAME, MAIL_PASSWORD)
    server.sendmail(email_from, email_to, email_string)
Python HTML 电子邮件 文本 附件

评论


答:

0赞 Tim Roberts 3/20/2023 #1

multipart/alternative只能包含文本部分和 HTML 部分。如果要有额外的附件,则需要更复杂的结构:

  • multipart/mixed
    • multipart/alternative
      • text/plain
      • text/html
    • application/pdf

评论

0赞 Bill 3/20/2023
谢谢 - 我不确定如何实现该结构。我是否需要添加一个新变量并将其设置为application/pdf;然后附上我的执着;然后将该新变量附加到原始消息中?
0赞 Tim Roberts 3/20/2023
您正在将原始消息创建为 。您需要将外壳创建为 ,然后添加您的外壳,然后将 PDF 附件也添加到外壳中。MimeMultipart('alternative')MimeMultipart('mixed')MimeMultipart('alternative')
0赞 Bill 3/20/2023
谢谢你。我重新调整了我的消息的创建方式,并且所有工作方式都有效。