Giter Site home page Giter Site logo

phoenix_swoosh's Introduction

Swoosh

hex.pm hex.pm hex.pm github.com

Compose, deliver and test your emails easily in Elixir.

Swoosh comes with many adapters, including SendGrid, Mandrill, Mailgun, Postmark and SMTP. See the full list of adapters below.

The complete documentation for Swoosh is available online at HexDocs.

Requirements

Elixir 1.13+ and Erlang OTP 24+

Getting started

# In your config/config.exs file
config :sample, Sample.Mailer,
  adapter: Swoosh.Adapters.Sendgrid,
  api_key: "SG.x.x"
# In your application code
defmodule Sample.Mailer do
  use Swoosh.Mailer, otp_app: :sample
end
defmodule Sample.UserEmail do
  import Swoosh.Email

  def welcome(user) do
    new()
    |> to({user.name, user.email})
    |> from({"Dr B Banner", "[email protected]"})
    |> subject("Hello, Avengers!")
    |> html_body("<h1>Hello #{user.name}</h1>")
    |> text_body("Hello #{user.name}\n")
  end
end
# In an IEx session
email = Sample.UserEmail.welcome(%{name: "Tony Stark", email: "[email protected]"})
Sample.Mailer.deliver(email)
# Or in a Phoenix controller
defmodule Sample.UserController do
  use Phoenix.Controller
  alias Sample.UserEmail
  alias Sample.Mailer

  def create(conn, params) do
    user = create_user!(params)

    UserEmail.welcome(user) |> Mailer.deliver()
  end
end

See Swoosh.Mailer for more configuration options.

Installation

  • Add swoosh to your list of dependencies in mix.exs:

    def deps do
      [{:swoosh, "~> 1.16"}]
    end
  • (Optional-ish) Most adapters (non SMTP ones) use Swoosh.ApiClient to talk to the service provider. Swoosh comes with Swoosh.ApiClient.Hackney configured by default. If you want to use it, you just need to include Hackney as a dependency of your app.

    Swoosh also accepts Finch and Req out-of-the-box. See Swoosh.ApiClient.Finch and Swoosh.ApiClient.Req for details.

    If you need to integrate with another HTTP client, it's easy to define a new API client. Follow the Swoosh.ApiClient behaviour and configure Swoosh to use it:

    config :swoosh, :api_client, MyApp.ApiClient

    But if you don't need Swoosh.ApiClient, you can disable it by setting the value to false:

    config :swoosh, :api_client, false

    This is the case when you are using Swoosh.Adapters.Local, Swoosh.Adapters.Test and adapters that are SMTP based, that don't require an API client.

  • (Optional) If you are using Swoosh.Adapters.SMTP, Swoosh.Adapters.Sendmail or Swoosh.Adapters.AmazonSES, you also need to add gen_smtp to your dependencies:

    def deps do
      [
        {:swoosh, "~> 1.6"},
        {:gen_smtp, "~> 1.0"}
      ]
    end

Adapters

Swoosh supports the most popular transactional email providers out of the box and also has an SMTP adapter. Below is the list of the adapters currently included:

Provider Swoosh adapter Remarks
SMTP Swoosh.Adapters.SMTP
Mua Swoosh.Adapters.Mua SMTP alternative
SendGrid Swoosh.Adapters.Sendgrid
Brevo Swoosh.Adapters.Brevo Sendinblue
Sendmail Swoosh.Adapters.Sendmail
Mandrill Swoosh.Adapters.Mandrill
Mailgun Swoosh.Adapters.Mailgun
Mailjet Swoosh.Adapters.Mailjet
MsGraph Swoosh.Adapters.MsGraph
Postmark Swoosh.Adapters.Postmark
SparkPost Swoosh.Adapters.SparkPost
Amazon SES Swoosh.Adapters.AmazonSES
Amazon SES Swoosh.Adapters.ExAwsAmazonSES
Dyn Swoosh.Adapters.Dyn
Scaleway Swoosh.Adapters.Scaleway
SocketLabs Swoosh.Adapters.SocketLabs
Gmail Swoosh.Adapters.Gmail
MailPace Swoosh.Adapters.MailPace OhMySMTP
SMTP2GO Swoosh.Adapters.SMTP2GO
ProtonBridge Swoosh.Adapters.ProtonBridge
Mailtrap Swoosh.Adapters.Mailtrap
ZeptoMail Swoosh.Adapters.ZeptoMail

