애플리케이션을위한 Python의 간단한 Gmail API 클라이언트.
현재 지원되는 행동 :
필요한 유일한 설정은 Google에서 Oauth 2.0 클라이언트 ID 파일을 다운로드하여 응용 프로그램을 승인하는 것입니다.
이것은 https://console.developers.google.com/apis/credentials에서 수행 할 수 있습니다. 위의 링크를 클릭 한 후 (적절한 계정에 로그인) Google API에 대한 자격 증명을 만들지 않은 사람들을 위해
이 인증의 프로젝트 선택/생성 (새 프로젝트를 작성하는 경우 OAuth 동의 화면을 구성해야합니다. 응용 프로그램 이름 만 설정하면됩니다).
"대시 보드"탭을 클릭 한 다음 "API 및 서비스 활성화"를 클릭하십시오. Gmail을 검색하고 활성화하십시오.
자격 증명 탭을 클릭 한 다음 "자격 증명 만들기"> "Oauth Client ID"를 클릭하십시오.
이것이 어떤 종류의 응용 프로그램을 선택하고 기억에 남는 이름을 알려주십시오. 자격 증명에 필요한 모든 정보를 작성하십시오 (예 : "웹 응용 프로그램"을 선택하는 경우 승인 된 리디렉션 URI를 추가하십시오. 더 많은 정보는 https://developers.google.com/identity/protocols/oauth2를 참조하십시오).
자격 증명 화면으로 돌아가서 방금 만든 자격 증명 옆에있는 다운로드 아이콘을 JSON 객체로 다운로드하십시오.
이 파일을 "client_secret.json"으로 저장하고 응용 프로그램의 루트 디렉토리에 배치하십시오. ( Gmail 클래스는 다른 이름으로 이름을 지정하기로 선택한 경우이 파일의 이름에 대한 인수를 사용합니다.)
Gmail 클래스의 새 인스턴스를 처음 만들 때 브라우저 창이 열리고 응용 프로그램에 대한 권한을 부여하라는 메시지가 표시됩니다. 이렇게하면 "gmail-token.json"이라는 파일에 액세스 토큰을 절약 할 수 있으며 한 번만 발생하면됩니다.
당신은 이제 가기에 좋습니다!
인증 방법에 대한 참고 사항 : Google의 권한을 사용하는 것이 매우 안전하고 Google의 많은 보안 조치와 충돌하지 않기 때문에 IMAP/SMTP를 통해 Username-Password 인증 (IMAP/SMTP를 통해)을 사용하지 않기로 결정했습니다.
pip (Python3)를 사용하여 설치하십시오.
pip3 install simplegmail from simplegmail import Gmail
gmail = Gmail () # will open a browser window to ask you to log in and authenticate
params = {
"to" : "[email protected]" ,
"sender" : "[email protected]" ,
"subject" : "My first email" ,
"msg_html" : "<h1>Woah, my first email!</h1><br />This is an HTML email." ,
"msg_plain" : "Hi n This is a plain text email." ,
"signature" : True # use my account signature
}
message = gmail . send_message ( ** params ) # equivalent to send_message(to="[email protected]", sender=...) from simplegmail import Gmail
gmail = Gmail ()
params = {
"to" : "[email protected]" ,
"sender" : "[email protected]" ,
"cc" : [ "[email protected]" ],
"bcc" : [ "[email protected]" , "[email protected]" ],
"subject" : "My first email" ,
"msg_html" : "<h1>Woah, my first email!</h1><br />This is an HTML email." ,
"msg_plain" : "Hi n This is a plain text email." ,
"attachments" : [ "path/to/something/cool.pdf" , "path/to/image.jpg" , "path/to/script.py" ],
"signature" : True # use my account signature
}
message = gmail . send_message ( ** params ) # equivalent to send_message(to="[email protected]", sender=...)더 쉬울 수 없었습니다!
from simplegmail import Gmail
gmail = Gmail ()
# Unread messages in your inbox
messages = gmail . get_unread_inbox ()
# Starred messages
messages = gmail . get_starred_messages ()
# ...and many more easy to use functions can be found in gmail.py!
# Print them out!
for message in messages :
print ( "To: " + message . recipient )
print ( "From: " + message . sender )
print ( "Subject: " + message . subject )
print ( "Date: " + message . date )
print ( "Preview: " + message . snippet )
print ( "Message Body: " + message . plain ) # or message.html from simplegmail import Gmail
gmail = Gmail ()
messages = gmail . get_unread_inbox ()
message_to_read = messages [ 0 ]
message_to_read . mark_as_read ()
# Oops, I want to mark as unread now
message_to_read . mark_as_unread ()
message_to_star = messages [ 1 ]
message_to_star . star ()
message_to_trash = messages [ 2 ]
message_to_trash . trash ()
# ...and many more functions can be found in message.py! from simplegmail import Gmail
gmail = Gmail ()
# Get the label objects for your account. Each label has a specific ID that
# you need, not just the name!
labels = gmail . list_labels ()
# To find a label by the name that you know (just an example):
finance_label = list ( filter ( lambda x : x . name == 'Finance' , labels ))[ 0 ]
messages = gmail . get_unread_inbox ()
# We can add/remove a label
message = messages [ 0 ]
message . add_label ( finance_label )
# We can "move" a message from one label to another
message . modify_labels ( to_add = labels [ 10 ], to_remove = finance_label )
# ...check out the code in message.py for more! from simplegmail import Gmail
gmail = Gmail ()
messages = gmail . get_unread_inbox ()
message = messages [ 0 ]
if message . attachments :
for attm in message . attachments :
print ( 'File: ' + attm . filename )
attm . save () # downloads and saves each attachment under it's stored
# filename. You can download without saving with `attm.download()` from simplegmail import Gmail
from simplegmail . query import construct_query
gmail = Gmail ()
# Unread messages in inbox with label "Work"
labels = gmail . list_labels ()
work_label = list ( filter ( lambda x : x . name == 'Work' , labels ))[ 0 ]
messages = gmail . get_unread_inbox ( labels = [ work_label ])
# For even more control use queries:
# Messages that are: newer than 2 days old, unread, labeled "Finance" or both "Homework" and "CS"
query_params = {
"newer_than" : ( 2 , "day" ),
"unread" : True ,
"labels" :[[ "Work" ], [ "Homework" , "CS" ]]
}
messages = gmail . get_messages ( query = construct_query ( query_params ))
# We could have also accomplished this with
# messages = gmail.get_unread_messages(query=construct_query(newer_than=(2, "day"), labels=[["Work"], ["Homework", "CS"]]))
# There are many, many different ways of achieving the same result with search. from simplegmail import Gmail
from simplegmail . query import construct_query
gmail = Gmail ()
# For even more control use queries:
# Messages that are either:
# newer than 2 days old, unread, labeled "Finance" or both "Homework" and "CS"
# or
# newer than 1 month old, unread, labeled "Top Secret", but not starred.
labels = gmail . list_labels ()
# Construct our two queries separately
query_params_1 = {
"newer_than" : ( 2 , "day" ),
"unread" : True ,
"labels" :[[ "Finance" ], [ "Homework" , "CS" ]]
}
query_params_2 = {
"newer_than" : ( 1 , "month" ),
"unread" : True ,
"labels" : [ "Top Secret" ],
"exclude_starred" : True
}
# construct_query() will create both query strings and "or" them together.
messages = gmail . get_messages ( query = construct_query ( query_params_1 , query_params_2 )) 쿼리로 수행 할 수있는 작업에 대한 자세한 내용은 query.py 에서 construct_query() 의 DocString을 읽으십시오.
이 프로젝트에 추가 된 기능 또는이 프로젝트에 버그가있는 경우 문제를 게시하거나 풀 요청을 제출하여 알려주십시오!