From 1e0618c93d247617ab9cf57fb5df382b7c4f04a7 Mon Sep 17 00:00:00 2001 From: Andrew Timberlake Date: Thu, 4 Dec 2025 16:03:01 +0200 Subject: [PATCH] A multipart message with a single part will respect the multipart structure on render --- lib/mail/renderers/rfc_2822.ex | 14 ++++++-------- test/mail/renderers/rfc_2822_test.exs | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/lib/mail/renderers/rfc_2822.ex b/lib/mail/renderers/rfc_2822.ex index 1ffccb4..dc2d442 100644 --- a/lib/mail/renderers/rfc_2822.ex +++ b/lib/mail/renderers/rfc_2822.ex @@ -300,14 +300,12 @@ defmodule Mail.Renderers.RFC2822 do Mail.Message.put_content_type(message, "multipart/mixed") else alternative = - case text_parts do - [part] -> - part - - text_parts -> - Mail.build_multipart() - |> Mail.Message.put_content_type("multipart/alternative") - |> Mail.Message.put_parts(text_parts) + if match?([_part], text_parts) && attachments != [] do + List.first(text_parts) + else + Mail.build_multipart() + |> Mail.Message.put_content_type("multipart/alternative") + |> Mail.Message.put_parts(text_parts) end related = diff --git a/test/mail/renderers/rfc_2822_test.exs b/test/mail/renderers/rfc_2822_test.exs index 2d490e1..932f7d5 100644 --- a/test/mail/renderers/rfc_2822_test.exs +++ b/test/mail/renderers/rfc_2822_test.exs @@ -410,6 +410,30 @@ defmodule Mail.Renderers.RFC2822Test do end describe "multipart configuration" do + # This test ensures that Mail.build_multipart() is respected even if only one part is supplied + test "multipart/alternative with only one part and no attachments" do + message = + Mail.build_multipart() + |> Mail.put_to("user1@example.com") + |> Mail.put_from({"User2", "user2@example.com"}) + |> Mail.put_subject("Test email") + |> Mail.put_text("Some text") + |> Mail.Renderers.RFC2822.render() + |> Mail.Parsers.RFC2822.parse() + + assert %Mail.Message{ + headers: %{"content-type" => ["multipart/alternative", {"boundary", _boundary}]}, + parts: [ + %Mail.Message{ + headers: %{"content-type" => ["text/plain", {"charset", "UTF-8"}]}, + body: "Some text", + parts: [], + multipart: false + } + ] + } = message + end + test "multipart/alternative with text/plain and text/html" do message = Mail.build_multipart()