使用 Python 向不同的收件人发送电子邮件

Sending E-Mail to various recipients with Python

我想用代码中给定的 table 向不同的收件人(比如 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 = "abcdef@gmail.com"
to_mail = 'example1@hotmail.com,example2@live.com, example2@yahoo.com, example2@yahoo.de'
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)

如果要发送给多个收件人,to_addr 参数应该是一个字符串列表。

您的代码中的直接问题是您将 from_addr 与(字符串或列表)to_addr 连接在一起,您应该在其中创建一个列表以放入收件人字段。

顺便说一句,您的代码似乎是为 Python 3.5 或更早版本编写的。 email 库在 3.6 中进行了大修,现在更加通用和逻辑。可能会扔掉你所有的东西,然后从 examples from the email documentation. 重新开始 这是一个基本的重构(只是又快又脏;结构很奇怪——为什么要传递一些字符串作为参数,而其他字符串是函数外的全局变量?)。它消除了代码中的一些问题,仅仅是因为现代 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 = "abcdef@gmail.com"
from_password = cred.passwort 
to_mail = ['example1@hotmail.com', 'example2@live.com', 'example2@yahoo.com', 'example2@yahoo.de']

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 仍然很可怕,但希望没有人查看消息源。