Skip to content

Instantly share code, notes, and snippets.

@hanguokai
Created April 28, 2013 10:29
Show Gist options
  • Save hanguokai/5476516 to your computer and use it in GitHub Desktop.
Save hanguokai/5476516 to your computer and use it in GitHub Desktop.
本代码为 Google Apps Script 。 用于读取 Google Drive 中的报名表(电子表格),去除重复数据,并根据姓名和 Email 地址发送通知邮件。
//已发送邮件的标记内容
var EMAIL_SENT = "EMAIL_SENT";
//记录已发送记录的列,一般为原有数据的后面一列,从0开始
var EMAIL_SENT_COLUMN = 9;
// 发送的邮件主题
var SUBJECT = "北京GDG之编程语言沙龙参会确认函";
// email 所在的列,从0开始算
var emailColumn = 2;
// 姓名所在的列,从0开始算
var nameColumn = 1;
/**
* 读取数据去除重复的行,并将数据保存到新的表中
*/
function removeDuplicates() {
//var key = "0AhIp-TG_44qxdE96Y29hbklWbUEyYjBmTnVXTlNZZ1E";
//var sheet = SpreadsheetApp.openById(key).getSheets()[0];
var spreedsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreedsheet.getSheets()[0];
var data = sheet.getDataRange().getValues();
// a hashset for unique email
var emailSet = {};
var newData = new Array();
// 有效数据从第二行开始,跳过第一行的 title 内容
for (var i = 1; i < data.length; i++) {
var row = data[i];
var email = row[emailColumn];
if(!emailSet[email]){
emailSet[email] = true;//add email to hashset
newData.push(row);
}
}
//save to new sheet
var newSheet = spreedsheet.insertSheet();
newSheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
return newSheet;
}
/**
* 发送通知邮件。
* sheet 为去重后的数据表,且只含数据不含 title
*/
function sendEmails(sheet) {
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
var row = data[i];
var emailAddress = row[emailColumn];
var username = row[nameColumn];
var message = getSendMessage(username);
var emailSent = row[EMAIL_SENT_COLUMN];
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, SUBJECT, message);
sheet.getRange(i+1, EMAIL_SENT_COLUMN+1).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
/**
* 根据模版和参数获得实际要发送的邮件内容。
* 目前只是简单的纯文本邮件。
*/
function getSendMessage(username){
var content = username + ', 您好:\n\n'
+ '感谢您报名参加北京GDG之编程语言沙龙活动。您已成功报名。\n\n'
+ '本次活动将于5月5号13:30开始签到入场,请您按时参会。\n\n'
+ '地点:翠宫饭店,中国北京市海淀区知春路76号。10号线知春里D口,东行200米。\n\n'
+ '北京GDG';
return content;
}
/**
* 从头开始完成所有工作,重复执行会重复发送邮件!
*/
function main(){
var sheet = removeDuplicates();
sendEmails(sheet);
}
/**
* 已完成去重的工作,只发送邮件
*/
function main2(){
var spreedsheet = SpreadsheetApp.getActiveSpreadsheet();
//读取之前生成的数据表,如:getSheets()[1];
var sheet = spreedsheet.getSheets()[1];
sendEmails(sheet);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment