Skip to content

Instantly share code, notes, and snippets.

@thomasthaddeus
Created June 2, 2024 07:08
Show Gist options
  • Save thomasthaddeus/9e2d3e4ee1546f8f5ad2e7b3fffca605 to your computer and use it in GitHub Desktop.
Save thomasthaddeus/9e2d3e4ee1546f8f5ad2e7b3fffca605 to your computer and use it in GitHub Desktop.
This gist is here to answer a question from a user on reddit

Email Autoreply

Setup

By following these steps, you will have an email rule that moves emails containing "unfortunately" to a specific folder and marks them as read, along with sending an auto-reply of "k" to the sender.

Setting Up the Rule (for Outlook)

  1. Open Outlook and go to the Home tab.
  2. Click on Rules and then Manage Rules & Alerts.
  3. In the Rules and Alerts dialog box, click New Rule.
  4. Select Apply rule on messages I receive and click Next.
  5. Check with specific words in the body and click on specific words.
  6. Type "unfortunately" and click Add, then OK.
  7. Click Next.
  8. Check move it to the specified folder.
  9. Click on specified and choose the folder you want to move these emails to, then click OK.
  10. Click Next.
  11. Check mark as read and click Next.
  12. Click Next again to skip any exceptions.
  13. Give your rule a name and click Finish.

Setting Up the AutoReply (for Outlook)

  1. Go to File > Automatic Replies.
  2. Select Send automatic replies.
  3. Check Only send during this time range (optional).
  4. Enter your auto-reply message "k" in both the Inside My Organization and Outside My Organization tabs.
  5. Click OK to save.

Setting Up the Rule (for Gmail)

  1. Open Gmail and click on the gear icon, then select See all settings.
  2. Go to the Filters and Blocked Addresses tab.
  3. Click Create a new filter.
  4. In the Has the words field, type "unfortunately".
  5. Click Create filter.
  6. Check Skip the Inbox (Archive it), Apply the label (choose or create a new label/folder), and Mark as read.
  7. Click Create filter.

Setting Up the AutoReply (for Gmail)

  1. Open Gmail and click on the gear icon, then select See all settings.
  2. Go to the Vacation responder section at the bottom.
  3. Check Vacation responder on.
  4. Enter the subject and body of your auto-reply message "k".
  5. Select the date range (optional).
  6. Click Save Changes.

To set this up programmatically, you can use the Microsoft Graph API for Outlook or the Gmail API for Gmail. Here's a general outline for both.

Using Microsoft Graph API (Outlook)

  1. Register your application in Azure AD to get the necessary permissions.
  2. Authenticate using OAuth2 to get an access token.
  3. Set up a rule to move emails and mark them as read.
  4. Set up an auto-reply.

Step-by-Step

  1. Register your application in Azure AD

    • Go to the Azure portal.
    • Register a new application.
    • Note the Application (client) ID and Directory (tenant) ID.
    • Generate a client secret.
  2. Authenticate using OAuth2

    • Use the Microsoft Identity platform to authenticate and get an access token.
  3. Set up a rule

    import requests
    
    # Replace with your values
    tenant_id = 'YOUR_TENANT_ID'
    client_id = 'YOUR_CLIENT_ID'
    client_secret = 'YOUR_CLIENT_SECRET'
    access_token = 'YOUR_ACCESS_TOKEN'
    
    # Get access token
    def get_access_token():
        url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        body = {
            'client_id': client_id,
            'scope': 'https://graph.microsoft.com/.default',
            'client_secret': client_secret,
            'grant_type': 'client_credentials'
        }
        response = requests.post(url, headers=headers, data=body)
        return response.json().get('access_token')
    
    access_token = get_access_token()
    
    # Create the rule
    url = "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messageRules"
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    body = {
        "displayName": "Move unfortunately emails",
        "sequence": 1,
        "conditions": {
            "bodyContains": ["unfortunately"]
        },
        "actions": {
            "moveToFolder": "YOUR_FOLDER_ID",
            "markAsRead": True
        }
    }
    response = requests.post(url, headers=headers, json=body)
    print(response.json())
  4. Set up an auto-reply

    url = "https://graph.microsoft.com/v1.0/me/mailboxSettings"
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    body = {
        "automaticRepliesSetting": {
            "status": "alwaysEnabled",
            "internalReplyMessage": {
                "message": "k"
            },
            "externalReplyMessage": {
                "message": "k"
            }
        }
    }
    response = requests.patch(url, headers=headers, json=body)
    print(response.json())

Using Gmail API

  1. Enable the Gmail API in the Google Cloud Console.
  2. Authenticate using OAuth2 to get an access token.
  3. Set up a filter to move emails and mark them as read.
  4. Set up an auto-reply.

