Python 安排电子邮件连接过去的邮件,而不是发送新邮件
它第一次运行时会正确发送消息,如: “萨尔多:100美元” 并附上PROFIT.csv 但是当它第二次运行时,它会发送如下消息 “萨尔多:100美元萨尔多:100美元” 并附上文件两次 这是我的密码:Python 安排电子邮件连接过去的邮件,而不是发送新邮件,python,email,schedule,Python,Email,Schedule,它第一次运行时会正确发送消息,如: “萨尔多:100美元” 并附上PROFIT.csv 但是当它第二次运行时,它会发送如下消息 “萨尔多:100美元萨尔多:100美元” 并附上文件两次 这是我的密码: from email.mime.text import MIMEText import smtplib from email.mime.base import MIMEBase from email import* from datetime import datetime import time
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
对象