Guest User

Untitled

a guest
Jun 18th, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.68 KB | None | 0 0
  1. import os
  2. import re
  3.  
  4. import click
  5. import sendgrid
  6. import six
  7. from pyconfigstore import ConfigStore
  8. from PyInquirer import (Token, ValidationError, Validator, print_json, prompt,
  9. style_from_dict)
  10. from sendgrid.helpers.mail import *
  11.  
  12. from pyfiglet import figlet_format
  13.  
  14. try:
  15. import colorama
  16. colorama.init()
  17. except ImportError:
  18. colorama = None
  19.  
  20. try:
  21. from termcolor import colored
  22. except ImportError:
  23. colored = None
  24.  
  25.  
  26. conf = ConfigStore("EmailCLI")
  27.  
  28. style = style_from_dict({
  29. Token.QuestionMark: '#fac731 bold',
  30. Token.Answer: '#4688f1 bold',
  31. Token.Instruction: '', # default
  32. Token.Separator: '#cc5454',
  33. Token.Selected: '#0abf5b', # default
  34. Token.Pointer: '#673ab7 bold',
  35. Token.Question: '',
  36. })
  37.  
  38. def getDefaultEmail(answer):
  39. try:
  40. from_email = conf.get("from_email")
  41. except KeyError, Exception:
  42. from_email = u""
  43. return from_email
  44.  
  45. def getContentType(answer, conttype):
  46. return answer.get("content_type").lower() == conttype.lower()
  47.  
  48. def sendMail(mailinfo):
  49. sg = sendgrid.SendGridAPIClient(api_key=conf.get("api_key"))
  50. from_email = Email(mailinfo.get("from_email"))
  51. to_email = Email(mailinfo.get("to_email"))
  52. subject = mailinfo.get("subject").title()
  53. content_type = "text/plain" if mailinfo.get("content_type") == "text" else "text/html"
  54. content = Content(content_type, mailinfo.get("content"))
  55. mail = Mail(from_email, subject, to_email, content)
  56. response = sg.client.mail.send.post(request_body=mail.get())
  57. return response
  58.  
  59. def log(string, color, font="slant", figlet=False):
  60. if colored:
  61. if not figlet:
  62. six.print_(colored(string, color))
  63. else:
  64. six.print_(colored(figlet_format(
  65. string, font=font), color))
  66. else:
  67. six.print_(string)
  68.  
  69.  
  70. class EmailValidator(Validator):
  71. pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"
  72.  
  73. def validate(self, email):
  74. if len(email.text):
  75. if re.match(self.pattern, email.text):
  76. return True
  77. else:
  78. raise ValidationError(
  79. message="Invalid email",
  80. cursor_position=len(email.text))
  81. else:
  82. raise ValidationError(
  83. message="You can't leave this blank",
  84. cursor_position=len(email.text))
  85.  
  86. class EmptyValidator(Validator):
  87. def validate(self, value):
  88. if len(value.text):
  89. return True
  90. else:
  91. raise ValidationError(
  92. message="You can't leave this blank",
  93. cursor_position=len(value.text))
  94.  
  95.  
  96. class FilePathValidator(Validator):
  97. def validate(self, value):
  98. if len(value.text):
  99. if os.path.isfile(value.text):
  100. return True
  101. else:
  102. raise ValidationError(
  103. message="File not found",
  104. cursor_position=len(value.text))
  105. else:
  106. raise ValidationError(
  107. message="You can't leave this blank",
  108. cursor_position=len(value.text))
  109.  
  110.  
  111. class APIKEYValidator(Validator):
  112. def validate(self, value):
  113. if len(value.text):
  114. sg = sendgrid.SendGridAPIClient(
  115. api_key=value.text)
  116. try:
  117. response = sg.client.api_keys._(value.text).get()
  118. if response.status_code == 200:
  119. return True
  120. except:
  121. raise ValidationError(
  122. message="There is an error with the API Key!",
  123. cursor_position=len(value.text))
  124. else:
  125. raise ValidationError(
  126. message="You can't leave this blank",
  127. cursor_position=len(value.text))
  128.  
  129.  
  130. def askAPIKEY():
  131. questions = [
  132. {
  133. 'type': 'input',
  134. 'name': 'api_key',
  135. 'message': 'Enter SendGrid API Key (Only needed to provide once)',
  136. 'validate': APIKEYValidator,
  137. },
  138. ]
  139. answers = prompt(questions, style=style)
  140. return answers
  141.  
  142. def askEmailInformation():
  143.  
  144. questions = [
  145. {
  146. 'type': 'input',
  147. 'name': 'from_email',
  148. 'message': 'From Email',
  149. 'default': getDefaultEmail,
  150. 'validate': EmailValidator
  151. },
  152. {
  153. 'type': 'input',
  154. 'name': 'to_email',
  155. 'message': 'To Email',
  156. 'validate': EmailValidator
  157. },
  158. {
  159. 'type': 'input',
  160. 'name': 'subject',
  161. 'message': 'Subject',
  162. 'validate': EmptyValidator
  163. },
  164. {
  165. 'type': 'list',
  166. 'name': 'content_type',
  167. 'message': 'Content Type:',
  168. 'choices': ['Text', 'HTML'],
  169. 'filter': lambda val: val.lower()
  170. },
  171. {
  172. 'type': 'input',
  173. 'name': 'content',
  174. 'message': 'Enter plain text:',
  175. 'when': lambda answers: getContentType(answers, "text"),
  176. 'validate': EmptyValidator
  177. },
  178. {
  179. 'type': 'confirm',
  180. 'name': 'confirm_content',
  181. 'message': 'Do you want to send an html file',
  182. 'when': lambda answers: getContentType(answers, "html")
  183.  
  184. },
  185. {
  186. 'type': 'input',
  187. 'name': 'content',
  188. 'message': 'Enter html:',
  189. 'when': lambda answers: not answers.get("confirm_content", True),
  190. 'validate': EmptyValidator
  191. },
  192. {
  193. 'type': 'input',
  194. 'name': 'content',
  195. 'message': 'Enter html path:',
  196. 'validate': FilePathValidator,
  197. 'filter': lambda val: open(val).read(),
  198. 'when': lambda answers: answers.get("confirm_content", False)
  199. },
  200. {
  201. 'type': 'confirm',
  202. 'name': 'send',
  203. 'message': 'Do you want to send now'
  204. }
  205. ]
  206.  
  207. answers = prompt(questions, style=style)
  208. return answers
  209.  
  210.  
  211. @click.command()
  212. def main():
  213. """
  214. Simple CLI for sending emails using SendGrid
  215. """
  216. log("Email CLI", color="blue", figlet=True)
  217. log("Welcome to Email CLI", "green")
  218. try:
  219. api_key = conf.get("api_key")
  220. except KeyError:
  221. api_key = askAPIKEY()
  222. conf.set(api_key)
  223.  
  224. mailinfo = askEmailInformation()
  225. if mailinfo.get("send", False):
  226. conf.set("from_email", mailinfo.get("from_email"))
  227. try:
  228. response = sendMail(mailinfo)
  229. except Exception as e:
  230. raise Exception("An error occured: %s" % (e))
  231.  
  232. if response.status_code == 202:
  233. log("Mail sent successfully", "blue")
  234. else:
  235. log("An error while trying to send", "red")
  236.  
  237. if __name__ == '__main__':
  238. main()
Add Comment
Please, Sign In to add comment