Skip to content

Instantly share code, notes, and snippets.

@pmarkun
Created October 1, 2024 17:12
Show Gist options
  • Save pmarkun/e881ebd8ee2af6b80e6dbd299878ee19 to your computer and use it in GitHub Desktop.
Save pmarkun/e881ebd8ee2af6b80e6dbd299878ee19 to your computer and use it in GitHub Desktop.
ExtraiEmail
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);
});
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function onLoad() {
var today = new Date();
var thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(today.getDate() - 30);
// Formata as datas para o input date (YYYY-MM-DD)
var todayStr = today.toISOString().substr(0, 10);
var thirtyDaysAgoStr = thirtyDaysAgo.toISOString().substr(0, 10);
document.getElementById('dateEnd').value = todayStr;
document.getElementById('dateStart').value = thirtyDaysAgoStr;
}
function startSearch() {
var dateStart = document.getElementById('dateStart').value;
var dateEnd = document.getElementById('dateEnd').value;
google.script.run.withSuccessHandler(function() {
alert('Busca concluída! Verifique a planilha para os resultados.');
}).searchEmails(dateStart, dateEnd);
}
</script>
</head>
<body onload="onLoad()">
<h2>Configuração de Busca</h2>
<form id="configForm">
<label for="dateStart">Data de início:</label><br>
<input type="date" id="dateStart" name="dateStart"><br><br>
<label for="dateEnd">Data de fim:</label><br>
<input type="date" id="dateEnd" name="dateEnd"><br><br>
<input type="button" value="Iniciar Busca" onclick="startSearch()">
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment