PYTHON   44
manage Gandi Mail Redir py
Guest on 3rd February 2023 01:31:18 PM


  1. #!/usr/bin/python3
  2. # Management of gandi mail redirections
  3. #
  4. ################################################# #####
  5. # imports
  6. ################################################# #####
  7. import requests
  8. import json
  9. import sys
  10. from configGandiAPI import * # Initialization of api_key variable
  11. ################################################# #####
  12. # Initiate variables
  13. ################################################# #####
  14. debug=False
  15. # api_key = 'XXX' -> Variable entered in the configGandiAPI.py file
  16. api_url_base_redir = "https://api.gandi.net/v5/email/forwards/"
  17. api_url_base_mailboxes = "https://api.gandi.net/v5/email/mailboxes/"
  18. ################################################# #####
  19. # Functions
  20. ################################################# #####
  21. def print_usage():
  22.         print("Usage:")
  23.         print(" ", sys.argv[0], "-count domain\n\t-> Count domain redirects.")
  24.         print(" ", sys.argv[0], "-list domain\n\t-> List domain redirects.")
  25.         print(" ", sys.argv[0], "-search_src domain string\n\t-> Search source addresses for string.")
  26.         print(" ", sys.argv[0], "-search_dest domain string\n\t-> Searches for a string in destination addresses.")
  27.         print(" ", sys.argv[0], "-create domain new_redir destination\n\t-> Create a new mail redirect.")
  28. #
  29. # Reading API in a json
  30. #
  31. def list_addresses_redir(api_url, api_key):
  32.         headers = {'authorization': 'Apikey' + api_key}
  33.  
  34.         print("Downloading", api_url, "...")
  35.         #response = requests.request("GET", api_url, headers=headers)
  36.         response = requests.get(api_url, headers=headers)
  37.         data = response.json()
  38.         head = response.headers
  39.         #print (type(response))
  40.         if str(response) != "<Response[200]>":
  41.                 print ("\nProblem accessing the API. \nReturn code = " + str(response))
  42.                 quit()
  43.  
  44.         if debug:
  45.                 print("Type data:", type(data))
  46.                 #print(data)
  47.                 print("Type head:", type(head))
  48.                 print(head)
  49.                 # print("Type head.link", type(head['link']))
  50.                 #print(head['link'])
  51.                 # print(response.text)
  52.                 # quit()
  53.  
  54.         return (head, data)
  55. #
  56. # Count the number of redirects
  57. #
  58. def count_redir(head, domain):
  59.         print(" " + head['total-count'] + " addresses found.")
  60. #
  61. # Display nb occurrences
  62. #
  63. def displays_nb_occurences(nb_src, liste_dest):
  64.         # Remove duplicates from destination address list
  65.         list_dest = list(set(list_dest))
  66.         print ("\n", nb_src, "source addresses and", len(dest_list), "destination addresses found.")
  67. #
  68. # Search if redirect exists
  69. #
  70. def search_redir(data, domain, email_string, src_or_dest):
  71.         nb_src = 0
  72.         dest_list = []
  73.         #email_string = email_string.ascii_lowercase()
  74.         for mail_list in data:
  75.                 #if src_or_dest == 'source' and (email_string == "ALL" or email_string.lower() in mail_list[src_or_dest].lower() ):
  76.                 if src_or_dest == 'source' and (email_string.lower() in mail_list[src_or_dest].lower() ):
  77.                         nb_src += 1
  78.                         #print ("- " + mail_list['source'] + "@" + domain + "\t-> ", end='')
  79.                         src = mail_list['source'] + "@" + domain
  80.                         print (" - {:<40} ​​-> "-> ".format(src), end='' )
  81.                         for destination in mail_list['destinations']:
  82.         # Counting destination addresses
  83. ses
  84.                                         dest_list.append(dest.lower())
  85.                                         print(dest + ' ', end='')
  86.                         print()
  87.                 elif src_or_dest == 'destinations':
  88.                         for destination in mail_list['destinations']:
  89.                                 if email_string.lower() in dest.lower():
  90.                                         nb_src += 1
  91.         #print (" - " + mail_list['source'] + "@" + domain + "\t -> ", dest)
  92. st)
  93.                                         src = mail_list['source'] + "@" + domain
  94.                                         print (" - {:<40} ​​-> ".format(src) + des# Counting destination addresses
  95. dresses
  96.                                         dest_list.append(dest.lower(#print (dest + ' ', end='')
  97. end='')
  98.                
  99.         displays_nb_occurences(nb_src, list#
  100. # Create a redirect
  101. #                              
  102. t
  103. #                              
  104. def create_redir(api_url, new_redir, dest):
  105.         payload = "{\":\u"ce\":\"" + new_redir + "\",\"destinations\":[\"" + dest + "\"]}"
  106.         headers = {
  107.             'authorization': "Apikey" + api_key,
  108.             'content-type': "application/json"
  109.             }
  110.         response = requests.request("POST", api_url, data=payload, headers=headers)
  111.         print("Return API:", respons#
  112. # Find Aliases
  113. #
  114. iases
  115. #
  116. def search_alias(api_url, alias_string, api_key):
  117.         headers = {'authorization': 'Apikey' + api_key}
  118.         response = requests.request("GET", api_url, headers=headers)
  119.         if debug:
  120.                 print(response.text)
  121.         data = response.# Path of mailboxes
  122. ilboxes
  123.         for mail_list in data:
  124.                 if debug:
  125.                         print(type(data))
  126.                         print(mail_list['href'])
  127.                 url = mail_list['href']
  128.                 headers = {'authorization': 'Apikey' + api_key}
  129.                 response = requests.request("GET", url, headers=headers)
  130.                 data_detail = response.json()
  131.                 print ("\n - Search for mailbox alias '" + data_detail['] + "'s'] + "' ...")
  132.                 if debug:
  133.                         print(type(data_detail))
  134.                         print(response.# Browse mailbox aliases
  135. al# print(data_detail['aliases'])
  136. ases'])
  137.                 nb_alias = 0
  138.                 for alias in data_detail[']:
  139.                         #if (alias_string == "ALL" or alias_string.lower() in alias ):
  140.                         if (alias_string.lower() in alias):
  141.                                 nb_alias += 1
  142.                                 print (" ", alias, end='s, end='')
  143.                 print ("\n " + str(nb_alias) + " alias found for mailbox " + data_detail['])
  144. ################################################# #####
  145. # Hand
  146. ################################################# #####
  147. #
  148. # Argument testing
  149. #
  150. if len(sys.argv) < 3:
  151.         print_usage()
  152.         quit()
  153.  
  154. domain = sys.argv[2]
  155. # 1000 per page to avoid pb pagination
  156. api_url_redir = api_url_base_redir + domain + "?per_page=1000"
  157. api_url_mailboxes = api_url_base_mailboxes + domain
  158.  
  159. if sys.argv[1] == "-create" and len(sys.argv) == 5:
  160.         new_redir = sys.argv[3]
  161.         dest = sys.argv[4]
  162.         create_redir(api_url_redir, new_redir, dest)
  163.  
  164. elif sys.argv[1] == "-count" and len(sys.argv) == 3:
  165.         print("\pCount of mail redirections in domain 'domain '" + domain + "'...")
  166.         tuple_head_redir = lister_adresses_redir (api_url_redir, api_key)
  167.         count_redir(tuple_head_redir[0], domain)
  168.  
  169. elif sys.argv[1] == "-list" and len(sys.argv) == 3:
  170.         print("\nDisplay of mail redirections for domain '" + domain + "'...")
  171.         tuple_head_redir = lister_adresses_redir (api_url_redir, api_key)
  172.         search_redir(tuple_head_redir[1], domain, "", "source")
  173.         print("\nDisplay of mailbox aliases for domain '" + domain + "'...")
  174.         search_alias(api_url_mailboxes, "", api_key)
  175.  
  176. elif sys.argv[1] == "-search_src" and len(sys.argv) == 4:
  177.         email_string = sys.argv[3]
  178.         print("\nSearch for '" + email_string + "' in the mail redirections of the domain '" + domain + "'...")
  179.         tuple_head_redir = lister_adresses_redir (api_url_redir, api_key)
  180.         search_redir(tuple_head_redir[1], domain, email_string, "source")
  181.         print("\nSearch for '" + email_string + "' in the mailbox aliases of the domain '" + domain + "'...")
  182.         search_alias(api_url_mailboxes, email_string, api_key)
  183.  
  184. elif sys.argv[1] == "-search_dest" and len(sys.argv) == 4:
  185.         email_string = sys.argv[3]
  186.         print("\nSearch for '" + email_string + "' in destination addresses of domain '" + domain + "'...")
  187.         tuple_head_redir = lister_adresses_redir (api_url_redir, api_key)
  188.         search_redir(tuple_head_redir[1], domain, email_string, "destinations")
  189.  
  190. else:
  191.         print_usage()
  192.  

Raw Paste

Login or Register to edit or fork this paste. It's free.