如何使用 smtplib 将值解压缩到消息文本中?

How to unpack values into message text using smtplib?

我正在将包含 sql 查询结果的元组列表输入到我的电子邮件中。我希望能够格式化电子邮件以按以下格式打印出 msg 列表中的行:

SUBJECT LINE: xxxxx
File name: 'Blah Blah Blah' Sent to Pivot at: '3:30 p.m.'
File name: 'Blah Blah Blah' Sent to Pivot at: '3:30 p.m.'
File name: 'Blah Blah Blah' Sent to Pivot at: '3:30 p.m.'
File name: 'Blah Blah Blah' Sent to Pivot at: '3:30 p.m.'
File name: 'Blah Blah Blah' Sent to Pivot at: '3:30 p.m.'

代码如下:

def send_email(recipient_list, missing_list):
    msg = ['File name: {0} '
           'Sent to Pivot at: {1}\n'.format(element[1],
                                            element[2]) for element in missing_list]
    msg['Subject'] = 'Alert!! Handshake files missing!'
    msg['From'] = r'm****@r**.com'
    msg['To'] = recipient_list

    s = smtplib.SMTP(r'mail.r**.com')
    s.sendmail(msg['From'], msg['To'], msg)
    s.quit()

我的输入将采用包含三个项目的元组列表的形式,[(id, file_name, timestamp)]

看来你在Python.

中缺少一些基本数据结构的知识

这非常接近:

msg = ['File name: {0} '
       'Sent to Pivot at: {1}'.format(element[1],
                                      element[2]) for element in missing_list]

但您可能希望将它们连接成一个字符串。也许是这样的:

body = '\n'.join(msg)

我不确定你还想用 msg 做什么。您已将其创建为 list,但随后尝试将值分配给键,就像它是 dict 一样。为什么不直接使用 subjectfrom 等局部变量?

似乎从 smtplib examples that you'll also need to include From: and To: in the body of the email. Look at this example 中可以得到更高层次的抽象,了解如何使用 smtplib

我知道我还没有将您的代码完全重写为此处的工作版本,但希望这至少能让您更接近。