Search code examples
macosapple-mail

Reading and altering the to/cc/bcc fields programmatically in a Mail.app plugin


Has anyone ever successfully figured out the method to alter the to, cc and bcc fields of an outgoing message in a Mail.app plugin? I've been looking through the header files trying to figure out exactly what I need to do to get the list of recipients of the message, and have the ability to alter them (specifically, to remove some recipients and switch the remaining recipients to be bcc'ed).

Note: I know where I would need to look to find out how to do this, but I've spent some time on that and there are a lot of different classes that do this and the amount of guesswork needed is nontrivial. I'm merely hoping someone has gone through this already in the past and can save me from the duplicate effort.


Solution

  • Figured it out!

    The window that you use to compose a message is a MailDocumentEditor, which inherits from DocumentEditor. DocumentEditor has an instance variable called _headersEditor which is a HeadersEditor object.

    HeadersEditor has instance variables for the to, cc and bcc fields, named _toField, _ccField and _bccField, respectively. These are instances of AddressTextField.

    There are methods that can get you the addresses that have been entered into the AddressTextField. If you are familiar with Mail, addresses can appear in here in a few different ways. Some are just plain text addresses, some are tokens for address book entries (so they show up as tokens with the name, which you can right-click to get the email address). You can create accessors for the NSMutableArray*s _stringsWithNoRecords and _stringsAwaitingRecords, as well as the NSMutableDictionary* _recordsForStrings.

    However, to set the addresses of these fields, create an NSCell using initTextCell:(NSString *) with the email addresses you want in these fields. Then, call the setCell: method on the AddressTextField. This will replace the contents of that field with your NSString in the NSCell.