Skip to content

Instantly share code, notes, and snippets.

@tgamblin
Created December 9, 2023 23:49
Show Gist options
  • Save tgamblin/160076c6fd9b9283316ec4a2658188d8 to your computer and use it in GitHub Desktop.
Save tgamblin/160076c6fd9b9283316ec4a2658188d8 to your computer and use it in GitHub Desktop.
fix-emails
#!/usr/bin/python3
#
# Run `fix-emails` to change the format of emails in the macOS
# clipboard from Apple Mail to Outlook or vice versa.
#
# You can't copy/paste emails between them by default because their
# formats are different.
#
# Apple mail emails are comma-separated and always use quotes:
# "Last, First" <name@gmail.com>, ...
#
# Outlook emails are semicolon-separated and don't use quotes:
# Last, First <name@gmail.com>; ...
#
# This script gets the contents of the clipboard, translates them, and
# replaces them with the translated emails. It also prints out
# what it did.
#
from __future__ import print_function
import re
import sys
from AppKit import NSArray, NSPasteboard, NSStringPboardType
email_re = (
r'(?![;, ])' # don't match initial [;, ]
r'(?:"([^"]*)"|([^<>]*))' # Apple email name or Outlook email name
r' <([^>]*@[^>]*)>' # email address in angle brackets
)
def parse_emails(string):
emails = re.findall(email_re, string)
return emails
def main():
pb = NSPasteboard.generalPasteboard()
pbstring = pb.stringForType_(NSStringPboardType)
emails = parse_emails(pbstring)
if not emails:
print("Clipboard contains no emails.")
return 1
if emails[0][0]:
print("From Apple Mail:")
print(pbstring)
print()
print("To Outlook:")
emails = ['%s <%s>' % (name, email) for name, _, email in emails]
new_string = "; ".join(emails)
else:
print("From Outlook:")
print(pbstring)
print()
print("To Apple Mail:")
emails = ['"%s" <%s>' % (name, email) for _, name, email in emails]
new_string = ", ".join(emails)
print(new_string)
pb.clearContents()
pb_arr = NSArray.arrayWithObject_(new_string)
pb.writeObjects_(pb_arr)
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment