Using app scripts I'm trying to extract all the email addresses from email messages and put them in an array. From my console.log messages, I'm getting stuck because it looks like instead of an array I just get a string. i'm not too familiar with javascript. Any help would be great. I'm looking for an array of email address. The methods of message.get() return a string. I want to split out the email address and create a single, unified array.
var ui = SpreadsheetApp.getUi();
function onOpen(e){
ui.createMenu("Gmail Manager").addItem("Get Emails by Label", "getGmailEmails").addToUi();
}
function getGmailEmails(){
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
var fullArray = [];
for(var i = threads.length - 1; i >=0; i--){
var messages = threads[i].getMessages();
for (var j = 0; j <messages.length; j ){
var message = messages[j];
if (message.isUnread()){
fullArray.push(extractDetails(message));
}
}
}
console.log("FullArray:" fullArray);
for(var i=0; i<fullArray.length; i ){
console.log("printing array " i ": " fullArray[i])
}
}
function extractDetails(message){
var dateTime = message.getDate();
var subjectText = message.getSubject();
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmail = message.getReplyTo();
var toEmail = message.getTo();
var emailArray = []
var senderArray = senderDetails.split(',');
var ccArray = ccEmails.split(',');
var replyArray = replyEmail.split(',');
var toArray = toEmail.split(',');
for (var i =0 ; i<toArray.length; i ){
console.log("toArray Loop" i " : " toArray[i]);
emailArray.push([toArray[i]]);
}
for (var i =0 ; i<ccArray.length; i ){
console.log("ccArray Loop" i " : " ccArray[i]);
emailArray.push([ccArray[i]]);
}
console.log("Email Array: " emailArray);
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, senderDetails, subjectText, ccEmails,replyEmail,toEmail,emailArray]);
return emailArray;
}
CodePudding user response:
I think the problem is just the console output. If you change console.log("Email Array: " emailArray);
to console.log("Email Array: ", emailArray);
, then it shows an array of arrays. You could simplify your extract method as follows:
function extractDetails(message) {
/* ... */
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmails = message.getReplyTo();
var toEmails = message.getTo();
let emailArray = [senderDetails, ccEmails, replyEmails, toEmails].reduce(
(array, string) => {
//remove names (like "Name <[email protected]>") and filter empty values
let emails = string
.split(/\s*,\s*/)
.map(e => e.replace(/.*?([^@<\s] @[^@\s>] ).*?/g, "$1"))
.filter(Boolean);
if(emails.length > 0)
return array.concat(emails)
return array
}, []);
/* ... */
}