       |> format_email_data
       |> convert_to_form_data
 
+    IO.inspect(payload)
+
     case HTTPoison.post(@api_url <> "mail.send.json", payload, headers) do
       { :ok, %{ status_code: 200 } } -> :ok
       { :ok, %{ body: body } } -> { :error, Poison.decode!(body)["errors"] }


  defp format_email_data(%Email{} = email) do
    from_name = email.from_name
    template = email.x_smtpapi
    reply_to = email.reply_to

    email
      |> Map.drop([:from_name, :x_smtpapi, :reply_to])
      |> Map.put(:fromname, from_name)
      |> Map.put(:replyto, reply_to)
      |> Map.put("x-smtpapi", Poison.encode!(template))
  end

  defp convert_to_form_data(email) do
    email

    |> Enum.join("&")
  end

  defp encode_attribute("x-smtpapi", value), do: "x-smtpapi=#{value}"
  defp encode_attribute(key, value), do: "#{ key }=#{ URI.encode_www_form(value) }"
end
