Zhenguo Yang
Zhenguo Yang

Reputation: 3910

How to user erlang gen_smtp to send html-formatted email?

gen_smtp can be found here

What I want is to let the content of email supports HTML tag, such as <strong>Hello</strong>

Will display as Hello.

Upvotes: 3

Views: 1704

Answers (3)

Emacs The Viking
Emacs The Viking

Reputation: 199

The answer given by @Ward Bekker is fundamentally correct but it took me a while to make it work as the mimemail:encode/1 expects a proplist not a map which the example shows. I used Erlang Erlang/OTP 23 [erts-11.0.3] and it failed with:

** exception error: no function clause matching proplists:get_value(<<"content-type-params">>, #{disposition => <<"inline">>,<<"content-type-params">> =>              [{<<"charset">>,<<"US-ASCII">>}]},[]) (proplists.erl, line 215)
     in function  mimemail:ensure_content_headers/7 (/Users/sean/Documents/code/erlang/scofblog/_build/default/lib/gen_smtp/src/mimemail.erl, line 661)

The following is the modified code and the encoded output:

Email = {
  <<"text">>,
  <<"html">>,
  [
    {<<"From">>, <<"[email protected]">>},
    {<<"To">>, <<"[email protected]">>},
    {<<"Subject">>, <<"This is a test">>}
  ],
  [{<<"content-type-params">>, [{<<"charset">>, <<"US-ASCII">>}]},
   {<<"disposition">>, <<"inline">>}
  ],
  <<"This is a <strong>HTML</strong> øÿ\r\nso there">>
}.

62> mimemail:encode(Email).
<<"From: [email protected]\r\nTo: [email protected]\r\nSubject: This is a test\r\nContent-Type: text/html;\r\n\tcharset=US-ASCII\r\nCon"...>>

Hope that saves some head scratching.

Upvotes: 0

Ward Bekker
Ward Bekker

Reputation: 6366

See the gen_smtp mimemail tests for an example of multipart/alternative messages:

Email = {<<"text">>, <<"html">>, [
  {<<"From">>, <<"[email protected]">>},
  {<<"To">>, <<"[email protected]">>},
  {<<"Subject">>, <<"This is a test">>}],
  #{content_type_params => [
    {<<"charset">>, <<"US-ASCII">>}],
    disposition => <<"inline">>
  },
  <<"This is a <strong>HTML</strong> message with some non-ascii characters øÿ\r\nso there">>},
Encoded = mimemail:encode(Email)

Upvotes: 2

P_A
P_A

Reputation: 1818

Look at https://github.com/selectel/pat. It's an easy to use SMTP client and you can use any text, including html tags as body of the message.

Upvotes: 2

Related Questions