Advertisement
Guest User

Untitled

a guest
Apr 25th, 2016
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.28 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # coding=utf8
  3. """
  4. Copyright (c) 2013 Azar-A Ltd., Azarov Andrew
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in all
  12. copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. SOFTWARE.
  20. """
  21. import datetime
  22. import smtplib
  23. from email.mime.multipart import MIMEMultipart
  24. from email.mime.text import MIMEText
  25. from email.header import Header
  26. from email import Charset
  27.  
  28. # Add the general charset here, you can do the same in your script before
  29. # running the module function to add your custom encodings for support
  30. Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
  31.  
  32.  
  33. def send_email(messages_list, smtp_user=None, smtp_pass=None, tls=False, service_name=None, service_port=587, pre_hook=None, post_hook=None):
  34. """
  35. Send plain text or text+html email
  36.  
  37. Keyword arguments:
  38. messages_list -- required, a list of tuples in format:
  39. (
  40. [
  41. 'To someone', - optional, nice name for To header
  42. 'someone@email.test' - required, To header email address
  43. ],
  44. [
  45. 'From someone', - optional, nice name for From header
  46. 'someone2@email.test' - required, From header email address
  47. ],
  48. 'Subject', - required, can be empty string
  49. 'encoding', - required, must be preloaded with email.Charset.add_charset() function, for more information look into email module
  50. [
  51. [
  52. 'Text', - required, the text portion of the message, goes with text type to MIMEText function of email module
  53. 'encoding' - required, must be preloaded with email.Charset.add_charset() function, for more information look into email module
  54. ],
  55. [
  56. 'html', - required, the html portion of the message, goes with html type to MIMEText function of email module
  57. 'encoding' - required, must be preloaded with email.Charset.add_charset() function, for more information look into email module
  58. ]
  59. ]
  60. )
  61. smtp_user -- optional, for smtp login function
  62. smtp_pass -- optional, for smtp login function
  63. tls -- optional, whether establish secure connection over TLS
  64. service_name -- required, server to connect to (ie mail.serverastra.com)
  65. service_port -- optional, port (remember that default is 587 - submission port)
  66. pre_hook -- optional, function to run before full email construction but after MIME classification, you can redefine it though, gets arguments of resulting MIME part and the input message pair.
  67. post_hook -- optional, function to run after full email construction but before actual sending, same arguments as in pre_hook.
  68. """
  69. failed = []
  70. try:
  71. s = smtplib.SMTP(service_name, service_port)
  72. s.ehlo()
  73. if tls:
  74. s.starttls()
  75. s.ehlo()
  76. if smtp_user and smtp_pass:
  77. s.login(smtp_user, smtp_pass)
  78. except:
  79. traceback.print_exc()
  80. print(x[0] + "ehlo failed")
  81. failed = [x[0] for x in messages_list]
  82. else:
  83. for to_address, from_address, subject, encoding, mesg in messages_list:
  84. try:
  85. if len(mesg) == 2:
  86. # 2 parts to the message - define as alternative to allow
  87. # attachments
  88. msg = MIMEMultipart('alternative')
  89. else:
  90. # 1 part - MIMEText part is applied right away
  91. msg = MIMEText(mesg[0][0], 'plain', mesg[0][1])
  92. if pre_hook:
  93. # Execute function before constructing email but after MIME
  94. # classification, however you can redefine it or attach more
  95. # parts.
  96. msg = pre_hook(msg, mesg)
  97. # Subject with general message encoding
  98. msg['Subject'] = "%s" % Header(subject, encoding)
  99. # Message address encoding
  100. if len(from_address) == 2:
  101. msg['From'] = "\"%s\" <%s>" % (
  102. Header(from_address[0], encoding), from_address[-1])
  103. else:
  104. # No need to encode just the email address as it must be
  105. # ASCII according to RFC
  106. msg['From'] = from_address[-1]
  107.  
  108. if len(to_address) == 2:
  109. msg['From'] = "\"%s\" <%s>" % (
  110. Header(to_address[0], encoding), to_address[-1])
  111. else:
  112. # No need to encode just the email address as it must be
  113. # ASCII according to RFC
  114. msg['To'] = to_address[-1]
  115. # Setting general message encoding
  116. msg.set_charset(encoding)
  117. if len(mesg) == 2:
  118. # Preparing 2 parts - attaching both
  119. part1 = MIMEText(mesg[0][0], 'plain', mesg[0][1])
  120. part2 = MIMEText(mesg[1][0], 'html', mesg[1][1])
  121. msg.attach(part1)
  122. msg.attach(part2)
  123. if post_hook:
  124. # Execute function after constructing email and attaching
  125. # parts but before sending.
  126. msg = post_hook(msg, mesg)
  127. # Final launch of email to the server
  128. s.sendmail(from_address[-1], to_address[-1], msg.as_string())
  129. except:
  130. traceback.print_exc()
  131. failed.append(to_address[-1])
  132. try:
  133. s.quit()
  134. except:
  135. # I don't care, I love it
  136. pass
  137. return failed
  138.  
  139.  
  140. if __name__ == '__main__':
  141. # Example use, might not work, as I did not test it and refactored
  142. # blindly. Please accept my apologies and refine this GIST if you find an
  143. # error, we use a bit less customizeable version which works fine from
  144. # 2013. Have a nice day!
  145. maillist = []
  146. maillist.append((['someone@gmail.com'], ["Me", "noreply@example.com"], 'Subject',
  147. 'utf-8', [['text_message', 'utf-8'], ['html but you can delete this list item and it will become plain text', 'utf-8']]))
  148. for k in send_email(maillist, smtp_user='you@serverastra.com', smtp_pass='pwd', tls=True, service_name='mail-test.serverastra.com'):
  149. print(k + 'not delivered')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement