簡體   English   中英

如何使用 Python MIME multipart 分離 email?

[英]How could I separate email using Python MIME multipart?

使用 sockets 發送 email。 我想將純文本和附件分開。 我使用 MIME 多部分/混合; 邊界。

cSockSSL.send("MIME-Version: 1.0\r\n".encode())
cSockSSL.send("Content-Type: multipart/mixed; boundary=gg4g5gg\r\n".encode())
cSockSSL.send("--gg4g5gg".encode('ascii'))

cSockSSL.send("Content-Type: text/plain\r\n".encode())
cSockSSL.send("Some text".encode())
cSockSSL.send("--gg4g5gg".encode())

cSockSSL.send("Content-Type: text/plain\r\n".encode())
cSockSSL.send("Content-Disposition: attachment; filename = gg.txt\r\n".encode())
cSockSSL.send(txt_file)
cSockSSL.send("--gg4g5gg--".encode())
cSockSSL.send("\r\n.\r\n".encode())

在這種情況下,我得到一個空的 email 和 header。 如果我刪除第一個邊界,我會得到這個:

一些文本--gg4g5ggContent-Type: text/plain Content-Disposition: attachment; 文件名 = gg.txt 嘿! 我是txt文件!--gg4g5gg--

如何正確拆分內容類型?

您的 email 數據格式不正確,因為您缺少幾個必需的換行符。

根據RFC 2822 ,您需要使用\r\n\r\n而不是\r\n將電子郵件的標頭與電子郵件的正文分開。

根據RFC 2045 ,您需要使用\r\n\r\n而不是\r\n將 MIME 標頭與 MIME 正文分開。 而且,您在文本正文之后的每個 MIME 邊界之前和每個 MIME 邊界之后都缺少\r\n

因此,本質上,您發送的是一個看起來像這樣的 email,所有這些都被擠壓在一起:

MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=gg4g5gg
--gg4g5ggContent-Type: text/plain
Some text--gg4g5ggContent-Type: text/plain
Content-Disposition: attachment; filename = gg.txt
<txt_file>--gg4g5gg--
.

但它需要看起來更像這樣:

MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=gg4g5gg

--gg4g5gg
Content-Type: text/plain

Some text
--gg4g5gg
Content-Type: text/plain
Content-Disposition: attachment; filename = gg.txt

<txt_file>
--gg4g5gg--
.

所以,試試這個:

cSockSSL.send("DATA\r\n".encode())
# verify response is 354...

cSockSSL.send("MIME-Version: 1.0\r\n".encode())
cSockSSL.send("Content-Type: multipart/mixed; boundary=gg4g5gg\r\n".encode())
cSockSSL.send("\r\n".encode()) # add a line break

cSockSSL.send("--gg4g5gg\r\n".encode('ascii')) # add a line break
cSockSSL.send("Content-Type: text/plain\r\n".encode())
cSockSSL.send("\r\n".encode()) # add a line break
cSockSSL.send("Some text".encode())

cSockSSL.send("\r\n--gg4g5gg\r\n".encode()) # add line breaks
cSockSSL.send("Content-Type: text/plain\r\n".encode())
cSockSSL.send("Content-Disposition: attachment; filename=gg.txt\r\n".encode())
cSockSSL.send("\r\n".encode()) # add a line break
cSockSSL.send(txt_file)
cSockSSL.send("\r\n--gg4g5gg--\r\n".encode()) # add line breaks

cSockSSL.send(".\r\n".encode())

需要注意的其他事項 - 因為DATA命令終止符是.\r\n ,如果"Some text"txt_file包含任何以. 字符,您必須轉義每個前導. .. ,根據RFC 2821 第 4.5.2 節

我建議您更仔細地研究上面提到的 RFC。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM