function draftMail() {
var threads = GmailApp.search('in:draft', 0, 10);
if (threads.length === 0) {
Browser.msgBox("No draft emails found");
return;
}
var myapp = UiApp.createApplication().setTitle('Select and Send Mail').setHeight(160).setWidth(300);
var top_panel = myapp.createFlowPanel();
top_panel.add(myapp.createLabel("Please select an email from your Drafts folder"));
var lb = myapp.createListBox(false).setWidth(250).setName('templates').addItem("Select draft...").setVisibleItemCount(1);
for (var i = 0; i < threads.length; i++) {
lb.addItem((i+1)+'- '+threads[i].getFirstMessageSubject().substr(0, 40));
}
top_panel.add(lb);
top_panel.add(myapp.createLabel("").setHeight(10));
top_panel.add(myapp.createLabel("").setHeight(5));
var ok_btn = myapp.createButton("Send Email");
top_panel.add(ok_btn);
myapp.add(top_panel);
var handler = myapp.createServerClickHandler('sendMail').addCallbackElement(lb);
ok_btn.addClickHandler(handler);
SpreadsheetApp.getActiveSpreadsheet().show(myapp);
}
function sendMail(e) {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.toast("I'm sending the email, please wait...",'Gmail',-1);
var draft = GmailApp.search("in:drafts")[(parseInt(e.parameter.templates.substr(0, 2))-1)].getMessages()[0];
var body = draft.getPlainBody();
var to = draft.getTo();
var subject = draft.getSubject();
GmailApp.sendEmail(to, subject, body);
ss.toast('Your email is sent to ' + to);
} catch (e) {
ss.toast(e.toString());
}
var app = UiApp.getActiveApplication();
app.close();
return app;
}