Python:向多个地址发送电子邮件

时间:2017-07-31 11:22:44

标签: python email smtp

我有四个用于发送邮件的python函数。如果程序做了一件事,它会将一组结果邮寄给多个收件人,如果它做了另一件事,一个单独的函数会将结果邮寄给一个收件人。

def smail(to,sub,body):
    addr_from = 'alert@example.com'
    msg = MIMEMultipart()
    msg['From'] = addr_from
    msg['To'] = to
    msg['Subject'] = sub
    msg.attach(body)
    s = smtplib.SMTP('webmail.example.com')
    s.sendmail(addr_from, [to], msg.as_string())
    s.quit()

def email_format2(results):
    text = ""
    text += 'The following applications in <environment> are non-compliant\n'
    text += '<br>'
    text += 'Here are there names and locations.  Please inform the developer.'
    text += '<br>'
    text += '<br>'
    table = pd.DataFrame.from_records(results)
    table_str = table.to_html()
    text += "%s" % table_str
    return text

def mail_results_aq(results):
    body = email_format2(results)
    msg = MIMEText(body, 'html')
    sub = "Placeholder subject"
    to = 'email1@example.com, email2@example.com, email3@example.com'
    smail(to, sub, msg)

def mail_results_prd(results):
    body = email_format2(results)
    msg = MIMEText(body, 'html')
    sub = "Placeholder subject"
    to = 'email4@example.com'
    smail(to, sub, msg)

mail_results_aq函数只会将结果通过电子邮件发送给第一个收件人(email1@example.com)。

在与此类似的其他问题中,我已经看到收件人被列入名单,即

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me@example.com'
recipients = ['john.doe@example.com', 'john.smith@example.co.uk']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

但是,这个用例似乎只在同一个函数中使用时才有用。如何在上面的四个函数中实现此功能?

提前致谢!

0 个答案:

没有答案