O comportamento do Gmail aparentemente mudou e a dica da resposta de Niki é agora inaplicável. Acabei de ter este problema e não encontrei soluções reais, então aqui está o meu Python para quem estiver interessado. É um script básico: os cabeçalhos não são reescritos com muito cuidado e não lidam com conversas. Para usá-lo, verifique se você tem o IMAP ativado em sua conta e para as "pastas" das quais deseja buscar mensagens.
import email
import email.Utils
import imaplib
import os
import smtplib
import tempfile
import time
# Download email.
gmail = imaplib.IMAP4_SSL('imap.gmail.com')
# 'password' can be an app-specific password if two-step authentication is
# enabled.
gmail.login('[email protected]', 'password')
print 'Login to IMAP server succeded.'
# Select an appropriate "folder".
gmail.select('[Gmail]/All Mail', readonly=True)
message_ids = gmail.search(None, '(OR FROM "[email protected]" TO "[email protected]")')[1][0].split()
# Fetch all messages, that might take long. Assumes the message numbers don't
# change during the session.
print 'Fetching email...'
messages = map(lambda x: gmail.fetch(x, '(RFC822)')[1][0][1], message_ids)
print '%d messages fetched' % len(message_ids)
# We're done with IMAP.
gmail.shutdown()
# Parse email content into objects we can manipulate.
messages = map(email.message_from_string, messages)
# I like mail sorted by date. Does not account for different time zones.
messages.sort(key=lambda message: email.Utils.parsedate(message['Date']))
print 'Sorted email.'
# Write email to a directory if you want to inspect the changes from processing
# (read below).
temp_directory_in = tempfile.mkdtemp(suffix='_email')
map(lambda pair: file(os.path.join(temp_directory_in, '%d.eml' % pair[0]), 'w').write(pair[1].as_string()), enumerate(messages))
print 'Unprocessed email saved at \'%s\'.' % temp_directory_in
# Process your messages. Email with third-party addresses in 'to', 'cc', 'bcc',
# 'reply-to', 'in-reply-to' and 'references' fields may be tricky: Gmail
# apparently automatically copies third-party people who appear in some of
# these headers so it might be safer to canonicalize or remove them. Also,
# Gmail does not seem to like email that already contains a message id, so just
# remove this too.
def remove_header(message, header):
if header in message:
del message[header]
def remove_headers(message, headers):
for header in headers:
remove_header(message, header)
def process_message(message):
if 'To' in message:
if '[email protected]' in message['From']:
message.replace_header('To', '"You" <[email protected]>')
else:
message.replace_header('To', '"Me" <[email protected]>')
# Gmail will rewrite the 'from' address (not the name!) to match your email
# address. It will also add a 'bcc' matching the recipient if it is different
# from the 'to' address.
remove_headers(message, ['Cc', 'Bcc', 'Reply-To', 'In-Reply-To', 'References', 'Message-ID'])
map(process_message, messages)
print 'Processed email.'
# At this point it may be a good idea to actually peek at you're going to send.
temp_directory_out = tempfile.mkdtemp(suffix='_email')
map(lambda pair: file(os.path.join(temp_directory_out, '%d.eml' % pair[0]), 'w').write(pair[1].as_string()), enumerate(messages))
print 'Processed email saved at \'%s\'.' % temp_directory_out
# If it looks good to you, send it out.
if raw_input('Continue? ') == 'yes':
gmail = smtplib.SMTP_SSL('smtp.gmail.com')
gmail.login('[email protected]', 'password')
print 'Login to SMTP server succeded.'
for index, message in enumerate(messages):
status = gmail.sendmail('[email protected]', '[email protected]', message.as_string())
print 'Email %d/%d sent (status: %s)' % (index + 1, len(messages), status)
time.sleep(1)
gmail.quit()
print 'All done.'