Initial commit: Gmail Automation RPA
Gmail API를 활용한 이메일 자동화 RPA 프로그램 Features: - Gmail API 인증 및 연동 - 키워드/발신자 기반 자동 분류 - 조건별 자동 답장 기능 - 통계 리포트 생성 - 커스터마이징 가능한 JSON 설정 Modules: - gmail_automation.py: 메인 프로그램 - gmail_auth.py: Gmail API 인증 - email_classifier.py: 이메일 분류 로직 - auto_reply.py: 자동 답장 로직 - config.json.example: 설정 예시 Documentation: - 상세한 README.md (설치, 사용법, 트러블슈팅) - Google Cloud Console 설정 가이드 - 실제 효과 측정 데이터
This commit is contained in:
91
gmail_auth.py
Normal file
91
gmail_auth.py
Normal file
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
Gmail API 인증 모듈
|
||||
"""
|
||||
|
||||
import os.path
|
||||
import pickle
|
||||
from google.auth.transport.requests import Request
|
||||
from google.oauth2.credentials import Credentials
|
||||
from google_auth_oauthlib.flow import InstalledAppFlow
|
||||
from googleapiclient.discovery import build
|
||||
|
||||
# Gmail API 스코프
|
||||
SCOPES = [
|
||||
'https://www.googleapis.com/auth/gmail.modify',
|
||||
'https://www.googleapis.com/auth/gmail.send',
|
||||
'https://www.googleapis.com/auth/gmail.labels'
|
||||
]
|
||||
|
||||
|
||||
class GmailAuth:
|
||||
"""Gmail API 인증 클래스"""
|
||||
|
||||
def __init__(self, credentials_file='credentials.json', token_file='token.pickle'):
|
||||
"""
|
||||
초기화
|
||||
|
||||
Args:
|
||||
credentials_file: Google Cloud Console에서 다운로드한 credentials.json
|
||||
token_file: 인증 토큰 저장 파일
|
||||
"""
|
||||
self.credentials_file = credentials_file
|
||||
self.token_file = token_file
|
||||
self.creds = None
|
||||
|
||||
def authenticate(self):
|
||||
"""Gmail API 인증"""
|
||||
# 기존 토큰이 있으면 로드
|
||||
if os.path.exists(self.token_file):
|
||||
with open(self.token_file, 'rb') as token:
|
||||
self.creds = pickle.load(token)
|
||||
|
||||
# 토큰이 없거나 유효하지 않으면 새로 인증
|
||||
if not self.creds or not self.creds.valid:
|
||||
if self.creds and self.creds.expired and self.creds.refresh_token:
|
||||
print("🔄 토큰 갱신 중...")
|
||||
self.creds.refresh(Request())
|
||||
else:
|
||||
if not os.path.exists(self.credentials_file):
|
||||
print("❌ credentials.json 파일이 없습니다!")
|
||||
print("📝 설정 방법:")
|
||||
print("1. https://console.cloud.google.com 접속")
|
||||
print("2. 프로젝트 생성")
|
||||
print("3. Gmail API 활성화")
|
||||
print("4. OAuth 2.0 클라이언트 ID 생성")
|
||||
print("5. credentials.json 다운로드")
|
||||
print("6. 이 폴더에 credentials.json 파일 복사")
|
||||
raise FileNotFoundError("credentials.json 파일이 필요합니다.")
|
||||
|
||||
print("🔐 Gmail 인증 시작...")
|
||||
print("브라우저가 열립니다. Google 계정으로 로그인하세요.")
|
||||
flow = InstalledAppFlow.from_client_secrets_file(
|
||||
self.credentials_file, SCOPES
|
||||
)
|
||||
self.creds = flow.run_local_server(port=0)
|
||||
|
||||
# 토큰 저장
|
||||
with open(self.token_file, 'wb') as token:
|
||||
pickle.dump(self.creds, token)
|
||||
|
||||
print("✅ 인증 완료!")
|
||||
|
||||
return self.creds
|
||||
|
||||
def get_service(self):
|
||||
"""Gmail 서비스 객체 반환"""
|
||||
if not self.creds:
|
||||
self.authenticate()
|
||||
|
||||
try:
|
||||
service = build('gmail', 'v1', credentials=self.creds)
|
||||
return service
|
||||
except Exception as e:
|
||||
print(f"❌ Gmail 서비스 생성 실패: {e}")
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 테스트
|
||||
auth = GmailAuth()
|
||||
service = auth.get_service()
|
||||
print("✅ Gmail API 연결 성공!")
|
||||
Reference in New Issue
Block a user