Configure which adapter you want to use by updating your config/config.exs file:

config :sample, Sample.Mailer,
  adapter: Swoosh.Adapters.SMTP
  # adapter config (api keys, etc.)

Check the documentation of the adapter you want to use for more specific configurations and instructions.

Adding new adapters is super easy and we are definitely looking for contributions on that front. Get in touch if you want to help!

Recipient

The Recipient Protocol enables you to easily make your structs compatible with Swoosh functions.

defmodule MyUser do
  @derive {Swoosh.Email.Recipient, name: :name, address: :email}
  defstruct [:name, :email, :other_props]
end

Now you can directly pass %MyUser{} to from, to, cc, bcc, etc. See Swoosh.Email.Recipient for more details.

Async Emails

Swoosh does not make any special arrangements for sending emails in a non-blocking manner. Opposite to some stacks, sending emails, talking to third party apps, etc in Elixir do not block or interfere with other requests, so you should resort to async emails only when necessary.

One simple way to deliver emails asynchronously is by leveraging Elixir's standard library. First add a Task supervisor to your application root, usually at lib/my_app/application.ex:

def start(_, _) do
  children = [
    ...,
    # Before the endpoint
    {Task.Supervisor, name: MyApp.AsyncEmailSupervisor},
    MyApp.Endpoint
  ]

  Supervisor.start_link(children, strategy: :one_for_one)
end

Now, whenever you want to send an email:

Task.Supervisor.start_child(MyApp.AsyncEmailSupervisor, fn ->
  %{name: "Tony Stark", email: "[email protected]"}
  |> Sample.UserEmail.welcome()
  |> Sample.Mailer.deliver()
end)

Please take a look at the official docs for Task and Task.Supervisor for further options.

One of the downsides of sending email asynchronously is that failures won't be reported to the user, who won't have an opportunity to try again immediately, and tasks by default do not retry on errors. Therefore, if the email must be delivered asynchronously, a safer solution would be to use a queue or job system. Elixir's ecosystem has many job queue libraries.

  • Oban is the current community favourite. It uses PostgreSQL for storage and coordination.
  • Exq uses Redis and is compatible with Resque / Sidekiq.

Attachments

You can attach files to your email using the Swoosh.Email.attachment/2 function. Just give the path of your file as an argument and we will do the rest. It also works with a %Plug.Upload{} struct, or a %Swoosh.Attachment{} struct, which can be constructed using Swoosh.Attachment.new detailed here in the docs.

All built-in adapters have support for attachments.

new()
|> to("[email protected]")
|> from({"Jarvis", "[email protected]"})
|> subject("Invoice May")
|> text_body("Here is the invoice for your superhero services in May.")
|> attachment("/Users/jarvis/invoice-peter-may.pdf")

Testing

In your config/test.exs file set your mailer's adapter to Swoosh.Adapters.Test so that you can use the assertions provided by Swoosh in Swoosh.TestAssertions module.

defmodule Sample.UserTest do
  use ExUnit.Case, async: true

  import Swoosh.TestAssertions

  test "send email on user signup" do
    # Assuming `create_user` creates a new user then sends out a
    # `Sample.UserEmail.welcome` email
    user = create_user(%{username: "ironman", email: "[email protected]"})
    assert_email_sent Sample.UserEmail.welcome(user)
  end
end

Mailbox preview in the browser

Swoosh ships with a Plug that allows you to preview the emails in the local (in-memory) mailbox. It's particularly convenient in development when you want to check what your email will look like while testing the various flows of your application.

For email to reach this mailbox you will need to set your Mailer adapter to Swoosh.Adapters.Local:

# in config/dev.exs
config :sample, MyApp.Mailer,
  adapter: Swoosh.Adapters.Local

In your Phoenix project you can forward directly to the plug without spinning up a separate webserver, like this:

# in web/router.ex
if Mix.env == :dev do
  scope "/dev" do
    pipe_through [:browser]

    forward "/mailbox", Plug.Swoosh.MailboxPreview
  end
end

You can also start a new server if your application does not depends on Phoenix:

# in config/dev.exs
# to run the preview server alongside your app
# which may not have a web interface already
config :swoosh, serve_mailbox: true
# in config/dev.exs
# to change the preview server port (4000 by default)
config :swoosh, serve_mailbox: true, preview_port: 4001

