亲爱的我正在尝试执行以下代码来生成每个用户每周发送的报告电子邮件数量,但是我收到未定义的错误。
我正在尝试为我们的团队创建活动报告,其中将包括每个团队成员发送的电子邮件数量。
我想每7天触发一次脚本,并为每个唯一的用户和日期添加一个新行。因此输出的每一行都是:日期/用户/ num_emails_sent
能请你帮忙吗?
/*
* UI - Menu function
*/
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Mail Reports')
.addItem('Generate User Report', 'generateUserReport')
.addToUi();
}
/*
* Main function to generate report
*/
function generateUserReport(){
// Get dates [perdiod start = week ago, period end = today]
var dates = getInterval();
var start = dates[0];
var end = dates[dates.length-1];
// Get users and dates in spreadsheet
listAllUsers();
// Loop over sheet and add values
var sheet = SpreadsheetApp.getActive().getActiveSheet();
var data = sheet.getDataRange().getValues();
for( var i =1; i < data.length; i++){
if(data[i][1] === ''){
sheet.getRange(i+1, 2).setValue(start);
sheet.getRange(i+1, 3).setValue(end);
var sent = 0;
var received = 0;
dates.forEach(function(date){
var res = getMailsReports(data[i][0], date);
sent = sent + Number(res.sent);
received = received + Number(res.received);
})
sheet.getRange(i+1, 4).setValue(sent);
sheet.getRange(i+1, 5).setValue(received);
}
}
}
/*
* Get Mail reports
* Sent / Saved number
*/
function getMailsReports(user, date){
var parameters = ['gmail:num_emails_sent', 'gmail:num_emails_received'];
var page = AdminReports.UserUsageReport.get(user, date, {
parameters: parameters.join(',')
});
return res = {
received : page.usageReports[0].parameters[0].intValue,
sent : page.usageReports[0].parameters[1].intValue,
}
}
/**
* Slice dates
*/
function getInterval(){
var end = new Date(new Date().getTime() - 2 * 24 * 60 * 60 * 1000);
var start = new Date(end.getTime() - 6 * 24 * 60 * 60 * 1000);
var timezone = Session.getScriptTimeZone();
var res = getDates(start, end).map(function(date){
return Utilities.formatDate(date, timezone, 'yyyy-MM-dd');
})
return res;
}
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf())
dat.setDate(dat.getDate() + days);
return dat;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push( new Date (currentDate) )
currentDate = currentDate.addDays(1);
}
return dateArray;
}
/*
* List all users in the domaine
*/
function listAllUsers() {
var pageToken, page;
do {
page = AdminDirectory.Users.list({
domain: 'lafargeholcim.com',
orderBy: 'Email',
maxResults: 100,
pageToken: pageToken
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
SpreadsheetApp.getActive().getActiveSheet().appendRow([user.primaryEmail])
}
} else {
Logger.log('No users found.');
}
pageToken = page.nextPageToken;
} while (pageToken);
}