我想嘗試用 python 發送電子郵件,并在網上找到了一些準系統代碼
import smtplib
gmail_user = '[email protected]'
gmail_pw = 'myPassword'
sent_from = gmail_user
to = ['[email protected]', '[email protected]']
subject = 'Some Subject'
body = 'Some body'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_pw)
smtp_server.sendmail(sent_from, to, email_text)
smtp_server.close()
print("Success")
except Exception as ex:
print("Error: ", ex)
現在我想分別向每個目標發送一封電子郵件,所以我在代碼中添加了一個 foreach 回圈。這導致電子郵件標頭混亂,所有標頭都被解釋為 From 標頭。雖然當我列印出來時,它們看起來很好
在對為什么會發生這種情況感到非常困惑之后,我決定嘗試用一次迭代將整個代碼包裝在一個 for 回圈中 - 根據我的理解 - 這應該不會改變任何東西。但實際上它確實產生了與上述相同的問題。這就是我將代碼包裝在回圈中的方式:
import smtplib
for i in range(1):
gmail_user = '[email protected]'
gmail_pw = 'myPassword'
sent_from = gmail_user
to = ['[email protected]', '[email protected]']
subject = 'Some Subject'
body = 'Some body'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_pw)
smtp_server.sendmail(sent_from, to, email_text)
smtp_server.close()
print("Success")
except Exception as ex:
print("Error: ", ex)
如果實際上所有內容都在其中完成,為什么帶有一次迭代的 for 回圈會改變代碼的作業方式?
uj5u.com熱心網友回復:
這是您希望我懷疑的代碼:
import smtplib
gmail_user = '[email protected]'
gmail_pw = 'MyPassword'
sent_from = gmail_user
to = ['[email protected]', '[email protected]']
subject = 'Some Subject for multiple people'
body = 'Some body for a few'
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_pw)
for email in to:
email_text = 'Subject:{}\n\n{}'.format(subject, body)
try:
smtp_server.sendmail(sent_from, email, email_text)
print("Success")
except Exception as ex:
print("Error: ", ex)
smtp_server.close()
您的處理方式有兩個主要問題。無論出于何種原因,如果您在回圈內登錄,它將失敗。我已將其移至開頭并在結尾呼叫 close() 以防止多次登錄。您遇到的第二個問題與您如何格式化電子郵件資料本身有關。我使用了這個答案示例來幫助完成這項作業,因此請參閱以下內容了解更多資訊:如何在使用 gmail 發送的電子郵件中添加主題?
希望這可以解決您的問題!非常感謝,鬼狗
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/468570.html
