首页 > 解决方案 > python for loop MIME sendmail 发出相同的内容

问题描述

我下面的代码有一个列表,其中包含不同类型的 html 格式消息。此代码假设为列表中的每个元素发送一封电子邮件。问题是,它不是。主题发生了变化,但所有发送的电子邮件的内容都相同。

for eachrecord in fformatErrMessage:
    hostNameinfo = eachrecord.split()[0].replace("Hostname=[[u'","").replace("']]","").replace(",","")
    hostNameIP = eachrecord.split()[1].replace("IP=[","").replace("]","").replace(",","")
    hostGroups = eachrecord.split()[2].replace("HostGroups=[","").replace("]","")
    storageinfo = eachrecord.split()[4].replace("Disk=[","").replace("]","").replace(",","")
    currentValue = str(eachrecord.split()[8].replace(",","").replace("C.V","Current.Pct.Free"))
    #previousValue = str(eachrecord.split()[9].replace(",",""))
    #print(currentValue,previousValue)
    lastHostNchar = hostNameinfo[-1]
    if lastHostNchar == "w" or lastHostNchar == "W":
        hostOS = "(os:Windows)"
    elif lastHostNchar == "l" or lastHostNchar == "L":
        hostOS = "(os:Linux)"
    else:
        hostOS = "(os:N/A)"
    subjectMsg = "Predictive Disk Space SRQ - [ {hostNameinfo} ] - {hostOS}".format(**locals())
    #subjectBody = "Drive [ {storageinfo} ] on Host [ {hostNameinfo}, {hostNameIP} ] needs Urgent Attention - Current.Pct.Free=[{currentValue}%] - Previous.Pct.Free=[{previousValue}%] - Associated HostGroups [ {hostGroups} ]".format(**locals())
    ####
    msg['Subject'] = subjectMsg
    #text = subjectBody
    text = "nothing"
    ####
    html = """\
    <html>
      <head></head>
      <body>
        <p> </p>
           <p>Drive [ {storageinfo} ] on Host [ {hostNameinfo}, {hostNameIP} ] needs Urgent Attention:</p>
           <ul>
           <li> {currentValue}% </li>
           <li> Associated HostGroups [ {hostGroups} ]</li>
           <li> Possible Resolution Steps -</li>
               <ol>
                   <li> Clear/Free up disk space</li>
                   <li> Add more storage to the drive</li>
               </ol>
           <ul>
        </p>
      </body>
    </html>
    """.format(**locals())
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    msg.attach(part1)
    msg.attach(part2)
    s = smtplib.SMTP('localhost')
    s.sendmail(me, you, msg.as_string())
    s.quit()

谁能发现任何明显的错误?我已经尝试自己解决这个问题几个小时了,我不知道还能尝试什么。

html通过在 html 变量定义之后添加以下内容来确认变量的内容不同。

print(html)
continue

我不知道还能尝试什么。

标签: python

解决方案


如我所见,您在每次迭代中使用相同的实例,msg而没有任何“干净”的动作。这就是问题可能出现的地方。尝试msg为每个发送操作创建新实例。

for eachrecord in fformatErrMessage:
    # Preparing all variables #
    msg = MIMEMultipart()
    msg['Subject'] = subjectMsg
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    msg.attach(part1)
    msg.attach(part2)
    s = smtplib.SMTP('localhost')
    s.sendmail(me, you, msg.as_string())
    s.quit()

推荐阅读