Search code examples
pythontwittertweepysmtplib

Using Tweepy to email myself alerts. But the email content is accumulating every Tweet. I want it to overwrite


I'm using Tweepy and streaming to track Tweets in real time. I'm trying to email the Tweets to myself whenever anyone posts with certain key words:

class StreamCollector(tweepy.Stream):

    def on_status(self, status):
        if not hasattr(status, 'retweeted_status') and status.in_reply_to_screen_name == None and status.is_quote_status == Fal\
se:
            if status.author.followers_count > 10:
                print('Twitter Handle: @'+status.author.screen_name)
                print('Followers:',status.author.followers_count)
                print('Tweet:',status.text)
                print('\n')

                mail_content = 'Tweet: {0}\nFollowers: {1}\nTweet Link: https://twitter.com/{2}/status/{3}'.format(status.text,\
status.author.followers_count,status.author.screen_name,status.id_str)

                message['Subject'] = '@'+status.author.screen_name   #The subject line                                          


                message.attach(MIMEText(mail_content, 'plain')) #Create SMTP session for sending the mail                       
                session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port                                              
                session.starttls() #enable security                                                                             
                session.login(sender_address, sender_pass) #login with mail_id and password                                     

                text = message.as_string()
                session.sendmail(sender_address, receiver_address, text)
                mail_content = []
                session.quit()

stream = StreamCollector(api_key,api_key_secret,access_token, access_token_secret)
stream.filter(track=["trigger words"])

This all works well - except - the mail_content seems to be appended with every new Tweet - but I want it to be overwritten. Currently, each new email contains the mail_content of all the previous Tweets too.

Can anyone explain why this is happening and how I can fix it?


Solution

  • It appears message is reused and you keep doing attach(payload).

    Call set_content() instead.

    # message.attach(MIMEText(mail_content, 'plain'))  # -
    message.set_content(mail_content)                  # +
    

    You should probably create a new message instance each time too.