Python에서 IGmailClient를 사용한 Gmail 메시지 관리
.NET을 통한 Python용 Aspose.Email은 Gmail 계정 작업을 위한 확장 기능을 제공합니다 IGmailClient 클래스. 여기에는 메시지 목록 조회, 전송, 추가, 가져오기, 삭제 및 Gmail 필터 관리가 포함됩니다.
사용하기 전에 IGmailClient, 클라이언트 ID, 클라이언트 시크릿, 리프레시 토큰 및 이메일 주소로 인증합니다. 그런 다음 Gmail 클라이언스 인스턴스를 생성합니다:
from aspose.email.clients.google import GmailClient
client = GmailClient.get_instance(client_id, client_secret, refresh_token, email)
Gmail API로 이메일 전송
Gmail 계정을 통해 첨부 파일이 있는 이메일을 보내려면 다음을 사용하십시오 send_message 메서드 IGmailClient 클래스.
다음 코드 예제는 Gmail API를 사용하여 첨부 파일이 있는 이메일을 생성하고 전송하는 방법을 보여줍니다:
from aspose.email import MailMessage, Attachment
# Create the message
message = MailMessage("sender@example.com", "recipient@example.com", "Weekly Report", "Attached is the weekly report.")
# Add an attachment
attachment_path = "path/to/report.pdf"
message.attachments.add(Attachment(attachment_path))
# Send the message
message_id = client.send_message(message)
print(f"Message with attachment sent! ID: {message_id}")
Gmail 폴더에 메시지 추가
표준 분류를 건너뛰고 Gmail 사서함에 직접 메시지를 추가하려면 다음 방법을 사용하십시오:
- append_message(msg) 기본 동작을 위해.
- append_message(msg, label_name) 사용자 정의 라벨을 지정하려면.
아래 코드 예제는 Gmail 클라이언트를 사용하여 이메일 메시지를 생성하고 특정 라벨과 함께 수신자의 인박스에 추가하는 방법을 보여줍니다:
message = MailMessage("sender@example.com", "recipient@example.com", "Subject for inbox message", "Body of the message")
# Append the message to the inbox with a label
message_id = client.append_message(message, "INBOX")
print(f"Message appended to the Inbox. ID: {message_id}")
Gmail 메시지 목록
Gmail 사서함의 모든 메시지 목록을 다음을 사용하여 가져올 수 있습니다 list_messages() 메서드 IGmailClient 클래스. 반환된 리스트의 각 항목은 GmailMessageInfo ‘id’ 및 ‘thread_id’와 같은 가벼운 메타데이터를 포함하는 객체.
아래 코드 예제는 사용자 인박스에 있는 모든 Gmail 메시지 정보를 검색하고 표시하는 방법을 보여줍니다:
# List all Gmail messages
messages = client.list_messages()
# Print basic info for each message
for i, msg_info in enumerate(messages):
print(f"Message {i + 1}: ID = {msg_info.id}, Thread ID = {msg_info.thread_id}")
Gmail 메시지 내용 가져오기
메시지 메타데이터를 가져온 후, 사용하십시오 fetch_message(message_id) 특정 메시지의 전체 내용을 다음 형식으로 다운로드하려면 MailMessage 객체. 이를 통해 제목, 본문, 첨부 파일 및 기타 메시지 세부 정보를 액세스할 수 있습니다.
아래 코드 예제는 사용자 인박스에서 처음 세 개의 Gmail 메시지를 가져와 내용을 표시하는 방법을 보여줍니다:
# Fetch and display content for the first 3 messages
for i in range(min(3, len(messages))):
message = client.fetch_message(messages[i].id)
print(f"Message {i + 1}")
print("Subject:", message.subject)
print("Body:", message.body)
Gmail 메시지 삭제
다음 사용 delete_message(message_id, move_to_trash) 메서드 IGmailClient 메시지를 삭제하는 클래스입니다. 두 번째 매개변수를 생략하거나 False를 전달하면 영구 삭제하거나, 휴지통으로 이동(비영구)할 수 있습니다.
아래 코드 예제는 메시지 목록(예: 이메일) 중 처음 세 개를 휴지통으로 이동하는 방법을 보여줍니다:
# Move the first 3 messages to trash
for i in range(min(3, len(messages))):
client.delete_message(messages[i].id, True) # True = move to trash
print(f"Message {i + 1} moved to trash.")
Gmail 필터 관리
Aspose.Email for Python은 다음과 같은 메서드를 제공합니다. IGmailClient 제목줄을 기준으로 수신 이메일을 정리하고 Google 이메일 계정의 기존 필터를 관리하기 위해 필터 설정 프로세스를 자동화하는 클래스:
list_filters()- 사서함에 적용된 모든 필터를 검색합니다.create_filter(filter)- 사용자 지정 기준 및 동작으로 새 필터를 추가합니다.get_filter(id)- 특정 필터 세부 정보를 가져옵니다.delete_filter(id)- 필터를 영구 제거합니다.
Gmail 필터 생성 및 목록
다음 코드 예제는 Google 클라이언트를 위해 Aspose.Email 라이브러리를 사용해 이메일 필터를 생성하고 관리하는 방법을 보여줍니다:
from aspose.email.clients.google.filters import Filter, Criteria, Action
# Create a new filter
filter_obj = Filter()
filter_obj.matching_criteria = Criteria()
filter_obj.matching_criteria.subject = "Important"
filter_obj.action = Action()
filter_obj.action.add_label_ids = ["IMPORTANT"]
# Create the filter
filter_id = client.create_filter(filter_obj)
print(f"Filter created! ID: {filter_id}")
# List all filters
filters = client.list_filters()
for f in filters:
print(f"Filter ID: {f.id}")
Gmail 필터 삭제
다음 코드 예제는 Gmail 계정에서 모든 필터를 제거하는 방법을 보여줍니다:
filters = client.list_filters()
# Delete each filter
for f in filters:
client.delete_filter(f.id)
print(f"Filter ID: {f.id} deleted.")