【问题标题】:Is there a way to skip empty Google sheet values and continue with the next row in focus? Partially working script included有没有办法跳过空的 Google 工作表值并继续关注下一行?包括部分工作脚本
【发布时间】:2026-02-05 10:30:01
【问题描述】:

下面是一个 python 脚本,它将向同一行中列出的地址发送电子邮件。我的信息/消息在第 2 列,我的目标电子邮件地址在第 6 列。脚本正在运行。但是,当第 6 列(空白单元格)中没有电子邮件地址时,它会跳到下一个可用的电子邮件地址并为第 2 列发送错误的文本(它会在行中没有电子邮件地址的情况下发送第 2 列的文本)。所以,发送了错误的消息......我可以让它工作的唯一方法是每个单元格中都有值,并且我不会跳过第 6 列中的任何单元格。我不知道该怎么做。有谁知道如何修改脚本,以便我只能在有可用电子邮件地址时发送电子邮件,如果没有可用电子邮件地址则跳过,并确保只发送正确行中的值?这是我到目前为止的代码。另外,请看附图。

class DatetimeEncoder(json.JSONEncoder):
    def default(self, obj):
        try:
            return super(DatetimeEncoder, obj).default(obj)
        except TypeError:
            return str(obj)


scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('', scope)


testtime = datetime.today().strftime('%m-%d-%Y AT %H:%M:%S.')

gc = gspread.authorize(credentials)

wks = gc.open("log").worksheet("emaillist")

emaillist = [item for item in wks.col_values(6)[1:] if item]
for item in emaillist:
    print(item)

messageinfo = [item2 for item2 in wks.col_values(2)[1:] if item2]
for item2 in messageinfo:
    print(item2)

import yagmail

yag = yagmail.SMTP("x@gmail.com", "x")


for i in range(len(emaillist)):
    email = emaillist[i]
    body = "test"


    yag.send(
        to=[email],
        subject="Inquiry " + testtime,
        contents=messageinfo,
    )

print("Done")

编辑:我有一个半解决方案。也许不是最优雅的。仍然会感谢您的意见:

def emails(wks):
    for row in wks.get_all_records():
        if row["EMAIL"] and row != "":
            yield row["EMAIL"]

to_emails = list(emails(wks))


print(to_emails)

def message(wks):
    for row in wks.get_all_records():
        if row["MESSAGETEXT"] and row["EMAIL"] != "":
            yield row["MESSAGETEXT"]


to_message = list(message(wks))
print(to_message)

这会将其分成两个列表...仍在测试中

【问题讨论】:

    标签: python python-3.x email google-sheets data-structures


    【解决方案1】:

    这行得通:

    def emails(wks):
        for row in wks.get_all_records():
            if row["EMAIL"] and row != "":
                yield row["EMAIL"]
    
    to_emails = list(emails(wks))
    
    
    print(to_emails)
    
    def message(wks):
        for row in wks.get_all_records():
            if row["MESSAGETEXT"] and row["EMAIL"] != "":
                yield row["MESSAGETEXT"]
    
    
    to_message = list(message(wks))
    print(to_message)
    

    【讨论】:

      最近更新 更多