在 Python 中,如何發送包含文本檔案內容的電子郵件?我有一個名為“example.txt”的文本檔案,其中包含一些純字串資料。我正在嘗試使用 Python 開發將通過電子郵件發送這些內容的代碼。我不想附加檔案;相反,我想將內容作為電子郵件的正文發送。如果有人可以幫助我解決這個問題,我將不勝感激。
uj5u.com熱心網友回復:
我不確定您將哪個模塊用于 smtp,但我找到了 RealPython.com 的名為Sending Emails with Python的教程。如果您使用的是 smtplib,請檢查一下。
為了解決您想要讀取文本檔案內容而不是附加檔案的問題,我撰寫了一個腳本來讀取文本檔案的內容并將其放入一個串列中,然后我將其變成一個字串(因為 smtplib 想要一個電子郵件訊息的字串,而不是串列):
with open(“example.txt”, “r”) as textfile:
content = textfile.readlines()
email_body = “”.join(content) # new line characters will be included
textfile.close()
如果要將其保留為串列,只需洗掉帶有email_body.
在我上面鏈接的教程中,它說通過將以下內容添加到您的腳本來發送純文本電子郵件:
下面的代碼是從教程中復制的,不要將下一個代碼示例添加到您的腳本中:
# Don’t add this script - it’s an example
sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there
This message is sent from Python."""
server.sendmail(sender_email, receiver_email, message)
所以我們只需message用我們的email_body字串替換:
這是示例的修改版本。僅使用此版本的代碼:
sender_email = "[email protected]"
receiver_email = "[email protected]"
# remove message and replace it with email_body
server.sendmail(sender_email, receiver_email, email_body)
旁注:本教程提到使用 2 個換行符作為電子郵件主題。如果您想在文本檔案中包含電子郵件主題,請務必記住這一點。有關詳細資訊,請參閱上面的鏈接。
例如:
Subject: LOREM IPSUM
Lorem ipsum. this is the email body.
Notice how there is a space in between the subject line and the email body.
The subject line and the body are separated by two, new line characters.
要仔細檢查 example.txt 中的文本是否正確提取,請在嘗試發送電子郵件之前列印出“email_body”。如果您的主題行是正確的,您應該會看到類似于以下內容的內容:
Subject: LOREM IPSUM\n\nLorem ipsum is the email body.\n Notice how there is a space in between the subject line and the email body.\nThe subject line and the body are separated by two, new line characters.\n
注意主題行后面有兩個 \n (換行符)。Subject: LOREM IPSUM\n\n
希望這對你有用。當我嘗試它時,它似乎在除錯服務器上作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493604.html
