首页 > 解决方案 > Gmail API 在批量发送期间发送多封邮件

问题描述

我希望使用 Gmail API 发送批量电子邮件。我有一个使用 for 循环的实现,它在每次迭代中更改接收者的电子邮件,并创建一条新消息并执行服务。

问题是我观察到多封电子邮件都发往同一个邮件 ID。由于我是使用 Gmail API 的新手,因此我不知道此问题的根本原因。

代码:


# receiver_path contains file with emails separated by comma
f = open(receiver_path, "r")
receivers = (f.read()).split(',')

message = MIMEText(body_txt)
message['from'] = senders_email
message['subject'] = subject

while i < (len(receivers)):
    a = min(45, len(receivers)-i)
    for j in range(a):
        message['to'] = str(receivers[i + j])

        raw = base64.urlsafe_b64encode(message.as_bytes())
        raw = raw.decode()
        final_message = {'raw': raw}

        try:
            message_temp = (service.users().messages().send(userId=senders_email, body=final_message)
                            .execute())
        except BaseException as e:
            print('Could not send mail: ', e)
            print('Mail id #' + str(i + j + 1))

    sleep(1.5)

    print('Mail delivered to set ' + str(int(i / 45) + 1))
    i += 45

我试过什么?:

  1. 在执行每封邮件而不是每批邮件后休眠。
  2. 调试代码,循环逻辑按预期工作。

标签: pythongoogle-apigmailgmail-apigoogle-api-python-client

解决方案


推荐阅读