使用Gmail API发送的电子邮件未在线程中分组?

发布于 2025-02-09 12:23:24 字数 3822 浏览 1 评论 0 原文

我正在使用 gmail api 来发送电子邮件。这是我要创建电子邮件的功能:

    def createEmailNoAttachments(self, send_to_emails, subject_text, main_message_text, msgID=None, inReplyTo=None, html=False):
        try:
            fromEmail = self.from_email_total
            
            
            if (type(main_message_text) == list) or (type(main_message_text) == tuple): 
                total_text = ""
                for line in main_message_text:
                    if type(line) == str: 
                        total_text = total_text + line + "\n"
                main_message_text = total_text
                        
            mimeMessage = MIMEMultipart()
            if type(send_to_emails) == list: 
                mimeMessage['to'] = ", ".join(send_to_emails)
            else: 
                mimeMessage['to'] = send_to_emails

            mimeMessage['from'] = fromEmail
            mimeMessage['subject'] = subject_text
            if inReplyTo != None: 
                mimeMessage["In-Reply-To"] = inReplyTo
                mimeMessage["References"] = inReplyTo
            if msgID != None: 
                mimeMessage['Message-ID'] = msgID
            if html: 
                msg= MIMEText(main_message_text, 'html')
            else: 
                msg= MIMEText(main_message_text, "plain")
            mimeMessage.attach(msg)

            raw = base64.urlsafe_b64encode(mimeMessage.as_bytes())
            raw = raw.decode()
            body = {'raw': raw}

            return body
        except:
            self.myLogger.error("An error was encountered while attempting to create gmail email")
            tb = traceback.format_exc()
            self.myLogger.exception(tb)
            return False
            

然后,我注意到的

    def gmailAPISendEmail(self, email_message, deleteFromInbox=False, userID="me"):
        try:
            self.refreshGmailService()
            
            self.myLogger.info("Attempting to send email message")

            request = self.service.users().messages().send(userId=userID, body=email_message)
            response = self.executeGmailAPI_withretry(request=request)
            if response == False: 
                self.myLogger.error("An error occurred in executeGmailAPI_withretry while trying to send email message")
                return False
            else:
                try: 
                    responseID = str(response['id'])

                    if deleteFromInbox == True: 
                        delete_result = self.deleteEmail(emailID=responseID)
                        if delete_result == False: 
                            self.myLogger.error(f"An error occurred in deleteEmail with responseID ({responseID})")
                
                    self.myLogger.info("Successfully sent email message with ID (" + responseID +")")
                    return responseID
                except: 
                    return "CouldNotExtractID"
        except:
            self.myLogger.error("An error occurred in gmailAPISendEmail")
            tb = traceback.format_exc()
            self.myLogger.exception(tb)
            return False

问题是,我注意到的问题是,使用上述函数发送时,带有相同电子邮件主题的类似电子邮件和相同的发件人和收件人在一个线程中不会被分组( Gmail API )。在收件人的电子邮件收件箱中,每个电子邮件都会单独出现,即使它们具有相同的主题以及相同的发送者和接收器电子邮件地址。

我相信下一步将是手动分配 threadID 。但是,这远非理想,因为我需要纳入一些逻辑来完成所有这些逻辑。

在我使用 SMTP 之前,我不必设置 threadID 或类似的内容。在使用 SMTP 发送电子邮件时,电子邮件将根据同一电子邮件主题和同一收件人自动分组。

在之前和现在之间没有任何变化,除了我正在使用 gmail api 来代替 smtp 的同一电子邮件。

为什么 gmail api 行为与 smtp 相似,即使我的创建电子邮件非常相似?我可以做些什么来拥有 gmail 收件箱来对电子邮件进行分组,就像 smtp 一样,而无需构建逻辑并跟踪 thread> thread> threadID s ?

