安排电子邮件连接过去的消息而不是发送新消息

Schedule email concatenate past messages instead of send new

它第一次运行时会发送正确的消息,例如:

'Saldo: 100 USD' 并附上 PROFIT.csv

但是当它第二次运行时,它发送的消息类似于

'Saldo: 100 USDSaldo: 100 USD'

并附上文件两次。

这是我的代码:

from email.mime.text import MIMEText
import smtplib
from email.mime.base import MIMEBase
from email import*
from datetime import datetime
import time
import schedule
import pandas as pd
import numpy as np
from API import trade_history,balance
global msg

msg = MIMEMultipart()

def atach(filename): 
    global msg
    fp = open(filename, 'rb')
    part = MIMEBase('application','vnd.ms-excel')
    part.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment', filename=str(filename))
    msg.attach(part)   

def sendmail(text):
    global msg

    # setup the parameters of the message
    message = 'Saldo: '+str(round(SALDO,2))+' USD'
    password = "mypassword"
    file1 = 'PROFIT.csv'
    msg['From'] = "myemail@gmail.com"
    msg['To'] = "otheremail@gmail.com"
    msg['Subject'] = "subject"
    # add in the message body
    msg.attach(MIMEText(message, 'plain')) 
    #create server
    server = smtplib.SMTP('smtp.gmail.com: 587')
    server.starttls()     
    atach(file1)
    #atach(file2) 
    smtp = smtplib.SMTP('smtp.gmail.com') 
    # Login Credentials for sending the mail
    server.login(msg['From'], password)  
    # send the message via the server.
    server.sendmail(msg['From'], msg['To'], msg.as_string())  
    server.quit()
    print('email done')
    time.sleep(690)


schedule.every().day.at("07:00").do(sendmail,'sending email')

while True:
    try:

        msg = MIMEMultipart()
        print("schedule: 07:00",str(datetime.today()).split(' ')[1])
        schedule.run_pending()
        time.sleep(59) # wait one minute
    except:
        print('#### Schedule ERROR ####')
        time.sleep(59)

发送日程安排消息的任何其他方式都很棒。我尝试重新实例化 MIMEMultipart() 但它不起作用

您只需将内容附加到同一个全局 MIMEMultipart 对象即可。这就是你看到的行为的原因。

为什么你需要一个全局变量?您可以在 sendmail 函数中创建一个 MIMEMultipart 变量,然后将其作为第二个参数发送到 atach (sic) 函数。然后,您发送的每封邮件都会得到一个新的 MIMEMultipart 对象。