How to send email with attachment from Erlang

Today I am going to publish small script for sending email from Erlang. It is quite simple. The idea was taken from some other script (not mine, but I do not know who is an author. Sorry for that). Actually many linux users or at least admins will find it familar.

Main difference from original code, that I have found in the Internet, is that this script allows attachments. It does not cover all possible cases, but you can simply modify it for your needs.

So now is the code:

-module(mailer).

-compile(export_all).

send(Destination, Subject, Body, Attach, AttachName) -> 
	D = string:join(lists:map( fun(Addr) -> binary_to_list(Addr) end, Destination ), " " ), 
	S = io_lib:format("~p",[binary_to_list(Subject)]), 
	B = io_lib:format("~p",[binary_to_list(Body)]), 
	os:cmd("(echo "" ++ B ++ ""; uuencode "++binary_to_list(Attach)++" "++binary_to_list(AttachName)++") | mail -s ""++S++"" "++D).

send(Destination, Subject, Body) -> 
	D = string:join(lists:map( fun(Addr) -> binary_to_list(Addr) end, Destination ), " " ), 
	S = io_lib:format("~p",[binary_to_list(Subject)]), 
	B = io_lib:format("~p",[binary_to_list(Body)]), 
	os:cmd("echo "" ++ B ++ "" | mail -s "" ++ S ++ "" " ++ D).

send(Destination, Subject, Body, ContentType) -> 
	D = string:join(lists:map( fun(Addr) -> binary_to_list(Addr) end, Destination ), " " ), 
	S = io_lib:format("~p",[binary_to_list(Subject)]), 
	B = io_lib:format("~p",[binary_to_list(Body)]), 
	CT = binary_to_list(ContentType), 
	os:cmd("echo "" ++ B ++ "" | mail -a "Content-type: " ++ CT ++ ";" -s "" ++ S ++ "" " ++ D).

I think the script is quite clear to explain. The main trick here is usage of

uuencode and forwarding the output to the mail command. So, nothing complicated...

Here is a small usage example:

mailer:send([<<"foo@mail.org">>, <<"bar@mail.org">>], <<"hello">>, <<"Hello guys">>, <<"./test.txt">>, <<"CoolAttachment.txt">>).

I hope somebody will find this code helpful. Post your suggestions, if you know better ways to send e-mail from Erlang program.

Posted by:
Enjoyed this post? Share and Leave a comment below, thanks! :)