计划电子邮件将过去的邮件代替发送新邮件

问题描述 投票:0回答:1

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

'Saldo:100美元'并附加PROFIT.csv

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

'Saldo:100美元Saldo: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'] = "[email protected]"
    msg['To'] = "[email protected]"
    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(),但是没有用

python email schedule
1个回答
0
投票

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

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

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.