Step-by-Step2

  1. Enable the Gmail API

    • Go to the Google Cloud Console.
    • Enable the Gmail API.
    • Create OAuth 2.0 credentials.
  2. Authenticate using OAuth2

    • Use the Google OAuth2 library to authenticate and get an access token.
  3. Set up a filter

    from googleapiclient.discovery import build
    from google.oauth2.credentials import Credentials
    
    # Replace with your token.json path
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    service = build('gmail', 'v1', credentials=creds)
    
    # Create the filter
    filter = {
        'criteria': {
            'query': 'unfortunately'
        },
        'action': {
            'removeLabelIds': ['INBOX'],
            'addLabelIds': ['Label_123456'],  # Replace with your label ID
            'markAsRead': True
        }
    }
    result = service.users().settings().filters().create(userId='me', body=filter).execute()
    print(result)
  4. Set up an auto-reply

    from googleapiclient.discovery import build
    from google.oauth2.credentials import Credentials
    
    # Replace with your token.json path
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    service = build('gmail', 'v1', credentials=creds)
    
    # Set up auto-reply
    vacation_settings = {
        'enableAutoReply': True,
        'responseSubject': '',
        'responseBodyPlainText': 'k',
        'restrictToContacts': False,
        'restrictToDomain': False,
    }
    result = service.users().settings().updateVacation(userId='me', body=vacation_settings).execute()
    print(result)

These scripts provide a starting point for setting up your desired email automation programmatically. Make sure to replace placeholders with your actual values and handle the authentication process according to your needs.

url = "https://graph.microsoft.com/v1.0/me/mailboxSettings"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
body = {
"automaticRepliesSetting": {
"status": "alwaysEnabled",
"internalReplyMessage": {
"message": "k"
},
"externalReplyMessage": {
"message": "k"
}
}
}
response = requests.patch(url, headers=headers, json=body)
print(response.json())
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
# Replace with your token.json path
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
service = build('gmail', 'v1', credentials=creds)
# Set up auto-reply
vacation_settings = {
'enableAutoReply': True,
'responseSubject': '',
'responseBodyPlainText': 'k',
'restrictToContacts': False,
'restrictToDomain': False,
}
result = service.users().settings().updateVacation(userId='me', body=vacation_settings).execute()
print(result)
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
# Replace with your token.json path
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
service = build('gmail', 'v1', credentials=creds)
# Create the filter
filter = {
'criteria': {
'query': 'unfortunately'
},
'action': {
'removeLabelIds': ['INBOX'],
'addLabelIds': ['Label_123456'], # Replace with your label ID
'markAsRead': True
}
}
result = service.users().settings().filters().create(userId='me', body=filter).execute()
print(result)
import requests
# Replace with your values
tenant_id = 'YOUR_TENANT_ID'
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
access_token = 'YOUR_ACCESS_TOKEN'
# Get access token
def get_access_token():
url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
body = {
'client_id': client_id,
'scope': 'https://graph.microsoft.com/.default',
'client_secret': client_secret,
'grant_type': 'client_credentials'
}
response = requests.post(url, headers=headers, data=body)
return response.json().get('access_token')
access_token = get_access_token()
# Create the rule
url = "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messageRules"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
body = {
"displayName": "Move unfortunately emails",
"sequence": 1,
"conditions": {
"bodyContains": ["unfortunately"]
},
"actions": {
"moveToFolder": "YOUR_FOLDER_ID",
"markAsRead": True
}
}
response = requests.post(url, headers=headers, json=body)
print(response.json())
import requests
# Replace with your values
tenant_id = 'YOUR_TENANT_ID'
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
access_token = 'YOUR_ACCESS_TOKEN'
# Get access token
def get_access_token():
url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
body = {
'client_id': client_id,
'scope': 'https://graph.microsoft.com/.default',
'client_secret': client_secret,
'grant_type': 'client_credentials'
}
response = requests.post(url, headers=headers, data=body)
return response.json().get('access_token')
access_token = get_access_token()
# Create the rule
url = "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messageRules"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
body = {
"displayName": "Move unfortunately emails",
"sequence": 1,
"conditions": {
"bodyContains": ["unfortunately"]
},
"actions": {
"moveToFolder": "YOUR_FOLDER_ID",
"markAsRead": True
}
}
response = requests.post(url, headers=headers, json=body)
print(response.json())
```
4. Set up an auto-reply
```python
url = "https://graph.microsoft.com/v1.0/me/mailboxSettings"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
body = {
"automaticRepliesSetting": {
"status": "alwaysEnabled",
"internalReplyMessage": {
"message": "k"
},
"externalReplyMessage": {
"message": "k"
}
}
}
response = requests.patch(url, headers=headers, json=body)
print(response.json())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment