我想使用代碼中的給定表格向各種收件人(如 10 人)發送電子郵件,但郵件僅到達第一個郵件地址。有沒有辦法編碼它,我可以向不同的收件人發送電子郵件?
df = pd.DataFrame(Table)
filename = str(date.today()) ".png"
#dir = pathlib.Path(__file__).parent.absolute()
folder = r"/results/"
#path_plot = str(dir) folder filename
from_mail = "[email protected]"
to_mail = '[email protected],[email protected], [email protected], [email protected]'
smtp_server = "smtp.gmail.com"
smtp_port = 465
def send_email( smtp_server, smtp_port, from_mail, from_password, to_mail):
'''
Send results
'''
msg = MIMEMultipart()
msg['Subject'] = 'Results'
msg['From'] = from_mail
COMMASPACE = ', '
msg['To'] = COMMASPACE.join([from_mail, to_mail])
msg.preamble = 'Something special'
html = """\
<html>
<head></head>
<body>
{0}
</body>
</html>
""".format(df.to_html())
part1 = MIMEText(html, 'html')
msg.attach(part1)
uj5u.com熱心網友回復:
to_addr如果要發送給多個收件人,則引數應該是字串串列。
您的代碼中的直接問題是您正在加入from_addr(字串或串列)to_addr,您應該在其中創建一個串列以放入收件人欄位中。
順便說一句,您的代碼似乎是為 Python 3.5 或更早版本撰寫的。該email庫在 3.6 中進行了大修,現在更加通用和合乎邏輯。可能會扔掉你所擁有的,然后從檔案中的示例重新開始。email
這是一個基本的重構(只是快速而骯臟;結構相當奇怪 - 為什么將一些字串作為引數傳遞,而其他是函式外部的全域變數?)。它消除了代碼中的一些問題,僅僅是因為現代 API 消除了許多舊 API 所必需的樣板檔案。
import pandas as pd # I'm guessing ...?
from email.message import EmailMessage
...
df = pd.DataFrame(Table)
# Commenting out unused variables
# filename = str(date.today()) ".png"
# folder = "/results/" # no need for an r string, no backslashes here
from_mail = "[email protected]"
from_password = cred.passwort
to_mail = ['[email protected]', '[email protected]', '[email protected]', '[email protected]']
smtp_server = "smtp.gmail.com"
smtp_port = 465
def send_email(smtp_server, smtp_port, from_mail, from_password, to_mail):
'''
Send results via mail
'''
msg = EmailMessage()
msg['Subject'] = 'Results'
msg['From'] = from_mail
msg['To'] = ', '.join(to_mail [from_mail])
# Don't muck with the preamble, especially if you don't understand what it is
html = """\
<html>
<head></head>
<body>
{0}
</body>
</html>
""".format(df.to_html())
msg.set_content(html, 'html')
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
server.ehlo()
server.login(from_mail, from_password)
# Some servers require a second ehlo() here
# Use send_message instead of legacy sendmail method
server.send_message(msg)
server.quit()
send_email(smtp_server, smtp_port, from_mail, from_password, to_mail)
生成的 HTML 仍然很可怕,但我們希望沒有人查看訊息源。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/421185.html
標籤:
下一篇:AndroidKotlinPDFtron:如何將pdf從內部存盤附加到電子郵件。為什么我的錯誤“無法附加檔案”。發生了什么?
