johnmahugu

python - pyzsendmail in python module

Mar 10th, 2016
390
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.37 KB | None | 0 0
  1.  
  2. pyzmail: Python easy mail library
  3.  
  4. pyzmail is a high level mail library for Python. It provides functions and classes that help for reading, composing and sending emails. pyzmail exists because their is no reasons that handling mails with Python would be more difficult than with popular mail clients like Outlook or Thunderbird. pyzmail hides the complexity of the MIME structure and MIME encoding/decoding. It also make the problems of the internationalization encoding/decoding simpler.
  5. Download and Install
  6.  
  7. pyzmail is available for Python 2.6+ and 3.2+ from pypi and can be easily installed using the easy_install successor named distribute and pip using
  8.  
  9. $ pip install pyzmail
  10.  
  11. to quickly install distribute and pip, use
  12.  
  13. curl -O http://python-distribute.org/distribute_setup.py
  14. python distribute_setup.py
  15. easy_install pip
  16.  
  17. pyzmail can be installed the old way from sources. Download the archive from pypi and extract its content into a directory. cd into this directory and run:
  18.  
  19. > cd pyzmail-X.X.X
  20. > python setup.py install
  21.  
  22. Binary version of the scripts for Windows pyzmail-1.0.3-win32.zip can be downloaded from here.
  23.  
  24. pyzmail sources are also available on github https://github.com/aspineux/pyzmail
  25. Support for Python 3.x
  26.  
  27. Python 3.2+ supported
  28. _images/python-3.png
  29.  
  30. Python 3.2 is supported and has been tested. Python 3.0 and 3.1 are not supported because none of them provide functions to handle 8bits encoded emails like in 3.2 ( email.message_from_bytes() & email.message_from_binary_file() )
  31.  
  32. At installation time, pyzmail sources are automatically converted by distribute using 2to3.
  33.  
  34. Unfortunately, scripts are not converted in the process. You can convert them using 2to3 yourself (adapt paths to fit you configuration):
  35.  
  36. /opt/python-3.2.2/bin/2to3 --no-diffs --write --nobackups /opt/python-3.2.2/bin/pyzinfomail
  37. /opt/python-3.2.2/bin/2to3 --no-diffs --write --nobackups /opt/python-3.2.2/bin/pyzsendmail
  38.  
  39. Use pyzmail
  40.  
  41. The package is split into 3 modules:
  42.  
  43.     generate: Useful functions to compose and send mail s
  44.     parse: Useful functions to parse emails
  45.     utils: Various functions used by other modules
  46.  
  47. Most important functions are available from the top of the pyzmail package.
  48.  
  49. usage sample:
  50.  
  51. import pyzmail
  52.  
  53. #access function from top of pyzmail
  54. ret=pyzmail.compose_mail('me@foo.com', [ 'him@bar.com'], u'subject', \
  55.                          'iso-8859-1', ('Hello world', 'us-ascii'))
  56. payload=ret[0]
  57. print payload
  58. msg=pyzmail.PyzMessage.factory(payload)
  59. print msg.get_subject()
  60.  
  61. #use more specific function from inside modules
  62. print pyzmail.generate.format_addresses([('John', 'john@foo.com') ], \
  63.                                         'From', 'us-ascii')
  64. print pyzmail.parse.decode_mail_header('=?iso-8859-1?q?Hello?=')
  65.  
  66. More in the Quick Example section.
  67. Documentation
  68.  
  69. You can find lots of sample inside the docstrings but also in the tests directory.
  70.  
  71. The documentation, samples, docstring and articles are all fitted for python 2.x. Some occasional hint give some tricks about Python 3.x.
  72. Articles
  73.  
  74. To understand how this library works, you will find these 3 articles very useful. They have been written before the first release of pyzmail and the code has changed a little since:
  75.  
  76.         Parsing email using Python part 1 of 2 : The Header
  77.         Parsing email using Python part 2 of 2 : The content
  78.         Generate and send mail with python: tutorial
  79.  
  80. API documentation
  81.  
  82. The API documentation in epydoc format contains a lot of samples in doctest string. You will find them very useful too.
  83. Support
  84.  
  85. Ask your questions here
  86. Quick Example
  87.  
  88. Lets show you how it works !
  89. Compose an email
  90.  
  91. import pyzmail
  92.  
  93. sender=(u'Me', 'me@foo.com')
  94. recipients=[(u'Him', 'him@bar.com'), 'just@me.com']
  95. subject=u'the subject'
  96. text_content=u'Bonjour aux Fran\xe7ais'
  97. prefered_encoding='iso-8859-1'
  98. text_encoding='iso-8859-1'
  99.  
  100. payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\
  101.         sender, \
  102.         recipients, \
  103.         subject, \
  104.         prefered_encoding, \
  105.         (text_content, text_encoding), \
  106.         html=None, \
  107.         attachments=[('attached content', 'text', 'plain', 'text.txt', \
  108.                       'us-ascii')])
  109.  
  110. print payload
  111.  
  112. Look a the output:
  113.  
  114. Content-Type: multipart/mixed; boundary="===============1727493275=="
  115. MIME-Version: 1.0
  116. From: Me <me@foo.com>
  117. To: Him <him@bar.com> , just@me.com
  118. Subject: the subject
  119. Date: Fri, 19 Aug 2011 16:04:42 +0200
  120.  
  121. --===============1727493275==
  122. Content-Type: text/plain; charset="iso-8859-1"
  123. MIME-Version: 1.0
  124. Content-Transfer-Encoding: quoted-printable
  125.  
  126. Bonjour aux Fran=E7ais
  127. --===============1727493275==
  128. Content-Type: text/plain; charset="us-ascii"
  129. MIME-Version: 1.0
  130. Content-Transfer-Encoding: 7bit
  131. Content-Disposition: attachment; filename="text.txt"
  132.  
  133. attached content
  134. --===============1727493275==--
  135.  
  136. Send an email
  137.  
  138. First take a look at the other values returned by pyzmail.compose_mail():
  139.  
  140. print 'Sender address:', mail_from
  141. print 'Recipients:', rcpt_to
  142.  
  143. Here are the values I can reuse for my SMTP connection:
  144.  
  145. Sender address: me@foo.com
  146. Recipients: ['him@bar.com', 'just@me.com']
  147.  
  148. I want to send my email via my Gmail account:
  149.  
  150. smtp_host='smtp.gmail.com'
  151. smtp_port=587
  152. smtp_mode='tls'
  153. smtp_login='my.gmail.addresse@gmail.com'
  154. smtp_password='my.gmail.password'
  155.  
  156. ret=pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, \
  157.         smtp_port=smtp_port, smtp_mode=smtp_mode, \
  158.         smtp_login=smtp_login, smtp_password=smtp_password)
  159.  
  160. if isinstance(ret, dict):
  161.     if ret:
  162.         print 'failed recipients:', ', '.join(ret.keys())
  163.     else:
  164.         print 'success'
  165. else:
  166.     print 'error:', ret
  167.  
  168. Here pyzmail.send_mail() combine SSL and authentication.
  169. Parse an email
  170.  
  171. Now lets try to read the email we have just composed:
  172.  
  173. msg=pyzmail.PyzMessage.factory(payload)
  174.  
  175. print 'Subject: %r' % (msg.get_subject(), )
  176. print 'From: %r' % (msg.get_address('from'), )
  177. print 'To: %r' % (msg.get_addresses('to'), )
  178. print 'Cc: %r' % (msg.get_addresses('cc'), )
  179.  
  180. Take a look at the outpout:
  181.  
  182. Subject: u'the subject'
  183. From: (u'Me', 'me@foo.com')
  184. To: [(u'Him', 'him@bar.com'), (u'just@me.com', 'just@me.com')]
  185. Cc: []
  186.  
  187. And a little further regarding the mail content and attachment:
  188.  
  189. for mailpart in msg.mailparts:
  190.     print '    %sfilename=%r alt_filename=%r type=%s charset=%s desc=%s size=%d' % ( \
  191.         '*'if mailpart.is_body else ' ', \
  192.         mailpart.filename,  \
  193.         mailpart.sanitized_filename, \
  194.         mailpart.type, \
  195.         mailpart.charset, \
  196.         mailpart.part.get('Content-Description'), \
  197.         len(mailpart.get_payload()) )
  198.     if mailpart.type.startswith('text/'):
  199.         # display first line of the text
  200.         payload, used_charset=pyzmail.decode_text(mailpart.get_payload(), mailpart.charset, None)
  201.         print '        >', payload.split('\\n')[0]
  202.  
  203. And the output:
  204.  
  205. *filename=None alt_filename='text.txt' type=text/plain charset=iso-8859-1 desc=None size=20
  206.     > Bonjour aux Français
  207.  filename=u'text.txt' alt_filename='text-01.txt' type=text/plain charset=us-ascii desc=None size=16
  208.     > attached content
  209.  
  210. The first one, with a * is the text content, the second one is the attachment.
  211.  
  212. You also have direct access to the text and HTML content using:
  213.  
  214. if msg.text_part!=None:
  215.     print '-- text --'
  216.     print msg.text_part.get_payload()
  217.  
  218. if msg.html_part!=None:
  219.     print '-- html --'
  220.     print msg.html_part.get_payload()
  221.  
  222. And the output:
  223.  
  224. -- text --
  225. Bonjour aux Français
  226.  
  227. Their is no HTML part !
  228. Tricks
  229. Embedding image in HTML email
  230.  
  231. Image embedding differs from linked images in that the image itself is encoded, and included inside the message. Instead of using a normal URL in the IMG tag inside the HTML body, we must use a cid:target reference and assign this target name to the Content-ID of the embedded file.
  232.  
  233. See this sample:
  234.  
  235. import base64
  236. import pyzmail
  237.  
  238. angry_gif=base64.b64decode(
  239. """R0lGODlhDgAOALMAAAwMCYAAAACAAKaCIwAAgIAAgACAgPbTfoR/YP8AAAD/AAAA//rMUf8A/wD/
  240. //Tw5CH5BAAAAAAALAAAAAAOAA4AgwwMCYAAAACAAKaCIwAAgIAAgACAgPbTfoR/YP8AAAD/AAAA
  241. //rMUf8A/wD///Tw5AQ28B1Gqz3S6jop2sxnAYNGaghAHirQUZh6sEDGPQgy5/b9UI+eZkAkghhG
  242. ZPLIbMKcDMwLhIkAADs=
  243. """)
  244.  
  245. text_content=u"I'm very angry. See attached document."
  246. html_content=u'<html><body>I\'m very angry. ' \
  247.               '<img src="cid:angry_gif" />.\n' \
  248.               'See attached document.</body></html>'
  249.  
  250. payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\
  251.         (u'Me', 'me@foo.com'), \
  252.         [(u'Him', 'him@bar.com'), 'just@me.com'], \
  253.         u'the subject', \
  254.         'iso-8859-1', \
  255.         (text_content, 'iso-8859-1'), \
  256.         (html_content, 'iso-8859-1'), \
  257.         attachments=[('The price of RAM modules is increasing.', \
  258.                       'text', 'plain', 'text.txt', 'us-ascii'), ],
  259.         embeddeds=[(angry_gif, 'image', 'gif', 'angry_gif', None), ])
  260.  
  261. print payload
  262.  
  263. And here is the payload:
  264.  
  265. Content-Type: multipart/mixed; boundary="===============1435507538=="
  266. MIME-Version: 1.0
  267. From: Me <me@foo.com>
  268. To: Him <him@bar.com> , just@me.com
  269. Subject: the subject
  270. Date: Fri, 02 Sep 2011 01:40:52 +0200
  271.  
  272. --===============1435507538==
  273. Content-Type: multipart/related; boundary="===============0638818366=="
  274. MIME-Version: 1.0
  275.  
  276. --===============0638818366==
  277. Content-Type: multipart/alternative; boundary="===============0288407648=="
  278. MIME-Version: 1.0
  279.  
  280. --===============0288407648==
  281. Content-Type: text/plain; charset="iso-8859-1"
  282. MIME-Version: 1.0
  283. Content-Transfer-Encoding: quoted-printable
  284.  
  285. I'm very angry. See attached document.
  286. --===============0288407648==
  287. Content-Type: text/html; charset="iso-8859-1"
  288. MIME-Version: 1.0
  289. Content-Transfer-Encoding: quoted-printable
  290.  
  291. <html><body>I'm very angry. <img src=3D"cid:angry_gif" />. See attached doc=
  292. ument.</body></html>
  293. --===============0288407648==--
  294. --===============0638818366==
  295. Content-Type: image/gif
  296. MIME-Version: 1.0
  297. Content-Transfer-Encoding: base64
  298. Content-ID: <angry_gif>
  299. Content-Disposition: inline
  300.  
  301. R0lGODlhDgAOALMAAAwMCYAAAACAAKaCIwAAgIAAgACAgPbTfoR/YP8AAAD/AAAA//rMUf8A/wD/
  302. //Tw5CH5BAAAAAAALAAAAAAOAA4AgwwMCYAAAACAAKaCIwAAgIAAgACAgPbTfoR/YP8AAAD/AAAA
  303. //rMUf8A/wD///Tw5AQ28B1Gqz3S6jop2sxnAYNGaghAHirQUZh6sEDGPQgy5/b9UI+eZkAkghhG
  304. ZPLIbMKcDMwLhIkAADs=
  305. --===============0638818366==--
  306. --===============1435507538==
  307. Content-Type: text/plain; charset="us-ascii"
  308. MIME-Version: 1.0
  309. Content-Transfer-Encoding: 7bit
  310. Content-Disposition: attachment; filename="text.txt"
  311.  
  312. The price of RAM module is increasing.
  313. --===============1435507538==--
  314.  
  315. Scripts
  316.  
  317. Binary executables for Windows of these script are available in the `Download`_ section below.
  318. pyzsendmail
  319.  
  320. pyzsendmail is a command line script to compose and send simple and complex emails.
  321.  
  322. Features:
  323.  
  324.         SSL, TLS , authentication
  325.         HTML content and embedded images
  326.         attachments
  327.         Internationalisation
  328.  
  329. Read the manual for more.
  330.  
  331. Under Windows pyzsendmail.exe can replace the now old blat.exe and bmail.exe.
  332. pyzinfomail
  333.  
  334. pyzinfomail is a command line script reading an email from a file and printing most important information. Mostly to show how to use pyzmail library. Read the manual for more.
  335. License
  336.  
  337. pyzmail iis released under the GNU Lesser General Public License ( LGPL ).
  338. Links
  339.  
  340. More links about parsing and writing mail in python
  341.  
  342.         formataddr() and unicode
  343.         Sending Unicode emails in Python
  344.         Sending Email with smtplib
Add Comment
Please, Sign In to add comment