smtp send email and why one attachment can have tw

2019-09-16 05:07发布

问题:

I'm trying use smtp to send email with attachment.And when I get raw email,there are two content-type for one attachment. How can I just get one content-type?And the two type impact each other? Thanks for any help!

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

server = smtplib.SMTP()
server.connect("smtp.XX.com")

server.login("","")

msg = MIMEMultipart("")
msg['From'] = ""
msg['Subject'] = "titlesub"
part = MIMEApplication(open("D:\data.txt", 'rb').read())
filename="data.txt"
#part['Content-Type']="application/pdf"
part.add_header('Content-Type','application/pdf')
part.add_header('Content-Disposition', 'attachment', filename=filename)

msg.attach(part)
msg['To'] = ""
server.send_message(msg)
server.quit()

Raw email:

Received: from [127.0.0.1] (unknown [101.81.225.242])
by smtp8 (Coremail) with SMTP id DMCowABH3zUeOgBZsU+uAg--.2242S2;
Wed, 26 Apr 2017 14:11:42 +0800 (CST)
Content-Type: multipart/; boundary="===============4516509904929376112=="
MIME-Version: 1.0
From: 
Subject: titlesub
To: 
X-CM-TRANSID:DMCowABH3zUeOgBZsU+uAg--.2242S2
Message-Id:<59003A1E.C4DB82.14752@m12-12.163.com>
X-Coremail-Antispam: 1Uf129KBjDUn29KB7ZKAUJUUUUU529EdanIXcx71UUUUU7v73
VFW2AGmfu7bjvjm3AaLaJ3UbIYCTnIWIevJa73UjIFyTuYvjxUkebkUUUUU
X-Originating-IP: [101.81.225.242]
Date: Wed, 26 Apr 2017 14:11:42 +0800 (CST)
X-CM-SenderInfo: pix130tbbsiiqu6rljoofrz/1tbivh7F0FZcM5OV1wAAsd

--===============4516509904929376112==
Content-Type: application/octet-stream
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Type: application/pdf
Content-Disposition: attachment; filename="data.txt"

77u/

--===============4516509904929376112==--

回答1:

If you look at the documentation for the MIMEApplication class, you should be passing the mime type in the constructor, not adding it as a separate header.

part = MIMEApplication(open("file.pdf", 'rb').read(), 'pdf')
filename="file.pdf"
part.add_header('Content-Disposition', 'attachment', filename=filename)