如何在Google Sheets中实现按行内容触发邮件发送按钮?
解决方案:Google Sheets 项目邮件发送脚本适配需求
以下是完全符合你需求的修改后脚本,以及详细的设置步骤:
完整代码
function sendProjectEmail() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheet = ss.getSheetByName("Projects"); const activeRow = sheet.getActiveRange().getRow(); // 跳过表头行 if (activeRow === 1) { SpreadsheetApp.getUi().alert("请点击数据行的信封图标!"); return; } // 封装空值替换逻辑 const getCellValue = (columnIndex) => { const value = sheet.getRange(activeRow, columnIndex).getValue(); return value ? value : "NA"; }; // 提取对应列的数据(列号对应:C=3, D=4, E=5, F=6, G=7, H=8, I=9, P=16, Q=17, R=18, S=19, T=20, U=21, V=22, W=23, X=24, Y=25) const colC = getCellValue(3); const colD = getCellValue(4); const colE = getCellValue(5); const colF = getCellValue(6); const colG = getCellValue(7); const colH = getCellValue(8); const colI = getCellValue(9); const colP = getCellValue(16); const colQ = getCellValue(17); const colR = getCellValue(18); const colS = getCellValue(19); const colT = getCellValue(20); const colU = getCellValue(21); const colV = getCellValue(22); const colW = getCellValue(23); const colX = getCellValue(24); const colY = getCellValue(25); // 构建邮件主题 const emailSubject = `${colC} Here's the latest on our project ${colD}!`; // 构建邮件正文 const emailBody = `Latest Update: ${colY} Project Name: ${colD}, ${colE} Status: ${colF} Date Started: ${colG} Target Completion Date: ${colH} Will be completed in: ${colI} days Work Permits: TIM - ${colS}, End-customer - ${colT}, Others - ${colU} Cross Connect Details: From ${colQ} to ${colR} under Service ID: ${colP} Test Results: ${colV} 3PP Service ID: ${colW} Billing Effective Date: ${colX}`; const mainRecipient = "carlo.reyes.timcorp@gmail.com"; const currentUser = Session.getActiveUser().getEmail(); try { // 发送主邮件 MailApp.sendEmail(mainRecipient, emailSubject, emailBody); // 发送操作回执给当前用户 MailApp.sendEmail( currentUser, "回执:项目状态邮件已发送", `你已成功发送项目状态邮件至 ${mainRecipient}。 邮件主题:${emailSubject} --- 邮件正文: ${emailBody}` ); SpreadsheetApp.getUi().alert("邮件及回执发送成功!"); } catch (err) { SpreadsheetApp.getUi().alert(`发送失败:${err.message}`); } }
设置步骤
- 打开脚本编辑器:在你的Google Sheets中,点击顶部菜单栏「扩展程序」→「Apps Script」。
- 替换并保存代码:删除编辑器中原有的代码,粘贴上述完整代码,点击保存按钮,给项目命名(例如「ProjectEmailSender」)。
- 完成权限授权:首次运行脚本时会提示授权,按照指引完成授权(需允许脚本访问你的邮箱和表格数据)。
- 为Z列每行添加信封图标:
- 点击顶部菜单「插入」→「绘图」,选择内置的信封图标(或上传自定义信封图片),调整合适大小后点击「保存并关闭」。
- 将图标拖动到Z列对应数据行的单元格内,右键点击图标→「分配脚本」,输入
sendProjectEmail并确认。 - 重复此操作,为Z列每一行数据添加绑定了脚本的信封图标。
关键功能说明
- 空值自动替换:通过
getCellValue函数,自动将空单元格内容替换为「NA」。 - 行数据匹配:脚本通过
getActiveRange().getRow()获取点击图标所在的行,确保发送对应行的项目数据。 - 回执功能:使用
Session.getActiveUser().getEmail()获取当前操作用户的邮箱,发送包含完整邮件内容的回执。 - 错误提示:添加异常捕获逻辑,发送失败时弹出具体错误信息,方便排查问题。
内容的提问来源于stack exchange,提问作者Carlo Reyes
相关产品推荐
相关产品推荐

