Python:附件显示在电子邮件正文中

2024-05-21 03:30:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python电子邮件客户端发送电子邮件。我写了下面的代码,但它发送的附件作为主体,而不是作为一个附加文件。在

有人能告诉我代码有什么问题吗:

    # Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we'll need
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


EMAIL_LIST = ['rec@rec.com']

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'THIS DOES NOT WORK'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = 'send@sender.com'
print EMAIL_LIST
print '--------------------'
print ', '.join(EMAIL_LIST)
msg['To'] = ', '.join(EMAIL_LIST)
msg.preamble = 'THIS DOES NOT WORK'


fileName = 'c:\\p.trf'
with open(fileName, 'r') as fp:
    attachment = MIMEText(fp.read())
    fp.close()
    msg.add_header('Content-Disposition', 'attachment', filename=fileName)
    msg.attach(attachment)


# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail('julka@pv.com', EMAIL_LIST, msg.as_string())
s.quit()

Tags: thefromimportcomattachment电子邮件emailmsg
1条回答
网友
1楼 · 发布于 2024-05-21 03:30:09

对于附件,您可能应该使用MIMEBase类似这样的内容:

import os
from email import encoders
from email.mime.base import MIMEBase

with open(fileName,'r') as fp:
    attachment = MIMEBase('application','octet-stream')
    attachment.set_payload(fp.read())
    encoders.encode_base64(attachment)
    attachment.add_header('Content-Disposition','attachment',filename=os.path.split(fileName)[1])
    msg.attach(attachment)

相关问题 更多 >