You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Script执行成功但无法发送邮件,求技术协助

Fixing Your Google Apps Script Email Issue

Hey there, let's figure out why your script says it executed successfully but no emails are being sent. I went through your code and spotted several issues that are causing this problem—here's how to fix them:

Key Issues in Your Original Code

  • Duplicate function definition: You’ve written function sendEmails() twice in the code. This breaks the structure and means only the second (incomplete) version runs properly.
  • Incorrect logical operator: You used && (an HTML escaped version) instead of the JavaScript logical AND operator &&. This won’t work as intended for checking if both files exist.
  • Unscoped variables: Variables like file, file2, and i aren’t declared with let/const/var, leading to unexpected global scope behavior.
  • Poor array traversal: Using for (i in data) to loop through spreadsheet rows can cause issues with array indices in Apps Script—better to use a standard for loop or forEach.
  • Messy code structure: Extra closing brackets and misplaced code blocks are hiding logic errors.

Fixed Script

function sendEmails() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const startRow = 2; // First row of data to process
  const numRows = 2; // Number of rows to process
  
  // Fetch range A2:C3 (3 columns: email, subject, message)
  const dataRange = sheet.getRange(startRow, 1, numRows, 3);
  const data = dataRange.getValues();
  
  // Get file references ONCE outside the loop (if files are unique)
  let marksFile, remunFile;
  try {
    marksFile = DriveApp.getFilesByName('Marks.xls').next();
    remunFile = DriveApp.getFilesByName('Remuneration.pdf').next();
  } catch (error) {
    console.error("One or more required files not found: ", error.message);
    return;
  }

  // Loop through each row of data
  for (let i = 0; i < data.length; i++) {
    const row = data[i];
    const recipientEmail = row[0];
    const emailSubject = row[1];
    const emailMessage = row[2];

    try {
      MailApp.sendEmail({
        to: recipientEmail,
        subject: emailSubject,
        body: emailMessage,
        attachments: [
          marksFile.getAs('application/vnd.ms-excel'),
          remunFile.getAs('application/pdf')
        ],
        name: 'Automatic Emailer Script'
      });
      console.log(`Email sent successfully to ${recipientEmail}`);
    } catch (error) {
      console.error(`Failed to send email to ${recipientEmail}: ${error.message}`);
    }
  }
}

Additional Notes

  1. File Existence Check: The outer try/catch block ensures we stop execution immediately if either required file is missing, so you don’t waste time looping through rows when attachments aren’t available.
  2. MIME Type Correction: The correct MIME type for legacy Excel files is application/vnd.ms-excel instead of application/msexcel—this ensures email clients recognize the attachment properly.
  3. Logging: The console.log and console.error lines will help you debug in the Apps Script execution log to see exactly which emails sent successfully and which failed.
  4. Permissions: Double-check that you’ve authorized the script to access your Google Drive and send emails—sometimes initial authorization prompts are dismissed accidentally, which blocks the script from performing these actions.

内容的提问来源于stack exchange,提问作者Ravi Shankar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:28:29