When using serve_mailbox: true make sure to have either plug_cowboy or bandit as a dependency of your app.

{:plug_cowboy, ">= 1.0.0"}
# or
{:bandit, ">= 1.0.0"}

And finally you can also use the following Mix task to start the mailbox preview server independently:

mix swoosh.mailbox.server

Note: the mailbox preview won't display emails being sent from outside its own node. So if you are testing using an IEx session, it's recommended to boot the application in the same session. iex -S mix phx.server or iex -S mix swoosh.mailbox.server will do the trick.

If you are curious, this is how it the mailbox preview looks like:

Plug.Swoosh.MailboxPreview

Note : To show the preview we use the cdn-version of Tailwindcss. If you have set a content-security-policy you may have to add https://cdn.tailwindcss.com to default-src to have the correct make up.

The preview is also available as a JSON endpoint.

curl http://localhost:4000/dev/mailbox/json

Production

Swoosh starts a memory storage process for local adapter by default. Normally it does no harm being left around in production. However, if it is causing problems, or you don't like having it around, it can be disabled like so:

# config/prod.exs
config :swoosh, local: false

Telemetry

The following events are emitted:

  • [:swoosh, :deliver, :start]: occurs when Mailer.deliver/2 begins.
  • [:swoosh, :deliver, :stop]: occurs when Mailer.deliver/2 completes.
  • [:swoosh, :deliver, :exception]: occurs when Mailer.deliver/2 throws an exception.
  • [:swoosh, :deliver_many, :start]: occurs when Mailer.deliver_many/2 begins.
  • [:swoosh, :deliver_many, :stop]: occurs when Mailer.deliver_many/2 completes.
  • [:swoosh, :deliver_many, :exception]: occurs when Mailer.deliver_many/2 throws an exception.

View example in docs

Documentation

Documentation is written into the library, you will find it in the source code, accessible from iex and of course, it all gets published to HexDocs.

Contributing

We are grateful for any contributions. Before you submit an issue or a pull request, remember to:

  • Look at our Contributing guidelines
  • Not use the issue tracker for help or support requests (try StackOverflow, IRC or Slack instead)
  • Do a quick search in the issue tracker to make sure the issues hasn't been reported yet.
  • Look and follow the Code of Conduct. Be nice and have fun!

Running tests

Clone the repo and fetch its dependencies:

git clone https://github.com/swoosh/swoosh.git
cd swoosh
mix deps.get
mix test

Building docs

MIX_ENV=docs mix docs

LICENSE

See LICENSE

phoenix_swoosh's People

Contributors

chrisalley avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar dkln avatar josevalim avatar jswanner avatar kianmeng avatar mamespalmero avatar mdoza avatar princemaple avatar stevedomin avatar talklittle avatar victorsolis avatar wmnnd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

phoenix_swoosh's Issues

render_body exception when using email as an assign.

I just ran into a previously closed issue: swoosh/swoosh#152

The exception was "protocol Phoenix.HTML.Safe not implemented for %Swoosh.Email", and the solution mentioned was:

|> render_body("welcome.html", %{email: user.email}) # <--- don't do this

What do you think about raising an exception "don't use email for assigns". I think the place to put it is right before here: https://github.com/swoosh/phoenix_swoosh/blob/master/lib/phoenix_swoosh.ex#L159

content = Phoenix.View.render_to_string(view, template, Map.put(email.assigns, :email, email))

I can submit a PR if the approach seems fine.

Upgrading to Swoosh 0.13

It looks like Swoosh 0.1.0 is over two years old at this point. Any reason not to upgrade to a more recent release? I'm interested in getting access to the AmazonSES adapter found in a more recent version of Swoosh but definitely is not in 0.1.0.

ArgumentError: 1st argument: not an iodata term

I'm getting an error when trying to send an email with both an HTML and text version using render_body.

I made a minimal app here that replicates the problem. Steps:

  1. Generate a new Phoenix 1.6 app and add phoenix_swoosh as a dependency.
  2. Add a notifier class with a corresponding view:
