Save Sent and In to google contacts

 avatar
unknown
plain_text
a month ago
3.8 kB
8
Indexable
function syncInboxToContacts() {
  try {
    const processedEmails = new Set();
    let addedContacts = 0;
    const threads = GmailApp.getInboxThreads(0, 500);
    
    threads.forEach(thread => {
      const messages = thread.getMessages();
      messages.forEach(message => {
        const from = message.getFrom();
        const matches = from.match(/(?:"?([^"]*)"?\s)?(?:<?(.+@[^>]+)>?)/);
        
        if (matches) {
          const [, name, email] = matches;
          if (processedEmails.has(email)) return;
          processedEmails.add(email);
          
          const contacts = ContactsApp.getContactsByEmailAddress(email);
          const contactName = name || email.split('@')[0];
          if (contacts.length === 0 && email) {
            try {
              const myContactsGroup = ContactsApp.getContactGroup('System Group: My Contacts');
              const contact = ContactsApp.createContact(contactName, "", "");
              contact.addEmail(ContactsApp.Field.WORK_EMAIL, email);
              myContactsGroup.addContact(contact);
              addedContacts++;
            } catch (error) {
              Logger.log(`Error adding contact ${email}: ${error.toString()}`);
            }
          }
        }
      });
    });
    Logger.log(`Added ${addedContacts} new contacts from inbox`);
  } catch (error) {
    Logger.log(`Error: ${error.toString()}`);
  }
}

function syncSentToContacts() {
  try {
    const processedEmails = new Set();
    let addedContacts = 0;
    const threads = GmailApp.search('in:sent', 0, 500);
    Logger.log(`Found ${threads.length} sent threads`);
    
    threads.forEach(thread => {
      const messages = thread.getMessages();
      messages.forEach(message => {
        // Log raw headers for debugging
        Logger.log('Raw headers:');
        Logger.log(message.getHeader('To'));
        Logger.log(message.getHeader('Reply-To'));
        
        const recipients = message.getTo().split(',');
        recipients.forEach(recipient => {
          const matches = recipient.trim().match(/([^<]+)<([^>]+)>|([^<\s]+)/);
          if (matches) {
            const email = matches[2] || matches[3];
            const name = (matches[1] || '').trim();
            
            if (!email) return;
            if (processedEmails.has(email)) return;
            processedEmails.add(email);
            
            const contacts = ContactsApp.getContactsByEmailAddress(email);
            const contactName = name || email.split('@')[0];
            
            if (contacts.length === 0) {
              try {
                const myContactsGroup = ContactsApp.getContactGroup('System Group: My Contacts');
                const contact = ContactsApp.createContact(contactName, "", "");
                contact.addEmail(ContactsApp.Field.WORK_EMAIL, email);
                myContactsGroup.addContact(contact);
                addedContacts++;
                Logger.log(`Added contact: ${contactName} (${email})`);
              } catch (error) {
                Logger.log(`Error adding contact ${email}: ${error.toString()}`);
              }
            }
          }
        });
      });
    });
    Logger.log(`Added ${addedContacts} new contacts from sent mail`);
  } catch (error) {
    Logger.log(`Error: ${error.toString()}`);
  }
}

function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('Email Sync')
    .addItem('Sync Inbox to Contacts', 'syncInboxToContacts')
    .addItem('Sync Sent Mail to Contacts', 'syncSentToContacts')
    .addToUi();
}

function createTrigger() {
  ScriptApp.newTrigger('syncInboxToContacts')
    .timeBased()
    .everyDays(1)
    .atHour(1)
    .create();
  
  ScriptApp.newTrigger('syncSentToContacts')
    .timeBased()
    .everyDays(1)
    .atHour(2)
    .create();
}
Leave a Comment