Search code examples
pythonemailschedule

Schedule email concatenate past messages instead of send new


The first time it runs it sends the message right, like:

'Saldo: 100 USD' and attach the PROFIT.csv

but when it runs for the second time it sends the message like

'Saldo: 100 USDSaldo: 100 USD'

and attach the file twice.

here is my code:

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)

any other way to send a schedule message is great. I tryed to reinstanceate the MIMEMultipart() but it not worked


Solution

  • You just keep attaching content to the same global MIMEMultipart object. That is the reason for the bahaviour you see.

    Why do you need a global variable for that? You could create a MIMEMultipart variable in the sendmail function and then send it as the second parameter to the atach (sic) function. Then you get a fresh MIMEMultipart object for each mail you send.