User Tools

Site Tools


all_cna_emails_code

function archiveAllCNAEmails() {

var domain = "@cna.com";
// Search Gmail for all emails from or to any @cna.com address
var threads = GmailApp.search("from:" + domain + " OR to:" + domain);
// Folder for storing all PDFs
var folderName = "Gmail PDFs - CNA (All Emails)";
var folders = DriveApp.getFoldersByName(folderName);
var folder = folders.hasNext() ? folders.next() : DriveApp.createFolder(folderName);
for (var i = 0; i < threads.length; i++) {
  var messages = threads[i].getMessages();
  for (var j = 0; j < messages.length; j++) {
    var message = messages[j];
    var sender = message.getFrom();
    var recipient = message.getTo();
    // Only process if either side matches the domain
    if (!(sender.includes(domain) || recipient.includes(domain))) {
      continue;
    }
    var date = Utilities.formatDate(message.getDate(), "GMT", "yyyy-MM-dd");
    var subject = message.getSubject().replace(/[^a-zA-Z0-9 ]/g, '').substring(0, 50);
    
    var direction, contact;
    if (sender.includes(domain)) {
      direction = "FROM";
      contact = sender.match(/<(.+)>/) ? sender.match(/<(.+)>/)[1] : sender;
    } else {
      direction = "TO";
      contact = recipient.match(/<(.+)>/) ? recipient.match(/<(.+)>/)[1] : recipient;
    }
    var filename = `${date} - ${direction} ${contact} - ${subject}.pdf`;
    var blob = Utilities.newBlob(message.getBody(), "text/html", filename).getAs("application/pdf");
    folder.createFile(blob);
  }
}

}

all_cna_emails_code.txt · Last modified: 2025/03/23 00:05 by lwattsii