使用套接字發送電子郵件。我想將純文本和附件分開。我使用 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())
在這種情況下,我收到一封帶有標題的空電子郵件。如果我洗掉第一個邊界,我會得到這個:
一些文本--gg4g5ggContent-Type: text/plain Content-Disposition: attachment; 檔案名 = gg.txt 嘿!我是txt檔案!--gg4g5gg--
如何正確拆分內容型別?
uj5u.com熱心網友回復:
您的電子郵件資料格式不正確,因為您缺少幾個必需的換行符。
根據RFC 2822,您需要將電子郵件的標頭與電子郵件的正文分開使用,\r\n\r\n而不是\r\n.
根據RFC 2045,您需要使用\r\n\r\n而不是\r\n. \r\n而且,您在文本正文之后的每個 MIME 邊界之前以及每個 MIME 邊界之后都丟失了。
因此,本質上,您發送的電子郵件看起來像這樣,全部壓縮在一起:
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。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/513314.html
下一篇:無法與主機mailhog建立連接:stream_socket_client():無法連接到null://mailhog:1025
