我有一个需要登录的表单,我正在尝试获取其 html 以嵌入到电子邮件中。类似于问题Google Apps Script: how to access or call "Send this form to others"?
var form = FormApp.create('New Form');
form.setRequireLogin(true);
...
var url = form.getPublishedUrl();
var response = UrlFetchApp.fetch(url);
var htmlBody = HtmlService.createHtmlOutput(response).getContent();
MailApp.sendEmail({
to: email,
subject: subject,
htmlBody: htmlBody,
});
...
但是,URLFetchApp 似乎没有正确的 OAuth 配置,我总是获得 Google 登录页面的 HTML。
有没有办法设置正确的 OAuth 参数来获取表单 HTML?
最佳答案
您的问题询问的是允许 UrlFetch()
获取设置了 requiresLogin()
的表单的 HTML 内容所需的 OAuth 参数。这个答案没有直接解决这个问题。
无需 OAuth,您可以短暂更改表单的登录要求,只需足够长的时间即可从中获取 HTML。在一小段时间内,您的域外的个人可能会访问您的表单(如果他们碰巧知道 URL,并且在您再次锁定表单之前足够快地填写表单以提交他们的响应)。
脚本
无论是否设置了 requiresLogin()
,以下 sendForm()
函数都适用于消费者和 GApp 域帐户。
/**
* Send user an email containing the given form, in HTML.
*
* @param {Form} form Form object.
* @param {String} email One or more email addresses, comma separated.
*/
function sendForm(form,email) {
var url = form.getPublishedUrl();
// Temporarily disable requiresLogin so UrlFetch will operate
if (form.requiresLogin()) {
var requiresLogin = true;
form.setRequireLogin(false);
}
// Fetch form's HTML
var response = UrlFetchApp.fetch(url);
var htmlBody = HtmlService.createHtmlOutput(response).getContent();
// Re-enable requireLogin, if necessary
if (requiresLogin) {
form.setRequireLogin(true);
}
var subject = form.getTitle();
MailApp.sendEmail(email,
subject,
'This message requires HTML support to view.',
{
name: 'Form Emailer Script',
htmlBody: htmlBody
});
}
为了完整起见,这里有一个测试函数...
function test_sendForm() {
// Build new form for testing
var form = FormApp.create('New Form');
var formTitle = 'Form Name';
form.setTitle(formTitle)
.setDescription('Description of form')
.setConfirmationMessage('Thanks for responding!')
.setAllowResponseEdits(true)
.setAcceptingResponses(true)
// Require Login (for GApp Domain accounts only)
try {
form.setRequireLogin(true);
} catch (e) {
// Error is expected for consumer accounts - carry on.
}
// Just one question
form.addTextItem().setTitle("Q1");
// Send it to self
var email = Session.getEffectiveUser().getEmail();
sendForm(form,email)
}
关于google-apps-script - 如何在 Google 应用脚本中的电子邮件中嵌入 Google 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27028826/