Skip to content

Commit

Permalink
Add a fallback and logging when converting addresses to javamail
Browse files Browse the repository at this point in the history
There was an issue where it could not be determined which value was
the cause.
  • Loading branch information
eikek committed Feb 26, 2022
1 parent 7c3347a commit b37f84f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,35 @@ import emil.javamail.internal.{EmilMimeMessage, ThreadClassLoader}
import jakarta.activation.{DataHandler, DataSource}
import jakarta.mail._
import jakarta.mail.internet._
import org.log4s.getLogger

trait BasicEncode {
private val logger = getLogger

implicit def flagEncode: Conv[Flag, Flags.Flag] =
Conv { case Flag.Flagged =>
Flags.Flag.FLAGGED
}

implicit def mailAddressEncode: Conv[MailAddress, InternetAddress] =
Conv(mailAddress => new InternetAddress(mailAddress.displayString))
Conv { mailAddress =>
Either.catchNonFatal(new InternetAddress(mailAddress.displayString)) match {
case Right(a) => a
case Left(ex) =>
logger.warn(ex)(s"Error converting MailAddress '${mailAddress}' to javamail!")
Either.catchNonFatal(new InternetAddress(mailAddress.address)) match {
case Right(a) =>
logger.warn("Using address without name part.")
a
case Left(ex2) =>
logger.warn(
s"Using address without name '${mailAddress.address}' also failed: ${ex2.getMessage}"
)
ex.addSuppressed(ex2)
throw ex
}
}
}

implicit def attachmentEncode[F[_]: Sync]: Conv[Attachment[F], F[MimeBodyPart]] =
Conv { attach =>
Expand Down
17 changes: 17 additions & 0 deletions modules/javamail/src/test/scala/emil/javamail/MailConvTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import cats.effect._
import cats.effect.unsafe.implicits.global
import emil._
import emil.builder._
import emil.javamail.conv._
import emil.javamail.syntax._
import jakarta.mail.internet.InternetAddress
import munit._

class MailConvTest extends FunSuite {
Expand All @@ -23,6 +25,21 @@ class MailConvTest extends FunSuite {
)
}

test("write mail address") {
val ma1 = MailAddress.unsafe(Some("a;b;c"), "me@localhost")
val ma2 = MailAddress.unsafe(Some("a;b;c"), "me<@localhost")
val ma3 = MailAddress.unsafe(Some("Company name"), "[email protected]")
val addrConv = encode.mailAddressEncode

assertEquals(addrConv.convert(ma1), new InternetAddress("me@localhost"))
intercept[Exception](addrConv.convert(ma2))
assertEquals(
addrConv.convert(ma3),
new InternetAddress("\"Company name\" <[email protected]>")
)
assertEquals(addrConv.convert(ma3), new InternetAddress(ma3.displayString))
}

test("write text mail") {
val mail = MailBuilder.build[IO](
From("[email protected]"),
Expand Down

0 comments on commit b37f84f

Please sign in to comment.