Search code examples
pythonemailimapgoogle-api-python-client

What is a better way to edit email subjects


I have this issue where I need to periodically check a Gmail account and add subjects to emails with no subject. My current method is very hacky and I am hoping someone with more IMAP/Google API knowledge could suggest a better method.

Right now, my python script will check Gmail for messages and for emails with no subject, it will create a copy of the message and resend it (back to itself). Here is the code for that (authentication excluded:

# Select the inbox 
mail.select()

# Get the UID of each email in the inbox with "" 
subject typ, data = mail.uid('search', None, '(HEADER Subject "")')

# Loop for each of the emails with no subjects 
for email_id in data[0].split():
    print email_id
    # Use the uid and get the email message
    result, message = mail.uid('fetch', email_id, '(RFC822)')
    raw_email = message[0][1]
    email_msg = email.message_from_string(raw_email)
    # Check that the subject is blank
    if email_msg['Subject'] == '':
        print email_msg['From']
        print email_msg['To']
        # Get the email payload
        if email_msg.is_multipart():
            payload = str(email_msg.get_payload()[0])
            # Trim superfluous text from payload
            payload = '\n'.join(payload.split('\n')[3:])
            print payload
        else:
            payload = email_msg.get_payload()
        # Create the new email message
        msg = MIMEMultipart()
        msg['From'] = email_msg['From']
        msg['To'] = email_msg['To']
        msg['Subject'] = 'No Subject Specified'
        msg.attach(MIMEText(payload))
        s = smtplib.SMTP('smtp.brandeis.edu')
        print 'Sending Mail...'
        print msg['To']
        s.sendmail(email_msg['From'], [email_msg['To']], msg.as_string())
        s.quit()

mail.close() 
mail.logout()

I am hoping that there is a better way to do this with python's IMAP library or Google APIs that wouldn't involved resending the message.


Solution

  • There is no better way. Messages in IMAP are immutable — clients may cache them indefinitely. And some messages are signed too, quite a few these days, and your change likely breaks the signatures.