![](/img/trans.png)
[英]How to send a HTML email with attachment using MailApp in Google Apps Script?
[英]How to get file(s) from an HTML file input and send it as an attachment to an email in Google Apps Script?
此 HTML 代碼使用 Google Script 的類 HTML 服務獲取文件輸入:
(見下文)
我想獲取輸入字段的值(文件),發送到我的 .gs 文件並將其作為電子郵件的附件發送。
從輸入字段中獲取值只是返回文件的目錄,這沒有幫助,因為 Google Apps Script 無法從本地驅動器獲取文件。
我對這個問題進行了長時間的研究,但找不到任何有類似問題的人。
堆棧代碼.gs
function myFunction() {
var html = HtmlService.createHtmlOutputFromFile('Stack HTML').setWidth(250).setHeight(250);
SpreadsheetApp.getUi().showModalDialog(html,'Get File');
}
function processEmail(files){
var subject = 'Subject';
var message = 'Test';
var recipient = 'test@gmail.com';
GmailApp.sendEmail(recipient, subject, message, {attachments: files, htmlBody: message, name:'Stack Overflow Test'}); // Doesn't work
}
堆棧 HTML.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form method="post" enctype="multipart/form-data">
<div>
<input type="file" id= "file" multiple = "true">
</div>
</form>
<br><div style="text-align:center"> <input type="submit" name = "submitButton" onclick = "send()" id = "sendButton" value="Send"></div>
<script>
function done(e){
google.script.host.close();
}
function send(){
var files = document.getElementById("file").value;
console.log(files);
google.script.run.withSuccessHandler(done).processEmail(files);
}
</script>
</body>
</html>
如果我的理解是正確的,這個修改怎么樣? 請將此視為幾個答案之一。
從您的問題來看,這些文件被用作電子郵件的附件文件。 所以我認為以下流程可以用於您的情況。
請在 HTML 端修改send()
如下。
function send() {
const f = document.getElementById('file');
Promise.all([...f.files].map((file, i) => {
const fr = new FileReader();
return new Promise(r => {
fr.onload = e => {
const data = e.target.result.split(",");
r({fileName: file.name, mimeType: data[0].match(/:(\w.+);/)[1], data: data[1]});
}
fr.readAsDataURL(file);
});
}))
.then(obj => {
google.script.run.withSuccessHandler(done).processEmail(obj);
});
}
並請修改 GAS 端的processEmail()
如下。
function processEmail(obj){
var files = obj.map(function(e) {return Utilities.newBlob(Utilities.base64Decode(e.data), e.mimeType, e.fileName)});
var subject = 'Subject';
var message = 'Test';
var recipient = 'test@gmail.com';
GmailApp.sendEmail(recipient, subject, message, {attachments: files, htmlBody: message, name:'Stack Overflow Test'});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.