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

Google Sheets脚本邮件发送问题求助:合并行数据+多收件人配置

嘿,我完全懂这种找遍全网都没解决办法的憋屈!咱们来把这两个邮件自动化的问题逐个击破。

问题1:将多行/列数据合并为单封邮件发送

你遇到的“每行发一封”问题,大概率是因为你在循环遍历数据行的时候,每迭代一次就调用了发送邮件的函数。解决思路很简单:先把需要发送的所有数据收集、拼接成完整的邮件内容,等数据全部处理完后,再一次性发送给收件人。

举个Python的例子(假设你用pandas处理表格数据):

import pandas as pd
import smtplib
from email.mime.text import MIMEText

# 读取数据
df = pd.read_excel("your_data.xlsx")

# 收集需要合并的数据(比如B列到F列的所有行)
merged_content = "这是您需要的所有数据:\n\n"
# 把表格转换成易读的纯文本,去掉索引列
merged_content += df.loc[:, "B":"F"].to_string(index=False)

# 邮件基础配置
smtp_server = "smtp.your_email_provider.com"
smtp_port = 587
sender_email = "your_email@example.com"
sender_pwd = "your_app_password_or_password"
recipient_email = "target@example.com"

# 创建邮件
msg = MIMEText(merged_content, 'plain')
msg['From'] = sender_email
msg['To'] = recipient_email
msg['Subject'] = "合并后的完整数据"

# 发送邮件
with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(sender_email, sender_pwd)
    server.send_message(msg)

print("合并数据的邮件已发送!")

问题2:多收件人对应不同数据块发送

要实现“B2:F3给第一个收件人,B4:F5给第二个收件人”的需求,核心是把收件人和对应的数据块做绑定,然后循环处理每一组配对,给每个收件人发送专属的合并数据。

还是用Python+pandas的示例:

import pandas as pd
import smtplib
from email.mime.text import MIMEText

# 读取Excel数据
df = pd.read_excel("your_data.xlsx")

# 定义收件人与对应数据块的配对(注意:pandas行索引从0开始,所以Excel的第2行对应df的索引1)
recipient_data_map = [
    ("recipient1@example.com", df.loc[1:2, "B":"F"]),  # 对应Excel的B2:F3
    ("recipient2@example.com", df.loc[3:4, "B":"F"]),  # 对应Excel的B4:F5
    # 可以继续添加更多收件人和数据块
]

# 邮件服务器配置
smtp_server = "smtp.your_provider.com"
smtp_port = 587
sender_email = "your_email@example.com"
sender_pwd = "your_app_password"

# 循环发送专属邮件
for recipient, data_block in recipient_data_map:
    # 把数据块转换成邮件内容
    email_body = "您好,以下是您的专属数据:\n\n"
    email_body += data_block.to_string(index=False)
    
    # 构建邮件
    msg = MIMEText(email_body, 'plain')
    msg['From'] = sender_email
    msg['To'] = recipient
    msg['Subject'] = "您的专属数据报告"
    
    # 发送
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()
        server.login(sender_email, sender_pwd)
        server.send_message(msg)
    
    print(f"已给 {recipient} 发送专属邮件")

额外小提示

  • 如果想要更美观的邮件格式,可以把data_block.to_string()换成data_block.to_html(),然后把MIMEText的类型改成'html',这样邮件里会显示规整的表格。
  • 如果你不用pandas,用其他方式读取数据(比如CSV或纯文本),核心逻辑还是一样的:先分组收集对应收件人的数据,合并成内容后再发送。

内容的提问来源于stack exchange,提问作者Ichi Futures

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:10:00