Gmail 邮件显示通过 Python 脚本导入后的实际上传日期,而不是 eml 文件中的日期

Gmail message shows actual upload date after import via Python script and not the date from the eml file

提问人:x0100 提问时间:11/9/2023 最后编辑:x0100 更新时间:11/9/2023 访问量:58

问:

以下 Python 脚本应导入位于特定文件夹中的 eml 文件并分配预定义的标签。一般来说,脚本正在工作并完成它的工作。

只有一个小问题,而不是eml中的时间戳,在Gmail界面中,我看到了导入的时间戳。这样,电子邮件就无法正确地混合到时间线中。

是否可以将“收到:”日期调整为 eml 的日期,就像它原来一样?

我以为我已经通过设置“internalDate”解决了这个问题。

import os
import base64
import email
import json
import imaplib
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from datetime import datetime

# Gmail API settings
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
CLIENT_SECRET_FILE = 'credentials.json'
GMAIL_USER = '[email protected]'

# Label to use in Gmail (e.g., "backup")
GMAIL_LABEL = 'backup'

# Directory containing your local .eml files
LOCAL_EML_DIR = './eml/'

# Define a function to get a Gmail API service
def get_gmail_service():
    creds = None
    # The file token.json stores the user's access and refresh tokens.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
        creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    service = build('gmail', 'v1', credentials=creds)
    return service

def get_label_id(service, label_name):
    results = service.users().labels().list(userId=GMAIL_USER).execute()
    labels = results.get('labels', [])
    
    for label in labels:
        if label['name'] == label_name:
            return label['id']
    
    return None

# Upload local .eml files to Gmail using the Gmail API
def upload_eml_files_to_gmail(service, label_name, eml_dir):
    label_id = get_label_id(service, label_name)  # Get the label ID by name
    if not label_id:
        print(f"Label '{label_name}' not found in Gmail.")
        return

    for filename in os.listdir(eml_dir):
        if filename.endswith('.eml'):
            eml_path = os.path.join(eml_dir, filename)
            
            # Read the .eml file
            with open(eml_path, 'rb') as eml_file:
                eml_data = eml_file.read()
            
            # Extract the INTERNALDATE from the EML file
            eml_message = email.message_from_bytes(eml_data)
            internaldate = eml_message.get('Date')
            
            # Convert internaldate to Unix timestamp and then to an integer
            internaldate = datetime.strptime(internaldate, '%a, %d %b %Y %H:%M:%S %z').timestamp()
            internaldate = int(internaldate)
            
            # Create a message with the eml file content and internalDate
            message = base64.urlsafe_b64encode(eml_data).decode('utf-8')
            
            message = {
                'raw': message,
                'internalDate': str(internaldate),
                'labelIds': [label_id]  # Assign the label to the message
            }
            
            # Upload the message to Gmail with the specified label
            service.users().messages().insert(userId=GMAIL_USER, body=message).execute()

# Main function to run the script
def main():
    service = get_gmail_service()  # Authenticate with Gmail API
    upload_eml_files_to_gmail(service, GMAIL_LABEL, LOCAL_EML_DIR)  # Upload .eml files to Gmail

if __name__ == '__main__':
    main()

原始时间戳:enter image description here

Gmail 时间戳(显示上传时间):enter image description here

Gmail 中的邮件标头(显示两个时间戳):enter image description here

python gmail-api eml

评论

1赞 SputnikDrunk2 11/9/2023
您能否分享使用现有脚本时在结果电子邮件中看到的实际日期的屏幕截图?我之所以问,是因为当我尝试在示例.eml文件上使用时,我收到了一个日期列出的结果,即“Fri, 21 Nov 1997 09:55:06 -0600”。internaldate880127706
0赞 x0100 11/9/2023
我添加了屏幕截图。在比较 Gmail 中的原始 eml 和之后的邮件标题时,我可以看到添加了一行 Received: from 919466537526 named unknown by gmailapi.google.com with HTTPREST;Thu, 9 Nov 2023 04:29:33 -0800 看起来这个时间戳用于在 Gmail 界面中可见的日期。

答: 暂无答案