# lib/email_demo/notifier.ex
defmodule EmailDemo.Notifier do
  import Swoosh.Email
  use Phoenix.Swoosh, view: EmailDemoWeb.NotifierView

  alias EmailDemo.Mailer

  def deliver do
    email =
      new()
      |> to("[email protected]")
      |> from({"Someone Else", "[email protected]"})
      |> subject("Subject")
      |> render_body(:email)

    with {:ok, _metadata} <- Mailer.deliver(email) do
      {:ok, email}
    end
  end
end

# lib/email_demo_web/views/notifier_view.ex 
defmodule EmailDemoWeb.NotifierView do
  use EmailDemoWeb, :view
end
  1. Add HTML and text templates:

lib/email_demo_web/templates/notifier/email.text.heex:

This is a plaintext email    

lib/email_demo_web/templates/notifier/email.html.heex:

<p>This is an HTML email</p>                                                                                                                                                                                                                                             
  1. Set things up to deliver an email when you visit the home page:
defmodule EmailDemoWeb.PageController do
  use EmailDemoWeb, :controller

  def index(conn, _params) do
    EmailDemo.Notifier.deliver
    render(conn, "index.html")
  end
end

Now visit the homepage aaaaand... kaboom:

image

Is this a bug, or am I doing something wrong?


To make this searchable I'm going to c&p the whole error and stacktrace:
# ArgumentError at GET /

