Created
October 1, 2024 17:12
-
-
Save pmarkun/e881ebd8ee2af6b80e6dbd299878ee19 to your computer and use it in GitHub Desktop.
ExtraiEmail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function onOpen() { | |
var ui = SpreadsheetApp.getUi(); | |
ui.createMenu('Gmail Busca') | |
.addItem('Buscar Contatos', 'showSidebar') | |
.addToUi(); | |
} | |
function showSidebar() { | |
var html = HtmlService.createHtmlOutputFromFile('sidebar') | |
.setTitle('Buscar Contatos no Gmail'); | |
SpreadsheetApp.getUi().showSidebar(html); | |
} | |
function searchEmails(dateInputStart, dateInputEnd) { | |
Logger.log("Iniciando a função searchEmails"); | |
// Define as datas para filtrar os emails | |
var startDate = dateInputStart ? new Date(dateInputStart) : null; | |
var endDate = dateInputEnd ? new Date(dateInputEnd) : null; | |
// Se nenhuma data foi passada, busca os últimos 30 dias | |
if (!startDate || !endDate) { | |
endDate = new Date(); | |
startDate = new Date(); | |
startDate.setDate(endDate.getDate() - 30); | |
} | |
var formattedStartDate = Utilities.formatDate(startDate, Session.getScriptTimeZone(), "yyyy/MM/dd"); | |
var formattedEndDate = Utilities.formatDate(endDate, Session.getScriptTimeZone(), "yyyy/MM/dd"); | |
Logger.log("Data formatada de início: " + formattedStartDate); | |
Logger.log("Data formatada de fim: " + formattedEndDate); | |
// Busca os e-mails ENVIADOS no intervalo de datas | |
var query = "in:sent after:" + formattedStartDate + " before:" + formattedEndDate; | |
var threads = GmailApp.search(query); | |
Logger.log("Número de threads encontrados: " + threads.length); | |
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); | |
// Obter e-mails existentes na planilha para evitar duplicados | |
var data = sheet.getDataRange().getValues(); | |
var existingEmails = new Set(); | |
if (data.length > 1) { // Verifica se há dados além do cabeçalho | |
for (var i = 1; i < data.length; i++) { | |
existingEmails.add(data[i][1]); // Assume que a coluna B é o e-mail | |
} | |
} | |
// Se a planilha estiver vazia, adicionar cabeçalho | |
if (data.length === 0) { | |
sheet.appendRow(['Nome do Destinatário', 'E-mail', 'Comercial']); | |
} | |
var stopWords = ['suporte', 'contato', 'info', 'noreply', 'atendimento']; | |
for (var i = 0; i < threads.length; i++) { | |
var messages = threads[i].getMessages(); | |
messages.forEach(function(message) { | |
var toRecipients = message.getTo(); | |
var ccRecipients = message.getCc(); | |
var bccRecipients = message.getBcc(); | |
var recipients = []; | |
if (toRecipients) recipients = recipients.concat(toRecipients.split(',')); | |
if (ccRecipients) recipients = recipients.concat(ccRecipients.split(',')); | |
if (bccRecipients) recipients = recipients.concat(bccRecipients.split(',')); | |
recipients.forEach(function(recipient) { | |
var email = extractEmail(recipient); | |
var name = extractName(recipient); | |
if (email && !existingEmails.has(email)) { | |
var isCommercial = isCommercialEmail(email, stopWords) ? 'Sim' : 'Não'; | |
sheet.appendRow([name, email, isCommercial]); | |
existingEmails.add(email); // Adiciona ao conjunto para evitar duplicados futuros | |
} | |
}); | |
}); | |
// Opcional: Atualizar a barra de progresso ou logs | |
var progress = Math.round(((i + 1) / threads.length) * 100); | |
Logger.log("Progresso: " + progress + "%"); | |
} | |
Logger.log("Busca finalizada com sucesso."); | |
} | |
function extractEmail(text) { | |
var regex = /<(.+?)>/; | |
var match = text.match(regex); | |
if (match) { | |
return match[1].trim(); | |
} else { | |
// Se não estiver no formato <email>, tenta extrair diretamente | |
var emailMatch = text.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i); | |
return emailMatch ? emailMatch[0].trim() : ''; | |
} | |
} | |
function extractName(text) { | |
var regex = /^(.*?)</; | |
var match = text.match(regex); | |
if (match) { | |
return match[1].trim(); | |
} else { | |
// Se não tiver nome, retorna 'Sem Nome' | |
return 'Sem Nome'; | |
} | |
} | |
function isCommercialEmail(email, stopWords) { | |
var localPart = email.split('@')[0].toLowerCase(); | |
return stopWords.some(function(word) { | |
return localPart.includes(word); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment