BALABLANCE确认批量电子邮件将发送给GoogleSheep

问题描述 投票:0回答:1

是否需要以下电子邮件发送给供应商,我写了一个代码,但是有一个错误 ?需要帮助

我需要数据从Excel运行并获取DOC并继续发送给其他供应商

function sendBalanceConfirmationLetters() {
  // --- Configuration ---
  const sheetName = "VendorBalances"; // Name of your Google Sheet
  const subject = "Balance Confirmation Request";
  const senderEmail = Session.getActiveUser().getEmail(); // Your email address
  const templateDocId = "1ElTC5N5yeHWLkyH2C5c0bbjWR-sLA9q2Rn6vOPX3azM"; // Replace with your Google Doc template ID
  const sentLogSheetName = "SentLog"; // Sheet to record sent emails

  // --- Get Data from Google Sheet ---
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName(sheetName);
  const data = sheet.getDataRange().getValues();
  const headers = data[0]; // Assuming first row is headers

  // --- Find Column Indexes ---
  const vendorNameCol = headers.indexOf("Vendor Name");
  const vendorEmailCol = headers.indexOf("Vendor Email");
  const balanceCol = headers.indexOf("Balance");

  if (vendorNameCol === -1 || vendorEmailCol === -1 || balanceCol === -1) {
    Logger.log("Missing required columns in sheet.");
    return;
  }

  // --- Get or Create Sent Log Sheet ---
  let sentLogSheet = ss.getSheetByName(sentLogSheetName);
  if (!sentLogSheet) {
    sentLogSheet = ss.insertSheet(sentLogSheetName);
    sentLogSheet.appendRow(["Timestamp", "Vendor Name", "Vendor Email", "Balance", "Status"]);
  }

  // --- Process Each Vendor ---
  for (let i = 1; i < data.length; i++) { // Start from 1 to skip headers
    const vendorName = data[i][vendorNameCol];
    const vendorEmail = data[i][vendorEmailCol];
    const balance = data[i][balanceCol];

    if (!vendorEmail || !vendorName || balance === undefined || balance === "") {
      Logger.log(`Skipping row ${i + 1} due to missing data.`);
      continue;
    }

    try {
      // --- Create Letter from Template ---
      const doc = DocumentApp.openById(templateDocId).makeCopy();
      const body = doc.getBody();

      // --- Replace Placeholders ---
      body.replaceText("{{Vendor Name}}", vendorName);
      body.replaceText("{{Balance}}", balance.toFixed(2)); // Format balance to 2 decimal places

      // --- Convert to PDF ---
      const pdfBlob = doc.getAs("application/pdf");
      doc.removeFromFolder(DriveApp.getFileById(doc.getId()).getParents().next());//removes the temp file copy
      DriveApp.getFileById(doc.getId()).setTrashed(true);//trash the temp file copy

      // --- Send Email ---
      MailApp.sendEmail({
        to: vendorEmail,
        subject: subject,
        body: `Dear ${vendorName},\nPlease find attached the balance confirmation letter.`,
        attachments: [pdfBlob],
        name: "Balance Confirmation",
      });

      // --- Record Sent Log ---
      sentLogSheet.appendRow([new Date(), vendorName, vendorEmail, balance, "Sent"]);

      Logger.log(`Email sent to ${vendorEmail} (${vendorName}).`);

    } catch (e) {
      Logger.log(`Error sending email to ${vendorEmail} (${vendorName}): ${e}`);
      sentLogSheet.appendRow([new Date(), vendorName, vendorEmail, balance, `Error: ${e}`]);
    }
  }

  Logger.log("Balance confirmation process complete.");
}

DOC文件 [Google表] [2]

[2]:

Https://docs.google.com/spreadsheets/d/1jizbgoizqnci1lfdiou61fthe40edjmvlhsst3ofmus/Edit?gid = 0#gid = 0#gid =0

google-sheets google-apps-script
1个回答
0
投票

寄宿电子邮件以获取余额确认的批量 我修复的第一件事是列名,而不是使用"Vendor Email"

使用

"Email ID"


第二个用于Google Docs模板处理

from

DocumentApp.openById(templateDocId).makeCopy();

to to to

DriveApp.getFileById(templateDocId).makeCopy();
为了明确避免通过在副本上工作来修改原始模板。
我也修改了此脚本。

doc.removeFromFolder(DriveApp.getFileById(doc.getId()).getParents().next()); DriveApp.getFileById(doc.getId()).setTrashed(true);

将其更改为此

copiedFile.setTrashed(true);

丢弃临时文件。

我也更改了电子邮件主体以获得更好的方法
body: `Dear ${vendorName},\n\nPlease find attached your balance confirmation letter.\n\nBest regards,\n[Your Name]`,

修改脚本
function sendBalanceConfirmationLetters() {
  
  const sheetName = "VendorBalances"; 
  const sentLogSheetName = "SentLog"; 
  const templateDocId = "Google Docs Template ID";
  const subject = "Balance Confirmation Request";
 
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName(sheetName);
  const data = sheet.getDataRange().getValues();
  const headers = data[0].map(h => h.trim()); 

  const vendorNameCol = headers.indexOf("Vendor Name");
  const vendorEmailCol = headers.indexOf("Email ID");
  const balanceCol = headers.indexOf("Balance");

  if (vendorNameCol === -1 || vendorEmailCol === -1 || balanceCol === -1) {
    Logger.log("Missing required columns in sheet.");
    return;
  }

 
  let sentLogSheet = ss.getSheetByName(sentLogSheetName);
  if (!sentLogSheet) {
    sentLogSheet = ss.insertSheet(sentLogSheetName);
    sentLogSheet.appendRow(["Timestamp", "Vendor Name", "Vendor Email", "Balance", "Status"]);
  }

 
  for (let i = 1; i < data.length; i++) {
    const vendorName = data[i][vendorNameCol];
    const vendorEmail = data[i][vendorEmailCol];
    const balance = data[i][balanceCol];

    if (!vendorEmail || !vendorName || balance === undefined || balance === "") {
      Logger.log(` Skipping row ${i + 1} due to missing data.`);
      continue;
    }

    try {
     
      const copiedFile = DriveApp.getFileById(templateDocId).makeCopy();
      const doc = DocumentApp.openById(copiedFile.getId());
      const body = doc.getBody();
      body.replaceText("{{Vendor Name}}", vendorName);
      body.replaceText("{{Balance}}", parseFloat(balance).toFixed(2));
      doc.saveAndClose();
      const pdfBlob = copiedFile.getAs("application/pdf");
      copiedFile.setTrashed(true); 


      MailApp.sendEmail({
        to: vendorEmail,
        subject: subject,
        body: `Dear ${vendorName},\n\nPlease find attached your balance confirmation letter.\n\nBest regards,\n[Your Name]`,
        attachments: [pdfBlob],
        name: "Balance Confirmation",
      });

      sentLogSheet.appendRow([new Date(), vendorName, vendorEmail, balance, "Sent"]);
      Logger.log(`Email sent to ${vendorEmail} (${vendorName}).`);

    } catch (e) {
      Logger.log(`Error sending email to ${vendorEmail} (${vendorName}): ${e.message}`);
      sentLogSheet.appendRow([new Date(), vendorName, vendorEmail, balance, `Error: ${e.message}`]);
    }
  }

  Logger.log(" Balance confirmation process complete.");
}

样本输出


Reference

类Driveapp

image

© www.soinside.com 2019 - 2025. All rights reserved.