Exception:

    ** (ArgumentError) errors were found at the given arguments:
    
      * 1st argument: not an iodata term
    
        :erlang.iolist_to_binary(%Phoenix.LiveView.Rendered{static: ["This is a plaintext email\n"], dynamic: #Function&lt;1.35421111/1 in EmailDemoWeb.NotifierView."email.text"/1&gt;, fingerprint: 61109027427193190218149404380223381180, root: false})
        (phoenix_view 2.0.2) lib/phoenix_view.ex:564: Phoenix.View.render_to_string/3
        (phoenix_swoosh 1.2.0) lib/phoenix_swoosh.ex:172: Phoenix.Swoosh.do_render_body/4
        (elixir 1.14.3) lib/enum.ex:2468: Enum."-reduce/3-lists^foldl/2-0-"/3
        (email_demo 0.1.0) lib/email_demo/notifier.ex:13: EmailDemo.Notifier.deliver/0
        (email_demo 0.1.0) lib/email_demo_web/controllers/page_controller.ex:5: EmailDemoWeb.PageController.index/2
        (email_demo 0.1.0) lib/email_demo_web/controllers/page_controller.ex:1: EmailDemoWeb.PageController.action/2
        (email_demo 0.1.0) lib/email_demo_web/controllers/page_controller.ex:1: EmailDemoWeb.PageController.phoenix_controller_pipeline/2
        (phoenix 1.6.16) lib/phoenix/router.ex:354: Phoenix.Router.__call__/2
        (email_demo 0.1.0) lib/email_demo_web/endpoint.ex:1: EmailDemoWeb.Endpoint.plug_builder_call/2
        (email_demo 0.1.0) lib/plug/debugger.ex:136: EmailDemoWeb.Endpoint."call (overridable 3)"/2
        (email_demo 0.1.0) lib/email_demo_web/endpoint.ex:1: EmailDemoWeb.Endpoint.call/2
        (phoenix 1.6.16) lib/phoenix/endpoint/cowboy2_handler.ex:54: Phoenix.Endpoint.Cowboy2Handler.init/4
        (cowboy 2.9.0) /Users/george/arrowsmith/por/email_demo/deps/cowboy/src/cowboy_handler.erl:37: :cowboy_handler.execute/2
        (cowboy 2.9.0) /Users/george/arrowsmith/por/email_demo/deps/cowboy/src/cowboy_stream_h.erl:306: :cowboy_stream_h.execute/3
        (cowboy 2.9.0) /Users/george/arrowsmith/por/email_demo/deps/cowboy/src/cowboy_stream_h.erl:295: :cowboy_stream_h.request_process/3
        (stdlib 4.3) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
    

Code:

`nofile`

    No code available.

  Called with 1 arguments

  * `%Phoenix.LiveView.Rendered{static: ["This is a plaintext email\n"], dynamic: #Function&lt;1.35421111/1 in EmailDemoWeb.NotifierView."email.text"/1&gt;, fingerprint: 61109027427193190218149404380223381180, root: false}`
  
`lib/phoenix_view.ex`

    559   
    560     @doc """
    561     Renders the template and returns a string.
    562     """
    563     def render_to_string(module, template, assign) do
    564&gt;      render_to_iodata(module, template, assign) |&gt; IO.iodata_to_binary()
    565     end
    566   
    567     defp encode(content, template) do
    568       "." &lt;&gt; format = Path.extname(template)
    569   
    
`lib/phoenix_swoosh.ex`

    167   
    168       view =
    169         Map.get(email.private, :phoenix_view) ||
    170           raise "a view module was not specified, set one with put_view/2"
    171   
    172&gt;      content = Phoenix.View.render_to_string(view, template, Map.put(email.assigns, :email, email))
    173       Map.put(email, extension_to_body_key(email, extension), content)
    174     end
    175   
    176     @doc """
    177     Stores the formats for rendering if none was stored yet.
    
`lib/enum.ex`

    No code available.

`lib/email_demo/notifier.ex`

    8       email =
    9         new()
    10         |&gt; to("[email protected]")
    11         |&gt; from({"Someone Else", "[email protected]"})
    12         |&gt; subject("Subject")
    13&gt;        |&gt; render_body(:email)
    14   
    15       with {:ok, _metadata} &lt;- Mailer.deliver(email) do
    16         {:ok, email}
    17       end
    18     end
    
`lib/email_demo_web/controllers/page_controller.ex`

    1   defmodule EmailDemoWeb.PageController do
    2     use EmailDemoWeb, :controller
    3   
    4     def index(conn, _params) do
    5&gt;      EmailDemo.Notifier.deliver
    6       render(conn, "index.html")
    7     end
    8   end
    
`lib/email_demo_web/controllers/page_controller.ex`

    1&gt;  defmodule EmailDemoWeb.PageController do
    2     use EmailDemoWeb, :controller
    3   
    4     def index(conn, _params) do
    5       EmailDemo.Notifier.deliver
    6       render(conn, "index.html")
    
`lib/email_demo_web/controllers/page_controller.ex`

    1&gt;  defmodule EmailDemoWeb.PageController do
    2     use EmailDemoWeb, :controller
    3   
    4     def index(conn, _params) do
    5       EmailDemo.Notifier.deliver
    6       render(conn, "index.html")
    
`lib/phoenix/router.ex`

    349           metadata = %{metadata | conn: halted_conn}
    350           :telemetry.execute([:phoenix, :router_dispatch, :stop], measurements, metadata)
    351           halted_conn
    352         %Plug.Conn{} = piped_conn -&gt;
    353           try do
    354&gt;            plug.call(piped_conn, plug.init(opts))
    355           else
    356             conn -&gt;
    357               measurements = %{duration: System.monotonic_time() - start}
    358               metadata = %{metadata | conn: conn}
    359               :telemetry.execute([:phoenix, :router_dispatch, :stop], measurements, metadata)
    
`lib/email_demo_web/endpoint.ex`

    1&gt;  defmodule EmailDemoWeb.Endpoint do
    2     use Phoenix.Endpoint, otp_app: :email_demo
    3   
    4     # The session will be stored in the cookie and signed,
    5     # this means its contents can be read but not tampered with.
    6     # Set :encryption_salt if you would also like to encrypt it.
    
`lib/plug/debugger.ex`

    No code available.

`lib/email_demo_web/endpoint.ex`

    1&gt;  defmodule EmailDemoWeb.Endpoint do
    2     use Phoenix.Endpoint, otp_app: :email_demo
    3   
    4     # The session will be stored in the cookie and signed,
    5     # this means its contents can be read but not tampered with.
    6     # Set :encryption_salt if you would also like to encrypt it.
    
`lib/phoenix/endpoint/cowboy2_handler.ex`

    49             end
    50   
    51           {:plug, conn, handler, opts} -&gt;
    52             %{adapter: {@connection, req}} =
    53               conn
    54&gt;              |&gt; handler.call(opts)
    55               |&gt; maybe_send(handler)
    56   
    57             {:ok, req, {handler, opts}}
    58         end
    59       catch
    
`/Users/george/arrowsmith/por/email_demo/deps/cowboy/src/cowboy_handler.erl`

    32   -optional_callbacks([terminate/3]).
    33   
    34   -spec execute(Req, Env) -&gt; {ok, Req, Env}
    35   	when Req::cowboy_req:req(), Env::cowboy_middleware:env().
    36   execute(Req, Env=#{handler := Handler, handler_opts := HandlerOpts}) -&gt;
    37&gt;  	try Handler:init(Req, HandlerOpts) of
    38   		{ok, Req2, State} -&gt;
    39   			Result = terminate(normal, Req2, State, Handler),
    40   			{ok, Req2, Env#{result =&gt; Result}};
    41   		{Mod, Req2, State} -&gt;
    42   			Mod:upgrade(Req2, Env, Handler, State);
    
`/Users/george/arrowsmith/por/email_demo/deps/cowboy/src/cowboy_stream_h.erl`

    301   	end.
    302   
    303   execute(_, _, []) -&gt;
    304   	ok;
    305   execute(Req, Env, [Middleware|Tail]) -&gt;
    306&gt;  	case Middleware:execute(Req, Env) of
    307   		{ok, Req2, Env2} -&gt;
    308   			execute(Req2, Env2, Tail);
    309   		{suspend, Module, Function, Args} -&gt;
    310   			proc_lib:hibernate(?MODULE, resume, [Env, Tail, Module, Function, Args]);
    311   		{stop, _Req2} -&gt;
    
`/Users/george/arrowsmith/por/email_demo/deps/cowboy/src/cowboy_stream_h.erl`

    290   %% to simplify the debugging of errors. The proc_lib library
    291   %% already adds the stacktrace to other types of exceptions.
    292   -spec request_process(cowboy_req:req(), cowboy_middleware:env(), [module()]) -&gt; ok.
    293   request_process(Req, Env, Middlewares) -&gt;
    294   	try
    295&gt;  		execute(Req, Env, Middlewares)
    296   	catch
    297   		exit:Reason={shutdown, _}:Stacktrace -&gt;
    298   			erlang:raise(exit, Reason, Stacktrace);
    299   		exit:Reason:Stacktrace when Reason =/= normal, Reason =/= shutdown -&gt;
    300   			erlang:raise(exit, {Reason, Stacktrace}, Stacktrace)
    
`proc_lib.erl`

    No code available.


## Connection details

### Params

    %{}

### Request info

  * URI: http://localhost:4000/
  * Query string: 

### Headers
  
  * accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8
  * accept-encoding: gzip, deflate, br
  * accept-language: en-GB,en-US;q=0.9,en;q=0.8
  * connection: keep-alive
  * cookie: _lr_uf_-wly4ri=c1297a67-a292-4fe8-952e-1ca73a54510e; _twittex_key=SFMyNTY.g3QAAAADbQAAAAtfY3NyZl90b2tlbm0AAAAYWGxOV1o4bGptRzkwbkgzNHNFUi1pZHl0bQAAAA5saXZlX3NvY2tldF9pZG0AAAA7dXNlcnNfc2Vzc2lvbnM6Z3Qta1B1U3lhOUxqWjdGV0hITE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faWQiOjN9.fBO1z9ShpQ9gAqfaFX8rA82eDeRoTjoGfnScLoahgvg; infor_user={%22id%22:3%2C%22url%22:%22http://localhost:8000/api/users/3/%22%2C%22first_name%22:%22Test%22%2C%22last_name%22:%22Client%22%2C%22email%22:%[email protected]%22%2C%22phone%22:%22%22%2C%22alter_phone%22:null%2C%22authy_id%22:%22%22%2C%22company%22:%22Ground%20Truth%20Intelligence%22%2C%22street_address%22:%2227%20Dev%20Test%20Rd%22%2C%22apartment%22:%22%22%2C%22biography%22:%22%22%2C%22tags%22:[]%2C%22tag_groups%22:[]%2C%22avatar%22:null%2C%22is_client%22:true%2C%22is_administrator%22:false%2C%22is_network_partner%22:false%2C%22accept_batch%22:false%2C%22timezone%22:%22America/New_York%22%2C%22dual_account%22:null%2C%22is_active%22:true%2C%22full_name%22:%22Test%20Client%22%2C%22edit_role%22:false%2C%22is_auto_tag%22:true%2C%22is_deleted%22:false%2C%22notes%22:%22%22%2C%22team%22:{%22id%22:1%2C%22name%22:%22Test%20team%22}%2C%22role%22:%221%22%2C%22id_client%22:3}; type_view=Client%20Mode; tw=eyJhbGciOiJIUzI1NiIsImN0eSI6InR3aWxpby1mcGE7dj0xIiwidHlwIjoiSldUIn0.eyJqdGkiOiJTSzYzYWY2MjcwNWU0Yjk3ZTYyYWY1NTZiODRmNDM1NmQ3LTE2ODEzMTAxNjgiLCJncmFudHMiOnsiZGF0YV9zeW5jIjp7InNlcnZpY2Vfc2lkIjoiSVM2NmE3MzNmYWQ2YzIzNWRjNzM4MzVlMWE1N2ZkNGM2OCJ9LCJjaGF0Ijp7InNlcnZpY2Vfc2lkIjoiSVNjMGQwYTQ0YmQ5YzQ0YmQ1ODY3ZTZmMTRmMzQ4NjM5OCJ9LCJpZGVudGl0eSI6IjMifSwiaXNzIjoiU0s2M2FmNjI3MDVlNGI5N2U2MmFmNTU2Yjg0ZjQzNTZkNyIsImV4cCI6MTY4MTMxMzc2OCwibmJmIjoxNjgxMzEwMTY4LCJzdWIiOiJBQ2M1NzQwZGE5Y2JmYzQyZWZiYTc3ZTYyOTA0NWIxYWJmIn0.2qr8rLSVtfDRzP5QLMbLH9V94Y0lBQ89Yf3f14_XtWo; _trip_key=SFMyNTY.g3QAAAADbQAAAAtfY3NyZl90b2tlbm0AAAAYSmtjUHFMUTRudEJlbEQzNDdHU3BKQ3ZobQAAAA5saXZlX3NvY2tldF9pZG0AAAA7dXNlcnNfc2Vzc2lvbnM6MEMxUHRKdFdqeXZpMmk0b0RsaXlQOEJvS3h6dkRYNmc1N2N1WVZOMTVUQT1tAAAACnVzZXJfdG9rZW5tAAAAINAtT7SbVo8r4touKA5Ysj_AaCsc7w1-oOe3LmFTdeUw.A2Yyb3XvDcjrpAAkLWkG6SfcteZg724v6xeRNnuTMxM; _email_demo_key=SFMyNTY.g3QAAAABbQAAAAtfY3NyZl90b2tlbm0AAAAYbFBrZUZEdmlGTmtWZnlCOVlPdU5UaUFo.4KfqbHoZnjCfirkBczxRssAvay5q1A6B7-Cirm3xMzw
  * host: localhost:4000
  * sec-ch-ua: "Brave";v="111", "Not(A:Brand";v="8", "Chromium";v="111"
  * sec-ch-ua-mobile: ?0
  * sec-ch-ua-platform: "macOS"
  * sec-fetch-dest: document
  * sec-fetch-mode: navigate
  * sec-fetch-site: none
  * sec-fetch-user: ?1
  * sec-gpc: 1
  * upgrade-insecure-requests: 1
  * user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36

### Session

    %{"_csrf_token" =&gt; "lPkeFDviFNkVfyB9YOuNTiAh"}

phoenix_html 4.0 compatibility

The current version of Swoosh (1.2.0) depends on phoenix_html "~> 3.0". Since 4.0 is out now this has started causing some compatibility problems for me, as other libraries are moving to phoenix_html 4.0.

It'd be great to have phoenix_swoosh upgrade the phoenix_html dep to ~> 4.0.
I'd be happy to give the upgrade a shot myself if that's OK?

Incorrect Swoosh.Email struct keys set

phoenix_swoosh saves rendered content under the :"#{file_extension}_body" key. This forces users to use the .htmland the unusual.text` extensions. Otherwise, the Email struct does not contain a valid body field.

Error when following User_Email example

Received this error when following Phoenix.Swoosh docs.

(CompileError) web/emails/user_email.ex:6: Email.__struct__/1 is undefined, cannot expand struct Email

Using this code

def welcome(user) do
    %Email{}
    |> from("[email protected]")
    |> to(user.email)
    |> subject("Welcome to Sample!")
    |> render_body("welcome.html", %{name: user.name})
  end

Was able to fix it by following Swoosh docs instead and replacing %Email{} with new.

phoenix 1.6-rc0 - render_body with atom do nothing

Hi, i upgraded my webapp to phoenix 1.6-rc0 and now the tests of mail sending are failing
I noticed that the cause is render body with atom parameter (:registration_confirm) do nothing. No error is reported:

new()
|> to({user.name, user.email})
|> from(@from)
|> subject(subject)
|> render_body(:registration_confirm, %{username: user.name, url: url, subject: subject})

But if i change this in:
new()
|> to({user.name, user.email})
|> from(@from)
|> subject(subject)
|> render_body("registration_confirm.html", %{username: user.name, url: url, subject: subject})

It works. In my app there are the "registration_confirm.html.eex" and "registration_confirm.text.eex"
Is not possible using atom any more?

would it be possible to do another release ?

Since the last release uses html < 3.0.0, this is currently blocking upgrades to phoenix and live_view.

Would it be possible to do another release ?

Is there any way that I can help ?

respect the bang syntax

Most functions in elixir now embrace the bang syntax of:

  # This will raise if something happens
  render_body!(...)

  # This will return a tuple with {:ok, result} | {:error, error}
  render_body(...)

You can even do something like this:

render_body!(...) do
  case render_body(...) do
    {:ok, result} -> result
   {:error, error} -> raise error
  end
end

Release a version based on phoenix 1.3.0-rc

I'm trying to publish a package (coherence) that has this project as a dependency. The version I'm trying to publish has a dependency on phoenix-1.3.0-rc. I tried to publish my package with an override on phoenix, but hex won't allow that.

Any chance you could publish a version with the updated phoenix dependency? Perhaps a rc version?

Not yet published?

So I tried to upgrade to swoosh 1.0 (congrats! ๐ŸŽ‰ )

But when I did that, I got:

mix deps.get
Resolving Hex dependencies...

Failed to use "swoosh" (version 1.0.0) because
  phoenix_swoosh (version 0.2.0) requires ~> 0.1
  mix.exs specifies ~> 1.0.0

** (Mix) Hex dependency resolution failed, change the version requirements of your dependencies or unlock them (by using mix deps.update or mix deps.unlock). If you are unable to resolve the conflicts you can try overriding with {:dependency, "~> 1.0", override: true}

But if I look at phoenix_swoosh's mix.exs, there is:

  defp deps do
    [{:swoosh, "~> 1.0"},
    ...
  end

Any idea why? Maybe phoenix_swoosh upgrade hasn't been published yet?

Cheers

Implement .render_subject/2 and .render_subject/3

For Example:

.render_subject/2

Renders a phoenix template from previous assigns

iex> new(assigns: %{name: "Sitch"})
     |> render_subject("welcome.html") # contains `Welcome, <%= @name %>!`

%{assigns: %{name: "Sitch"}, subject: "Welcome, Sitch!"}

Renders a ~S sigil from previous assigns

iex> new(assigns: %{name: "Sitch"})
     |> render_subject(~S(Welcome, <%= @name %>!)))

%{assigns: %{name: "Sitch"}, subject: "Welcome, Sitch!"}

.render_subject/3

Renders a phoenix template with merged assigns

iex> new()
     |> render_subject("welcome.html", name: "Sitch") # contains `Welcome, <%= @name %>!`

%{assigns: %{name: "Sitch"}, subject: "Welcome, Sitch!"}

Renders a ~S sigil with with merged assigns

iex> new()
     |> render_subject(~S(Welcome, <%= @name %>!), %{name: "Sitch"})

%{assigns: %{name: "Sitch"}, subject: "Welcome, Sitch!"}

A heads up: we have extract phoenix_view into a separate project

Hi everyone,

Thanks for the amazing lib!

Just a heads up, we have extract Phoenix.View into a separate library so it is easier for projects like Swoosh to add template rendering without depending on all of Phoenix: https://github.com/phoenixframework/phoenix_view

When Phoenix v1.6 comes out, you should be able to depend on phoenix_view. Although keep in mind that if someone is using phoenix v1.5 or earlier, then will run into issues. So you should probably either do a new major release or keep {:phoenix, "~> 1.6", optional: true} just as a check to avoid conflicts.

How is the struct %Email{} available?

The example fails for me

defmodule Sample.UserEmail do
  use Phoenix.Swoosh, view: Sample.EmailView

  def welcome(user) do
    %Email{}   # <-- undefined
    |> from("[email protected]")
    |> to(user.email)
    |> subject("Hello, Avengers!")
    |> render_body("welcome.html", %{username: user.email})
  end
end

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.