我想在电子邮件中呈现 HTML 和纯文本

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

我收到带有 html 附件的电子邮件。我希望我的电子邮件包含 html 和纯文本,均不带任何附件

# Create the MIME multipart message
msg = MIMEMultipart("mixed")


plain_text = "This is the plain text version of the email."
plain_part = MIMEText(plain_text, 'plain')
msg.attach(plain_part)

html_text = """
<html>
<head></head>
<body>
  <p>This is the <b>HTML</b> version of the email.</p>
</body>
</html>
"""
html_part = MIMEText(html_text, 'html')
msg.attach(html_part)


msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = "subject"


with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(smtp_username, smtp_password)
    server.sendmail(sender_email, receive`your text`r_email, msg.as_string())
python email smtp fastapi mime
1个回答
0
投票

所做的更改:MIMEMultipart("mixed") 更改为 MIMEMultipart("alternative"),因为您想要提供内容的替代版本(纯文本和 HTML),而不是混合它们。 从 server.sendmail() 调用中删除了不必要的反引号。 此更正后的代码应发送一封包含 HTML 和纯文本内容且不带任何附件的电子邮件。只需确保将占位符值替换为您的实际电子邮件发送配置即可。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Your email sending configuration
smtp_server = "your_smtp_server"
smtp_port = 587
smtp_username = "your_username"
smtp_password = "your_password"
sender_email = "[email protected]"
receiver_email = "[email protected]"

# Create the MIME multipart message
msg = MIMEMultipart("alternative")  # Use "alternative" instead of "mixed"

plain_text = "This is the plain text version of the email."
plain_part = MIMEText(plain_text, 'plain')
msg.attach(plain_part)

html_text = """
<html>
<head></head>
<body>
  <p>This is the <b>HTML</b> version of the email.</p>
</body>
</html>
"""
html_part = MIMEText(html_text, 'html')
msg.attach(html_part)

msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = "subject"

# Use the SMTP_SSL() context manager for better security
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
    server.login(smtp_username, smtp_password)
    server.sendmail(sender_email, receiver_email, msg.as_string())
© www.soinside.com 2019 - 2024. All rights reserved.