I am using the gmail API for sending emails. This is the function I am using to create an email:

    def createEmailNoAttachments(self, send_to_emails, subject_text, main_message_text, msgID=None, inReplyTo=None, html=False):
        try:
            fromEmail = self.from_email_total
            
            
            if (type(main_message_text) == list) or (type(main_message_text) == tuple): 
                total_text = ""
                for line in main_message_text:
                    if type(line) == str: 
                        total_text = total_text + line + "\n"
                main_message_text = total_text
                        
            mimeMessage = MIMEMultipart()
            if type(send_to_emails) == list: 
                mimeMessage['to'] = ", ".join(send_to_emails)
            else: 
                mimeMessage['to'] = send_to_emails

            mimeMessage['from'] = fromEmail
            mimeMessage['subject'] = subject_text
            if inReplyTo != None: 
                mimeMessage["In-Reply-To"] = inReplyTo
                mimeMessage["References"] = inReplyTo
            if msgID != None: 
                mimeMessage['Message-ID'] = msgID
            if html: 
                msg= MIMEText(main_message_text, 'html')
            else: 
                msg= MIMEText(main_message_text, "plain")
            mimeMessage.attach(msg)

            raw = base64.urlsafe_b64encode(mimeMessage.as_bytes())
            raw = raw.decode()
            body = {'raw': raw}

            return body
        except:
            self.myLogger.error("An error was encountered while attempting to create gmail email")
            tb = traceback.format_exc()
            self.myLogger.exception(tb)
            return False
            

I then send the email with

    def gmailAPISendEmail(self, email_message, deleteFromInbox=False, userID="me"):
        try:
            self.refreshGmailService()
            
            self.myLogger.info("Attempting to send email message")

            request = self.service.users().messages().send(userId=userID, body=email_message)
            response = self.executeGmailAPI_withretry(request=request)
            if response == False: 
                self.myLogger.error("An error occurred in executeGmailAPI_withretry while trying to send email message")
                return False
            else:
                try: 
                    responseID = str(response['id'])

                    if deleteFromInbox == True: 
                        delete_result = self.deleteEmail(emailID=responseID)
                        if delete_result == False: 
                            self.myLogger.error(f"An error occurred in deleteEmail with responseID ({responseID})")
                
                    self.myLogger.info("Successfully sent email message with ID (" + responseID +")")
                    return responseID
                except: 
                    return "CouldNotExtractID"
        except:
            self.myLogger.error("An error occurred in gmailAPISendEmail")
            tb = traceback.format_exc()
            self.myLogger.exception(tb)
            return False

The problem I am noticing is that similar emails with the same email subject and same sender and recipient are not being grouped under one thread when sent using the above functions (the gmail API). In the recipient email inbox, each individual email appears separately, even though they have the same subject and same sender and receiver email addresses.

I believe the next step would be to manually assign threadid. However, this is far from ideal, as I would need to incorporate some logic to do all of this.

Before when I used SMTP, I didn't have to set a threadid or anything like that. When sending emails with SMTP, emails would automatically group together based on same email subject and same recipient.

Nothing changed between before and now, except that I am sending the same emails with the gmail API in place of SMTP.

Why doesn't the gmail API behave similar to SMTP, even though I am creating the email very similarly? Is there something I can do to have Gmail inboxes to group the emails just like SMTP, without having to build logic and keeping track of threadids?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

誰ツ都不明白 2025-02-16 12:23:24

来自发送

如果您想发送答复并希望将电子邮件发送到线程,请确保:

因此,您需要您要回复的原始消息的消息ID。这与线程ID不同。

message['In-Reply-To'] = message_id
message['References'] = message_id

From sending

If you're trying to send a reply and want the email to thread, make sure that:

  • The Subject headers match
  • The References and In-Reply-To headers follow the RFC 2822 standard.
  • For information on sending a message from a draft, see Creating Drafts.

So you need the message id of the original message you are replying to. This is not the same as thread id.

message['In-Reply-To'] = message_id
message['References'] = message_id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文