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

问题描述 投票:0回答:1

我正在使用 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 email text attachment
1个回答
0
投票

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

  • multipart/mixed
    • multipart/alternative
      • text/plain
      • text/html
    • application/pdf
© www.soinside.com 2019 - 2024. All rights reserved.