Я планирую использовать Gmail API для отправки электронных писем.
Я также буду использовать аутентификацию OAuth 2.0.
Механизм аутентификации указан в кратком руководстве:
from __future__ import print_function
import os.path
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
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', 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())
try:
# Call the Gmail API
service = build('gmail', 'v1', credentials=creds)
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
return
print('Labels:')
for label in labels:
print(label['name'])
except HttpError as error:
# TODO(developer) - Handle errors from gmail API.
print(f'An error occurred: {error}')
if __name__ == '__main__':
main()
Один из примеров отправки электронного письма:
def gmailAPISendEmail(self, message, userID = "me"):
try:
service = self.gmailAPIService
self.GLogger.info("Attempting to send email message")
try:
response = service.users().messages().send(userId=userID, body=message).execute()
except socket.timeout:
pass
except:
self.GLogger.error("Failed to send email message")
tb = traceback.format_exc()
self.GLogger.exception(tb)
try:
responseID = str(response['id'])
except:
responseID = "CouldNotParseID"
self.GLogger.info("Successfully sent email message with ID (" + responseID +")")
return responseID
except:
self.GLogger.error("Failed to send email message")
tb = traceback.format_exc()
self.GLogger.exception(tb)
return False
Пример создания электронного письма:
def createEmaiLWithAttachments(self,sendTo, sendFrom, subject,emailMsg , attachments, html=False):
try:
mimeMessage = MIMEMultipart()
mimeMessage['to'] = sendTo
mimeMessage['from'] = sendFrom
mimeMessage['subject'] = subject
if html:
msg= MIMEText(emailMsg, 'html')
else:
msg= MIMEText(emailMsg)
mimeMessage.attach(msg)
for attachment in attachments:
attachment_name = attachment[0]
attachment_instance = attachment[1]
content_type, encoding = mimetypes.guess_type(attachment_name)
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)
if main_type == 'text':
msg = MIMEText(attachment_instance, _subtype=sub_type)
elif main_type == 'image':
msg = MIMEImage(attachment_instance, _subtype=sub_type)
elif main_type == 'audio':
msg = MIMEAudio(attachment_instance, _subtype=sub_type)
else:
msg = MIMEBase(main_type, sub_type)
msg.set_payload(attachment_instance)
msg.add_header('Content-Disposition', 'attachment', filename=attachment_name)
mimeMessage.attach(msg)
raw_string = base64.urlsafe_b64encode(mimeMessage.as_string().encode()).decode()
theMessage = {'raw': raw_string}
return theMessage
except:
self.GLogger.error("An error occurred in createEmaiLWithAttachments")
tb = traceback.format_exc()
self.GLogger.exception(tb)
return False
Я хотел бы знать, какие firewall
требования?
Я попытался найти требования к порту и сайту/домену, но не нашел никакой информации для Gmail API
.
Мне нужно знать firewall
требования к таким вещам, как:
Конкретно по сервису Gmail есть аналогичный вопрос здесь.
Где он делает ссылку на документацию Google здесь и предоставляет следующее:
**The asterisk (*) is a wild card, and represents any value except a period**.
*.client-channel.google.com
accounts.google.com
apis.google.com
clients*.google.com
contacts.google.com
hangouts.google.com
*.googleusercontent.com
mail.google.com
ssl.gstatic.com
www.google.com
www.gstatic.com
ogs.google.com
play.google.com
В качестве альтернативы, если у вас есть подписка на Google Workspace и это реализовано через нее, вы можете открыть Билет поддержки разработчиков, чтобы проверить, можно ли поделиться какой-либо дополнительной информацией, относящейся к вашему делу.
Я отправил заявку в службу поддержки разработчиков в службу поддержки Google Workspace. Сотрудник Google, работающий с API, заявил следующее.
Для общего трафика API-запрос/ответ для Google APIs
:
*.googleapis.com
443 & 80
TCP
Для общего трафика аутентификация для Google APIs
:
*.google.com
443 & 80
TCP
Хост для трафика Gmail API
ответ на запрос, в частности, согласно здесь, будет:
gmail.googleapis.com
443 & 80
TCP
Ниже представлена информация, предоставленная участником репозитория google-api-python-client
Github.
python
Gmail API
использует конечные точки, определенные в документе обнаружения для Gmail V1 API здесь.Google Workspace
брандмауэра.
это может помочь stackoverflow.com/a/50252843/1841839 или это может помочь support.google.com/a/answer/2589954?hl=ru