mail2wordpresspost.py 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ################################################################################
  4. # Author: klaute - Kai Lauterbach - me@klaute.de - @kailauterbach
  5. # Date: 20.04.2016
  6. # License: GPLv3
  7. #
  8. # Some of the code contained in this python script was copied from stackoverflow
  9. # and other sites and are written by multiple authors.
  10. #
  11. # This script is just glue-code.
  12. #
  13. ################################################################################
  14. import os
  15. import sys
  16. import re
  17. import mimetypes
  18. import email
  19. import email.header
  20. from wordpress_xmlrpc import Client, WordPressPost
  21. from wordpress_xmlrpc.compat import xmlrpc_client
  22. from wordpress_xmlrpc.methods import media, posts
  23. from wordpress_xmlrpc.methods.posts import NewPost
  24. from optparse import OptionParser
  25. from mail2wordpresspost_cfg import * # import configuration file settings
  26. ################################################################################
  27. parser = OptionParser(usage="""\
  28. Read MIME message files from a directory of files
  29. and post it to a WordPress as a new post.
  30. Usage: %prog [options]
  31. """)
  32. parser.add_option('-d', '--directory',
  33. type='string', action='store',
  34. default='inbox',
  35. help="""Read the MIME messages from the named
  36. directory, which will be filled by the mailer daemon.""")
  37. parser.add_option('-t', '--temp',
  38. type='string', action='store',
  39. default='tmp',
  40. help="""Temporary directory path""")
  41. # TODO remove the upper two options and replace them by a option that will overwrite
  42. # the configuration file include
  43. ################################################################################
  44. wp = None
  45. ################################################################################
  46. # copied from
  47. # http://stackoverflow.com/questions/12903893/python-imap-utf-8q-in-subject-string
  48. def decode_mime_words(s):
  49. return u''.join(
  50. word.decode(encoding or 'utf8') if isinstance(word, bytes) else word
  51. for word, encoding in email.header.decode_header(s))
  52. ################################################################################
  53. def wpCreatePost(title, descr, images):
  54. post = WordPressPost()
  55. post.title = title
  56. post.post_status = POST_DEFAULT_STATUS
  57. post.tags = POST_TAGS
  58. post.categories = POST_CATEGORIES
  59. if descr == None:
  60. descr = ""
  61. # add image(s) to the post
  62. # first upload, than add the attachment_id(s)
  63. res = []
  64. for file in images:
  65. res.append(wpUploadMedia(file))
  66. if len(res) > 0:
  67. # add the first image as post thumbnail
  68. if USE_EMAIL_IMAGE_AS_THUMBNAIL >= 1:
  69. post.thumbnail = res[USE_EMAIL_IMAGE_AS_THUMBNAIL-1]['id']
  70. # create a list of the given images as HTML code
  71. image_list_descr = ""
  72. for r in res:
  73. tmp = DESCRIPTION_IMAGE
  74. # replace the dummy text/template elements by image upload result data
  75. tmp = tmp.replace('IMAGE_URL', r['url'])
  76. tmp = tmp.replace('IMAGE_ID', r['id'])
  77. tmp = tmp.replace('IMAGE_FILENAME', r['file'])
  78. image_list_descr = image_list_descr + tmp
  79. # add the list of images to the description
  80. #print "1:"+str(descr)
  81. #print "2:"+str(image_list_descr)
  82. if POST_TEXT_BEYOND_IMAGES == True:
  83. descr = image_list_descr + descr
  84. else:
  85. descr = descr + image_list_descr
  86. # set the post description
  87. post.content = descr
  88. # publish new post
  89. return wp.call(NewPost(post))
  90. ################################################################################
  91. def wpUploadMedia(file):
  92. global wp
  93. data = {
  94. 'name': os.path.basename(file), # filename only
  95. 'type': 'image/jpeg', # mimetype
  96. }
  97. # read the binary file and let the XMLRPC library encode it into base64
  98. with open(file, 'rb') as img:
  99. data['bits'] = xmlrpc_client.Binary(img.read())
  100. # example:
  101. # response == {
  102. # 'id': 6,
  103. # 'file': 'picture.jpg'
  104. # 'url': 'http://www.example.com/wp-content/uploads/2012/04/16/picture.jpg',
  105. # 'type': 'image/jpeg',
  106. # }
  107. response = wp.call(media.UploadFile(data))
  108. return response
  109. ################################################################################
  110. def main():
  111. global wp
  112. wp = Client(WORDPRESS_URL, WORDPRESS_USER, WORDPRESS_PASS)
  113. opts, args = parser.parse_args()
  114. # test if input folder exist
  115. if not opts.directory:
  116. parser.print_help()
  117. sys.exit(1)
  118. # done folder should be exist beyond the input folder
  119. if os.path.exists(opts.directory) == False:
  120. # directory not exist
  121. print "ERROR: Input folder (" + opts.directory + ") does not exist."
  122. exit(-1)
  123. if os.path.exists(opts.directory + '/done') == False:
  124. print "INFO: created done directory"
  125. os.mkdir(os.path.join(opts.directory, 'done'))
  126. if os.path.exists(opts.temp) == False:
  127. print "INFO: created temp directory " + opts.temp
  128. os.mkdir(opts.temp)
  129. # read and process all mail files
  130. listing = os.listdir(opts.directory)
  131. for infile in listing:
  132. fname = os.path.join(opts.directory, infile)
  133. if os.path.isfile(fname) == False:
  134. pass # skip subdirectories
  135. else:
  136. print "Process email file: " + fname
  137. # read email file
  138. fp = open(fname, 'r')
  139. msg = email.message_from_file(fp)
  140. fp.close()
  141. # only process emails which were received from allowed sender
  142. email_addr = re.findall(r'[\w\.-]+@[\w\.-]+', msg['from'])[0]
  143. if email_addr.lower() in [s.lower() for s in ALLOWED_EMAIL_FROM]:
  144. images = []
  145. # reset the counter which is used to create unnamed attachment files
  146. counter = 1
  147. for part in msg.walk():
  148. # multipart/* are just containers, dive into them
  149. if part.get_content_maintype() == 'multipart':
  150. continue
  151. # Applications should really sanitize the given filename so that an
  152. # email message can't be used to overwrite important files
  153. filename = part.get_filename()
  154. if not filename:
  155. # the filename of the attachment is germed, we have to create one
  156. ext = mimetypes.guess_extension(part.get_content_type())
  157. if not ext:
  158. # Use a generic bag-of-bits extension
  159. ext = '.bin'
  160. # create a dummy file name
  161. filename = 'part-%03d%s' % (counter, ext)
  162. # write the attachment, to the temporary output folder
  163. fp = open(os.path.join(opts.temp, filename), 'wb')
  164. fp.write(part.get_payload(decode=True))
  165. fp.close()
  166. # only specified mimetypes are allowed to post on wordpress
  167. if part.get_content_type() in ALLOWED_MIMETYPES:
  168. images.append(os.path.join(opts.temp, filename))
  169. # increment dummy file name counter
  170. counter += 1
  171. # extract plaintext mail body from email
  172. descr = ""
  173. if msg.is_multipart():
  174. for payload in msg.get_payload():
  175. # if payload.is_multipart(): ...
  176. ctype = payload.get_content_type()
  177. cdispo = str(payload.get('Content-Disposition'))
  178. if ctype == 'text/plain' and 'attachment' not in cdispo:
  179. # decode only plaintext content which is not a attachment
  180. descr = part.get_payload(decode=True)
  181. break
  182. else:
  183. descr = msg.get_payload(decode=True)
  184. # decode the (maybe) encoded subject if required
  185. email_sub = decode_mime_words(msg['subject'])
  186. # create post
  187. #print "Post title: " + email_sub
  188. wpCreatePost(email_sub, descr, images)
  189. # move processed file to done folder
  190. os.rename(fname, os.path.join(os.path.join(opts.directory, 'done'), infile))
  191. ################################################################################
  192. if __name__ == '__main__':
  193. main()