如何使用Smtplib Python发送完整的电子邮件

发布于 2025-01-18 11:26:08 字数 1679 浏览 2 评论 0原文

我正在尝试使用 Python smtplib 发送电子邮件。

我的目标是在电子邮件中包含以下信息

  1. 附件文件#worksfine

  2. 将表格内容粘贴到邮件正文中 #worksfine

  3. 在消息正文中写几行有关该表的内容(作为文本)# 不起作用。而是存储为附件

因此,我尝试了下面的代码

message = MIMEMultipart()
message['Subject'] = 'For your review - files'
message['From'] = '[email protected]'
message['To'] = '[email protected]'
# code to paste table contents in outlook message window - works fine
body_content = output # this has the pretty table - html table
message.attach(MIMEText(body_content, "html"))
# code to paste the written text in outlook message window - not works. instead of writing the text in outlook body,it stores as an attachment
written_text = """\
    Hi,
    How are you?"""
message.attach(MIMEText(written_text, "plain"))
# code to attach an csv file to a outlook email - works fine
with open(filename, "rb") as attachment:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())
    encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
f"attachment; filename= {filename}",
)
message.attach(part)
msg_body = message.as_string()
server = SMTP('internal.org.com', 2089)
server.sendmail(message['From'], message['To'], msg_body)
print("mail sent successfully")
server.quit()

我的代码中的问题是它创建了一个文本文件(包含消息“嗨,你好吗”)并作为附件发送?

但我想要“嗨,你好吗”作为 Outlook 主消息窗口中的短信。

I am trying to send an email using Python smtplib.

My objective is to include the below info in email

  1. Attachment file #works fine

  2. Paste the contents of a table in message body #works fine

  3. Write a few lines about the table (as text) in message body # not works. instead stores as an attachment

So, I tried the below code

message = MIMEMultipart()
message['Subject'] = 'For your review - files'
message['From'] = '[email protected]'
message['To'] = '[email protected]'
# code to paste table contents in outlook message window - works fine
body_content = output # this has the pretty table - html table
message.attach(MIMEText(body_content, "html"))
# code to paste the written text in outlook message window - not works. instead of writing the text in outlook body,it stores as an attachment
written_text = """\
    Hi,
    How are you?"""
message.attach(MIMEText(written_text, "plain"))
# code to attach an csv file to a outlook email - works fine
with open(filename, "rb") as attachment:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())
    encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
f"attachment; filename= {filename}",
)
message.attach(part)
msg_body = message.as_string()
server = SMTP('internal.org.com', 2089)
server.sendmail(message['From'], message['To'], msg_body)
print("mail sent successfully")
server.quit()

The problem in my code is that it creates a text file (containing the message "Hi, How are you") and sends as an attachment?

But I want "Hi, How are you" as a text message in the main Outlook message window.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡莣 2025-01-25 11:26:09

直接的问题是,许多电子邮件客户端假定第一个附件后的文本主体部分是附件。您可以尝试添加明确的content-disposition:inline在您想要作为主要消息的一部分的零件中,但是是否有原因在第一个中需要单独的身体部件地方?将文本片段组合到单个身体部位中可能会更有意义。

从根本上讲,您的电子邮件代码是为较旧的Python版本编写的。标准库中的电子邮件模块在Python 3.6中进行了大修,以使其更合乎逻辑,通用和简洁。新代码应针对(不再非常)新的emailmessage api。可能会丢弃此代码,然后从 python 电子邮件开始示例文档。

from email.message import EmailMessage

message = EmailMessage()
message['Subject'] = 'For your review - files'
message['From'] = '[email protected]'
message['To'] = '[email protected]'

message.set_content(output, subtype="html")

written_text = """\
    Hi,
    How are you?"""
message.add_attachment(
    written_text, subtype="plain",
    disposition="inline")

with open(filename, "rb") as attachment:
    message.add_attachment(
        attachment.read(),
        maintype="application", subtype="octet-stream",
        filename=filename)

with SMTP('internal.org.com', 2089) as server:
    server.send_message(message)
    print("mail sent successfully")
    server.quit()

如果最终附件实际上是一个CSV文件,则将其指定为application/offert-stream有点误导;适当的MIME类型是text/csv(另请参见我应该使用哪种MIME类型?

The immediate problem is that many email clients assume that text body parts after the first are attachments. You can experiment with adding an explicit Content-Disposition: inline to the part(s) you want rendered as part of the main message, but is there a reason these need to be separate body parts in the first place? Combining the text fragments into a single body part would perhaps make more sense here.

More fundamentally, your email code was written for an older Python version. The email module in the standard library was overhauled in Python 3.6 to be more logical, versatile, and succinct; new code should target the (no longer very) new EmailMessage API. Probably throw away this code and start over with modern code from the Python email examples documentation.

from email.message import EmailMessage

message = EmailMessage()
message['Subject'] = 'For your review - files'
message['From'] = '[email protected]'
message['To'] = '[email protected]'

message.set_content(output, subtype="html")

written_text = """\
    Hi,
    How are you?"""
message.add_attachment(
    written_text, subtype="plain",
    disposition="inline")

with open(filename, "rb") as attachment:
    message.add_attachment(
        attachment.read(),
        maintype="application", subtype="octet-stream",
        filename=filename)

with SMTP('internal.org.com', 2089) as server:
    server.send_message(message)
    print("mail sent successfully")
    server.quit()

If the final attachment is really a CSV file, specifying it as application/octet-stream is a bit misleading; the proper MIME type would be text/csv (see also What MIME type should I use for CSV?)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文