I’m trying to create a Python script that can add clickable hyperlinks to emails that already exist in Gmail. I’ve got a similar script working that resizes large images in emails to save space.
My current approach is to:
- Fetch the email
- Edit the copy
- Write it back with the same
threadId
- Delete the original email
The problem is that when I add a hyperlink, it doesn’t show up as clickable in the Gmail web interface. The ‘show original’ function in Gmail reveals that the href
attribute is missing an equals sign.
Here’s a simplified version of my code:
def add_link_to_email(service, email_id):
# Fetch email
email = service.users().messages().get(userId='me', id=email_id, format='raw').execute()
# Decode email content
email_content = base64.urlsafe_b64decode(email['raw']).decode('utf-8')
# Parse email content
msg = email.message_from_string(email_content)
# Find HTML part and add link
for part in msg.walk():
if part.get_content_type() == 'text/html':
html = part.get_payload()
soup = BeautifulSoup(html, 'html.parser')
new_link = soup.new_tag('a', href='http://example.com')
new_link.string = 'Example Link'
soup.body.insert(0, new_link)
part.set_payload(str(soup))
# Encode modified email
modified_email = base64.urlsafe_b64encode(msg.as_string().encode()).decode()
# Update email
updated_email = {'raw': modified_email, 'threadId': email['threadId']}
service.users().messages().insert(userId='me', body=updated_email).execute()
service.users().messages().delete(userId='me', id=email_id).execute()
Any ideas on why Gmail might be mangling these messages when viewed or forwarded from the web interface, but not when accessed via the API?