Skip to content

Instantly share code, notes, and snippets.

@GGontijo
Created June 25, 2024 20:14
Show Gist options
  • Save GGontijo/804dd21165725c28e46a88d52c183ddb to your computer and use it in GitHub Desktop.
Save GGontijo/804dd21165725c28e46a88d52c183ddb to your computer and use it in GitHub Desktop.
Office365EmailClient V2.0
import requests
import json
import time
class Office365EmailClient:
def __init__(self, client_id: str, client_secret: str, tenant_id: str):
self.client_id = client_id
self.client_secret = client_secret
self.tenant_id = tenant_id
self.token = None
self.token_expires_at = 0
self.base_url = 'https://outlook.office365.com/api/v1.0/'
self.auth_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
self.message = {
"Message": {
"Subject": "",
"Body": {
"ContentType": "Text",
"Content": ""
},
"ToRecipients": [],
"CcRecipients": [],
"Attachments": []
},
"SaveToSentItems": "true"
}
def _get_token(self):
data = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'scope': 'https://outlook.office365.com/.default',
'grant_type': 'client_credentials'
}
response = requests.post(self.auth_url, data=data)
token_response = response.json()
if 'access_token' in token_response:
self.token = token_response['access_token']
self.token_expires_at = time.time() + token_response['expires_in']
else:
raise Exception(f"Erro ao adquirir token: {token_response.get('error')}, {token_response.get('error_description')}")
def _ensure_token(self):
if self.token is None or time.time() >= self.token_expires_at:
self._get_token()
def set_subject(self, subject: str):
self.message["Message"]["Subject"] = subject
def set_body(self, body: str, content_type: str = "Text"):
self.message["Message"]["Body"]["ContentType"] = content_type
self.message["Message"]["Body"]["Content"] = body
def add_recipient(self, email: str):
self.message["Message"]["ToRecipients"].append({
"EmailAddress": {
"Address": email
}
})
def add_cc(self, email: str):
self.message["Message"]["CcRecipients"].append({
"EmailAddress": {
"Address": email
}
})
def add_attachment(self, filename: str, content: str):
self.message["Message"]["Attachments"].append({
"@odata.type": "#Microsoft.OutlookServices.FileAttachment",
"Name": filename,
"ContentBytes": content
})
def send_mail(self, user_email: str):
self._ensure_token()
headers = {
'Authorization': f'Bearer {self.token}',
'Content-Type': 'application/json'
}
endpoint = f'{self.base_url}users/{user_email}/sendMail'
response = requests.post(endpoint, headers=headers, data=json.dumps(self.message))
if response.status_code == 202:
print("E-mail enviado com sucesso")
else:
raise Exception(f"Erro ao enviar e-mail: {response.status_code}, {response.text}")
# Uso da classe
client = Office365EmailClient(client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', tenant_id='YOUR_TENANT_ID')
client.set_subject("Assunto de Teste")
client.set_body("Este é um e-mail de teste.")
client.add_recipient("recipient@example.com")
client.add_cc("cc@example.com")
client.add_attachment("test.txt", "VGhpcyBpcyBhIHRlc3QgYXR0YWNobWVudC4=") # Base64 content
client.send_mail("example@domain.com.br")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment