<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	>

<channel>
	<title>Paolo Donadeo -- LifeLOG &#187; Objective Caml</title>
	<atom:link href="http://www.donadeo.net/category/programming-languages/objective-caml/feed" rel="self" type="application/rss+xml" />
	<link>http://www.donadeo.net</link>
	<description>All about my life, job and thoughts</description>
	<pubDate>Sun, 15 Jun 2008 21:56:28 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5</generator>
	<language>en</language>
			<item>
		<title>Sending emails via Gmail with Objective Caml</title>
		<link>http://www.donadeo.net/2008/04/26/sending-emails-via-gmail-with-objective-caml/</link>
		<comments>http://www.donadeo.net/2008/04/26/sending-emails-via-gmail-with-objective-caml/#comments</comments>
		<pubDate>Sat, 26 Apr 2008 21:00:53 +0000</pubDate>
		<dc:creator>Paolo</dc:creator>
		
		<category><![CDATA[Article]]></category>

		<category><![CDATA[Computer programming]]></category>

		<category><![CDATA[English]]></category>

		<category><![CDATA[Objective Caml]]></category>

		<category><![CDATA[Python]]></category>

		<category><![CDATA[Spare time]]></category>

		<guid isPermaLink="false">http://www.donadeo.net/?p=78</guid>
		<description><![CDATA[
Motivation
Last week I was writing a Python script to make an automatic backup, and I decided to send me an email in case of scp failure. I decided to use Python to send the email, possibly via GMail and I found this interesting blog post: Sending emails via Gmail with Python. I like Python, it's [...]]]></description>
			<content:encoded><![CDATA[<p style="float: left; margin-right: 1em; margin-bottom: 1em"><img title="Gmail logo with the caml" src="http://www.donadeo.net/wp-content/uploads/2008/04/gmail_and_ocaml.png" border="2" alt="Gmail logo with the caml" width="256" height="158" /></p>
<h3>Motivation</h3>
<p>Last week I was writing a Python script to make an automatic backup, and I decided to send me an email in case of scp failure. I decided to use Python to send the email, possibly via GMail and I found this interesting blog post: <a title="Kutuma's Ramblings: Sending emails via Gmail with Python" href="http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/kutuma.blogspot.com');">Sending emails via Gmail with Python</a>. I like Python, it's a good programming language, but my heart (as a developer!) beats for the <a title="Objective Caml home page" href="http://caml.inria.fr/ocaml/index.en.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/caml.inria.fr');">Objective Caml</a> programming language.</p>
<p>So I decided to port the script presented in the post in OCaml. The result is this <a href="http://www.donadeo.net/wp-content/uploads/2008/04/sendmail.ml" >sendmail.ml</a>.</p>
<h3>Compiling the script</h3>
<p>To compile the script you need four software components:</p>
<ol>
<li>the Objective Caml environment. You can download it from the <a href="http://caml.inria.fr/ocaml/release.en.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/caml.inria.fr');">INRIA site</a>;</li>
<li><a href="http://projects.camlcity.org/projects/findlib.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/projects.camlcity.org');">Findlib</a>, to make compiling very simple;</li>
<li>Ocamlnet: here is the <a href="http://projects.camlcity.org/projects/ocamlnet.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/projects.camlcity.org');">home page of the project</a>;</li>
<li><a href="http://savonet.sourceforge.net/wiki/OCamlLibs" onclick="javascript:pageTracker._trackPageview('/outbound/article/savonet.sourceforge.net');">OCaml binding</a> to the SSL library.</li>
</ol>
<p>You can of course compile all this stuff, but every decent Linux distributions has all packaged. In Debian you have to run the following command:</p>
<pre># aptitude install ocaml libocamlnet-ocaml-dev \
  libssl-ocaml-dev ocaml-findlib</pre>
<p>Now, to compile the script, issue the command:</p>
<pre>$ ocamlfind ocamlopt -linkpkg -package \
  netstring,smtp,ssl,str sendmail.ml -o sendmail</pre>
<p>Before using it, remember to customize your name, email address, GMail user and password.</p>
<h3>Code comparison</h3>
<p>The first difference that jumps out at everyone confronting the two scripts is the number of lines: 41 lines for Python against 163 of my OCaml version. The difference is justified by the fact that the Python standard library comes with an almost full featured SMTP client, with ESMTP and TLS capability. On the other side Objective Caml has a very concise standard library, which includes essential modules and data structures, but no "batteries" are provided out of the box. This is a precise design decision by INRIA and, in some ways, I agree with them. Luckily the OCaml community is a source of excellent libraries and bindings, like <a href="http://projects.camlcity.org/projects/ocamlnet.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/projects.camlcity.org');">Ocamlnet</a> by Gerd Stolpmann and the <a href="http://savonet.sourceforge.net/wiki/OCamlLibs" onclick="javascript:pageTracker._trackPageview('/outbound/article/savonet.sourceforge.net');">SSL library binding</a>, written by Samuel Mimram. The first one is in particular the Swiss Army Knife for network oriented battles.</p>
<p>Since the SMTP client provided by Ocamlnet doesn't include TLS capability I decided to stole the source code and adapt it to my needs, to have a more comfortable and high level interface resembling the one offered by the Python standard library.</p>
<p>So the different length is easily explained: 109 lines of code are devoted to the smtp_client class, and the actual script is 54 lines long.</p>
<h3>The forward pipe operator</h3>
<p>All Turing complete computer languages are equivalent, but everyone knows this is only the theory and everyone have a programming language of choice. Here are two examples of what you can do in OCaml.</p>
<p>The first is the <em>pipe</em> operator:</p>
<pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> <span style="color: #6c6;">&#40;</span>|&gt;<span style="color: #6c6;">&#41;</span> x f = f x</pre>
<p>Here we define a (very common in <a href="http://en.wikipedia.org/wiki/Functional_programming" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">FP</a>) infix operator which simply inverts the order of its operands. What the <a href="http://en.wiktionary.org/wiki/frack" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wiktionary.org');">frack</a> is this? Very simple, we use it to invert the order of a function with its last parameter so, if we want to compute the 3rd Fibonacci number we can write:</p>
<pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> fib3 = fibonacci <span style="color: #c6c;">3</span></pre>
<p>but also:</p>
<pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> fib3 = <span style="color: #c6c;">3</span> |&gt; fibonacci</pre>
<p>This is not a style issue, we can define a simple infix operator that feeds a function with a value; we can of course connect several functions together, like in a shell script with the Unix pipe operator, transforming an ugly and difficult to be read call:</p>
<pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> result = func1<span style="color: #6c6;">&#40;</span>func2 <span style="color: #6c6;">&#40;</span>func3<span style="color: #6c6;">&#40;</span>x<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span></pre>
<p>into:</p>
<pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> result = x |&gt; func3 |&gt; func2 |&gt; func1</pre>
<p>In the sendmail.ml script, line 127, we read:</p>
<pre class="ocaml">email_string |&gt;
  <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/caml.inria.fr');"><span style="">Str</span></a>.<span style="color: #060;">global_replace</span> new_line_regexp <span style="color: #3cb371;">&quot;\r\n&quot;</span> |&gt;
    <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/caml.inria.fr');"><span style="">Str</span></a>.<span style="color: #060;">split</span> crlf_regexp |&gt;
      <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/caml.inria.fr');"><span style="">List</span></a>.<span style="color: #060;">iter</span> <span style="color: #6c6;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> s -&gt;
        self#output_string <span style="color: #6c6;">&#40;</span><span style="color: #06c; font-weight: bold;">if</span> <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/String.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/caml.inria.fr');"><span style="">String</span></a>.<span style="color: #060;">length</span> s &gt; <span style="color: #c6c;">0</span> &amp;&amp; s.<span style="color: #6c6;">&#91;</span><span style="color: #c6c;">0</span><span style="color: #6c6;">&#93;</span> = '.' <span style="color: #06c; font-weight: bold;">then</span>
                              <span style="color: #6c6;">&#40;</span><span style="color: #3cb371;">&quot;.&quot;</span> ^ s ^ <span style="color: #3cb371;">&quot;\r\n&quot;</span><span style="color: #6c6;">&#41;</span>
                            <span style="color: #06c; font-weight: bold;">else</span> s^<span style="color: #3cb371;">&quot;\r\n&quot;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span>;</pre>
<p>Here we take the string containing the email, we replace all new lines with the sequence "\r\n", split the stream into lines and in the end send each line to the SMTP server, taking care of quoting each line starting with a period. In 6 lines of code.</p>
<h3>Algebraic data type</h3>
<p><a href="http://en.wikipedia.org/wiki/Algebraic_data_type" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">Algebraic data type</a> are a very interesting aspect of functional programming. We can <em>easily</em> wrap two heterogeneous data types into a single one with two line of code:</p>
<pre class="ocaml"><span style="color: #06c; font-weight: bold;">type</span> socket =
  | Unix_socket <span style="color: #06c; font-weight: bold;">of</span> Unix.<span style="color: #060;">file_descr</span>
  | SSL_socket <span style="color: #06c; font-weight: bold;">of</span> Ssl.<span style="color: #060;">socket</span></pre>
<p>The smtp_client class contains a reference to the connection handle used for communicating with the server which is a plain file descriptor or an SSL socket, which one depends on the state of the communication. I <strong>do not want</strong> to create a virtual class or an interface and two implementing class as I should do in horrible languages like Java, spending half an hour deciding which methods to put in the public interface, and so on; after all, it's only a file descriptor!</p>
<p>Now I have a new type which is a <a href="http://en.wikipedia.org/wiki/Disjoint_union" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">disjoint union</a> of the two original types and I can write code like this (line 54):</p>
<pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALinput" onclick="javascript:pageTracker._trackPageview('/outbound/article/caml.inria.fr');"><span style="">input</span></a> = <span style="color: #06c; font-weight: bold;">match</span> channel <span style="color: #06c; font-weight: bold;">with</span>
  | Unix_socket s -&gt; Unix.<span style="color: #060;">read</span> s
  | SSL_socket s -&gt; Ssl.<span style="color: #060;">read</span> s i</pre>
<p>Here we say: if channel is actually a Unix file descriptor, let's define a new function "input" which is the standard function "read", from Unix module, otherwise, if channel is an SSL socket, let's define "input" as the Ssl.read function, which works only in ciphered sockets. From now on I'll use input instead of one of the two original functions.</p>
<p>Ok, it's time to stop the waffle. Enjoy the script if you need, it's completely free, like in free beer, in free speech and even in free sex! <img src='http://www.donadeo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.donadeo.net/2008/04/26/sending-emails-via-gmail-with-objective-caml/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
