├── .github ├── mergify.yml ├── workflows │ ├── publish.yml │ ├── release-drafter.yml │ ├── dependency-graph.yml │ └── build-test.yml ├── scala-steward.conf └── dependabot.yml ├── project ├── build.properties ├── plugins.sbt ├── Dependencies.scala └── Common.scala ├── samples ├── runtimeDI │ ├── project │ │ ├── build.properties │ │ └── plugins.sbt │ ├── public │ │ └── images │ │ │ └── favicon.png │ ├── conf │ │ ├── routes │ │ └── application.conf │ ├── app │ │ └── controllers │ │ │ ├── CustomSMTPConfigurationProvider.scala │ │ │ ├── ApplicationJava.java │ │ │ └── ApplicationScala.scala │ └── build.sbt └── compile-timeDI │ ├── project │ ├── build.properties │ └── plugins.sbt │ ├── public │ └── images │ │ └── favicon.png │ ├── conf │ ├── routes │ └── application.conf │ ├── build.sbt │ └── app │ ├── SimpleApplicationLoader.scala │ └── controllers │ └── ApplicationScala.scala ├── .gitignore ├── play-mailer └── src │ ├── test │ ├── resources │ │ └── play_icon_full_color.png │ └── scala │ │ └── play │ │ └── api │ │ └── libs │ │ └── mailer │ │ └── MailerPluginSpec.scala │ └── main │ ├── scala │ └── play │ │ └── api │ │ └── libs │ │ └── mailer │ │ ├── MailerComponents.scala │ │ ├── SMTPDynamicMailer.scala │ │ ├── SMTPConfigurationProvider.scala │ │ ├── Email.scala │ │ ├── SMTPMailer.scala │ │ ├── MockMailer.scala │ │ ├── Attachment.scala │ │ ├── SMTPConfiguration.scala │ │ ├── MailerClient.scala │ │ └── CommonsMailer.scala │ ├── java │ └── play │ │ └── libs │ │ └── mailer │ │ ├── MailerClient.java │ │ ├── Attachment.java │ │ └── Email.java │ └── resources │ └── reference.conf ├── play-mailer-guice └── src │ ├── main │ ├── resources │ │ └── reference.conf │ └── scala │ │ └── play │ │ └── api │ │ └── libs │ │ └── mailer │ │ ├── MailerConfigurationModule.scala │ │ ├── SMTPConfigurationModule.scala │ │ └── MailerModule.scala │ └── test │ └── scala │ └── play │ └── api │ └── libs │ └── mailer │ ├── ConfigModule.scala │ └── MailerPluginGuiceSpec.scala ├── .editorconfig ├── README.md └── LICENSE /.github/mergify.yml: -------------------------------------------------------------------------------- 1 | extends: .github 2 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.11.7 2 | -------------------------------------------------------------------------------- /samples/runtimeDI/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.11.7 2 | -------------------------------------------------------------------------------- /samples/compile-timeDI/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.11.7 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .bsp/ 2 | target/ 3 | logs/ 4 | *.lock 5 | .DS_Store 6 | .history 7 | .idea 8 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.1.4") 2 | addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.11.2") 3 | -------------------------------------------------------------------------------- /samples/runtimeDI/public/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playframework/play-mailer/main/samples/runtimeDI/public/images/favicon.png -------------------------------------------------------------------------------- /samples/compile-timeDI/public/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playframework/play-mailer/main/samples/compile-timeDI/public/images/favicon.png -------------------------------------------------------------------------------- /play-mailer/src/test/resources/play_icon_full_color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playframework/play-mailer/main/play-mailer/src/test/resources/play_icon_full_color.png -------------------------------------------------------------------------------- /play-mailer-guice/src/main/resources/reference.conf: -------------------------------------------------------------------------------- 1 | play.modules { 2 | enabled += "play.api.libs.mailer.MailerModule" 3 | enabled += "play.api.libs.mailer.SMTPConfigurationModule" 4 | } 5 | -------------------------------------------------------------------------------- /samples/runtimeDI/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("org.playframework" % "sbt-plugin" % sys.env.getOrElse("PLAY_VERSION", "3.1.0-M4")) 2 | addSbtPlugin("com.github.sbt" % "sbt-dynver" % "5.1.1") 3 | -------------------------------------------------------------------------------- /samples/compile-timeDI/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("org.playframework" % "sbt-plugin" % sys.env.getOrElse("PLAY_VERSION", "3.1.0-M4")) 2 | addSbtPlugin("com.github.sbt" % "sbt-dynver" % "5.1.1") 3 | -------------------------------------------------------------------------------- /play-mailer/src/main/scala/play/api/libs/mailer/MailerComponents.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import com.typesafe.config.Config 4 | 5 | trait MailerComponents { 6 | def config: Config 7 | lazy val mailerClient: SMTPMailer = new SMTPMailer(new SMTPConfigurationProvider(config).get()) 8 | } 9 | -------------------------------------------------------------------------------- /samples/compile-timeDI/conf/routes: -------------------------------------------------------------------------------- 1 | # Routes 2 | # This file defines all application routes (Higher priority routes first) 3 | # ~~~~ 4 | 5 | GET /send controllers.ApplicationScala.send() 6 | 7 | GET /configureAndSend controllers.ApplicationScala.configureAndSend() 8 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | branches: # Snapshots 6 | - main 7 | tags: ["**"] # Releases 8 | 9 | jobs: 10 | publish-artifacts: 11 | name: Publish / Artifacts 12 | uses: playframework/.github/.github/workflows/publish.yml@v4 13 | secrets: inherit 14 | -------------------------------------------------------------------------------- /project/Dependencies.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | 3 | object Dependencies { 4 | // scalaVersion needs to be kept in sync with ci 5 | val Scala213 = "2.13.18" 6 | val Scala3 = "3.3.7" 7 | val ScalaVersions = Seq(Scala213, Scala3) 8 | 9 | val PlayVersion = sys.props.getOrElse("play.version", sys.env.getOrElse("PLAY_VERSION", "3.1.0-M4")) 10 | } 11 | -------------------------------------------------------------------------------- /.github/scala-steward.conf: -------------------------------------------------------------------------------- 1 | commits.message = "${artifactName} ${nextVersion} (was ${currentVersion})" 2 | 3 | pullRequests.grouping = [ 4 | { name = "patches", "title" = "Patch updates", "filter" = [{"version" = "patch"}] } 5 | ] 6 | 7 | buildRoots = [ 8 | ".", 9 | "samples/compile-timeDI", 10 | "samples/runtimeDI", 11 | ] 12 | 13 | updates.pin = [ 14 | ] 15 | -------------------------------------------------------------------------------- /play-mailer/src/main/java/play/libs/mailer/MailerClient.java: -------------------------------------------------------------------------------- 1 | package play.libs.mailer; 2 | 3 | /** 4 | * A mailer client. 5 | */ 6 | public interface MailerClient { 7 | 8 | /** 9 | * Sends an email with the provided data. 10 | * 11 | * @param email The email to send. 12 | * @return The message id. 13 | */ 14 | String send(Email email); 15 | } 16 | -------------------------------------------------------------------------------- /play-mailer-guice/src/main/scala/play/api/libs/mailer/MailerConfigurationModule.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import com.google.inject.AbstractModule 4 | 5 | class MailerConfigurationModule extends AbstractModule { 6 | 7 | override def configure(): Unit = { 8 | bind(classOf[SMTPConfiguration]).toProvider(classOf[SMTPConfigurationProvider]) 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /play-mailer-guice/src/main/scala/play/api/libs/mailer/SMTPConfigurationModule.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import com.google.inject.AbstractModule 4 | 5 | class SMTPConfigurationModule extends AbstractModule { 6 | 7 | override def configure(): Unit = { 8 | bind(classOf[SMTPConfiguration]).toProvider(classOf[SMTPConfigurationProvider]) 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /samples/runtimeDI/conf/routes: -------------------------------------------------------------------------------- 1 | # Routes 2 | # This file defines all application routes (Higher priority routes first) 3 | # ~~~~ 4 | 5 | GET /send/java controllers.ApplicationJava.send() 6 | GET /send/scala controllers.ApplicationScala.send() 7 | 8 | GET /send/scala/customMailer controllers.ApplicationScala.sendWithCustomMailer() 9 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: http://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Unix-style newlines with a newline ending every file 7 | [*] 8 | charset = utf-8 9 | indent_style = space 10 | indent_size = 2 11 | end_of_line = lf 12 | insert_final_newline = true 13 | 14 | [*.sbt] 15 | insert_final_newline = false 16 | 17 | [*.scala] 18 | insert_final_newline = false 19 | -------------------------------------------------------------------------------- /play-mailer/src/main/scala/play/api/libs/mailer/SMTPDynamicMailer.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import jakarta.inject.{ Inject, Provider } 4 | 5 | class SMTPDynamicMailer @Inject() (smtpConfigurationProvider: Provider[SMTPConfiguration]) extends MailerClient { 6 | 7 | override def send(data: Email): String = { 8 | new SMTPMailer(smtpConfigurationProvider.get()).send(data) 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /play-mailer/src/main/scala/play/api/libs/mailer/SMTPConfigurationProvider.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import jakarta.inject.{ Inject, Provider } 4 | 5 | import com.typesafe.config.Config 6 | 7 | class SMTPConfigurationProvider @Inject() (config: Config) extends Provider[SMTPConfiguration] { 8 | override def get(): SMTPConfiguration = { 9 | SMTPConfiguration(config.getConfig("play.mailer")) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /play-mailer-guice/src/test/scala/play/api/libs/mailer/ConfigModule.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import com.typesafe.config.Config 4 | import play.api.inject.{ Binding, Module } 5 | import play.api.{ Configuration, Environment } 6 | 7 | /** 8 | * Config Module to provide a shim for Play 2.5.x 9 | */ 10 | class ConfigModule extends Module { 11 | 12 | override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[?]] = Seq( 13 | bind[Config].toInstance(configuration.underlying) 14 | ) 15 | 16 | } -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | - package-ecosystem: "github-actions" 8 | directory: "/" 9 | schedule: 10 | interval: "weekly" 11 | target-branch: "10.1.x" 12 | commit-message: 13 | prefix: "[10.1.x] " 14 | - package-ecosystem: "github-actions" 15 | directory: "/" 16 | schedule: 17 | interval: "weekly" 18 | target-branch: "9.1.x" 19 | commit-message: 20 | prefix: "[9.1.x] " 21 | -------------------------------------------------------------------------------- /play-mailer/src/main/scala/play/api/libs/mailer/Email.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | case class Email( 4 | subject: String, 5 | from: String, 6 | to: Seq[String] = Seq.empty, 7 | bodyText: Option[String] = None, 8 | bodyHtml: Option[String] = None, 9 | charset: Option[String] = None, 10 | cc: Seq[String] = Seq.empty, 11 | bcc: Seq[String] = Seq.empty, 12 | replyTo: Seq[String] = Seq.empty, 13 | bounceAddress: Option[String] = None, 14 | attachments: Seq[Attachment] = Seq.empty, 15 | headers: Seq[(String, String)] = Seq.empty) 16 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | update_release_draft: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: release-drafter/release-drafter@v6 13 | with: 14 | name: "Play Mailer $RESOLVED_VERSION" 15 | config-name: release-drafts/increasing-major-version.yml # located in .github/ in the default branch within this or the .github repo 16 | commitish: ${{ github.ref_name }} 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | -------------------------------------------------------------------------------- /samples/runtimeDI/app/controllers/CustomSMTPConfigurationProvider.scala: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import jakarta.inject.Provider 4 | 5 | import play.api.libs.mailer.SMTPConfiguration 6 | import play.api.{Configuration, Environment} 7 | import play.api.inject.Module 8 | 9 | class CustomSMTPConfigurationProvider extends Provider[SMTPConfiguration] { 10 | override def get() = new SMTPConfiguration("example.org", 1234) 11 | } 12 | 13 | class CustomMailerConfigurationModule extends Module { 14 | def bindings(environment: Environment, configuration: Configuration) = Seq( 15 | bind[SMTPConfiguration].toProvider[CustomSMTPConfigurationProvider] 16 | ) 17 | } -------------------------------------------------------------------------------- /play-mailer-guice/src/main/scala/play/api/libs/mailer/MailerModule.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import com.google.inject.AbstractModule 4 | import com.google.inject.name.Names 5 | import play.libs.mailer.{ MailerClient => JMailerClient } 6 | 7 | class MailerModule extends AbstractModule { 8 | 9 | override def configure(): Unit = { 10 | bind(classOf[MailerClient]).to(classOf[SMTPDynamicMailer]) 11 | bind(classOf[JMailerClient]).to(classOf[MailerClient]) 12 | bind(classOf[MailerClient]).annotatedWith(Names.named("mock")).to(classOf[MockMailer]) 13 | bind(classOf[JMailerClient]).annotatedWith(Names.named("mock")).to(classOf[MockMailer]) 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /samples/compile-timeDI/build.sbt: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | import PlayKeys._ 3 | 4 | name := "compile-time-DI" 5 | 6 | ThisBuild / dynverVTagPrefix := false 7 | 8 | ThisBuild / dynverSonatypeSnapshots := true 9 | 10 | scalaVersion := "2.13.18" 11 | 12 | crossScalaVersions := Seq("2.13.18", "3.3.6") 13 | 14 | libraryDependencies ++= Seq( 15 | "org.playframework" %% "play-mailer" % version.value, 16 | "org.scalatestplus.play" %% "scalatestplus-play" % "8.0.0-M2" % Test 17 | ) 18 | 19 | lazy val root = (project in file(".")).enablePlugins(PlayScala) 20 | 21 | scalacOptions ++= Seq("-Werror") // "-deprecation" gets set by Play already 22 | 23 | resolvers += Resolver.sonatypeCentralSnapshots 24 | -------------------------------------------------------------------------------- /samples/compile-timeDI/app/SimpleApplicationLoader.scala: -------------------------------------------------------------------------------- 1 | import play.api._ 2 | import play.api.ApplicationLoader.Context 3 | import router.Routes 4 | import play.api.libs.mailer._ 5 | 6 | class SimpleApplicationLoader extends ApplicationLoader { 7 | def load(context: Context) = { 8 | new ApplicationComponents(context).application 9 | } 10 | } 11 | 12 | class ApplicationComponents(context: Context) extends BuiltInComponentsFromContext(context) with MailerComponents with play.api.NoHttpFiltersComponents { 13 | lazy val applicationController = new _root_.controllers.ApplicationScala(mailerClient, environment, controllerComponents) 14 | lazy val router = new Routes(httpErrorHandler, applicationController) 15 | lazy val config = configuration.underlying 16 | } -------------------------------------------------------------------------------- /samples/compile-timeDI/conf/application.conf: -------------------------------------------------------------------------------- 1 | # This is the main configuration file for the application. 2 | # ~~~~~ 3 | 4 | # Secret key 5 | # ~~~~~ 6 | # The secret key is used to secure cryptographics functions. 7 | # If you deploy your application to several instances be sure to use the same key! 8 | play.http.secret.key="cBlQ[B0FM]DiFD logger.info(s"bodyText: $bodyText")) 16 | email.bodyHtml.foreach(bodyHtml => logger.info(s"bodyHtml: $bodyHtml")) 17 | email.to.foreach(to => logger.info(s"to: $to")) 18 | email.cc.foreach(cc => logger.info(s"cc: $cc")) 19 | email.bcc.foreach(bcc => logger.info(s"bcc: $bcc")) 20 | email.replyTo.foreach(replyTo => logger.info(s"replyTo: $replyTo")) 21 | email.bounceAddress.foreach(bounce => logger.info(s"bounceAddress: $bounce")) 22 | email.attachments.foreach(attachment => logger.info(s"attachment: $attachment")) 23 | email.headers.foreach(header => logger.info(s"header: $header")) 24 | "" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /play-mailer/src/main/scala/play/api/libs/mailer/Attachment.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import jakarta.activation.DataSource 4 | import java.io.File 5 | import java.net.URL 6 | 7 | sealed trait Attachment 8 | 9 | case class AttachmentData( 10 | name: String, 11 | data: Array[Byte], 12 | mimetype: String, 13 | description: Option[String] = None, 14 | disposition: Option[String] = None, 15 | contentId: Option[String] = None 16 | ) extends Attachment 17 | 18 | case class AttachmentFile( 19 | name: String, 20 | file: File, 21 | description: Option[String] = None, 22 | disposition: Option[String] = None, 23 | contentId: Option[String] = None 24 | ) extends Attachment 25 | 26 | case class AttachmentDataSource( 27 | name: String, 28 | dataSource: DataSource, 29 | description: Option[String] = None, 30 | disposition: Option[String] = None, 31 | contentId: Option[String] = None 32 | ) extends Attachment 33 | 34 | case class AttachmentURL( 35 | name: String, 36 | url: URL, 37 | description: Option[String] = None, 38 | disposition: Option[String] = None, 39 | contentId: Option[String] = None 40 | ) extends Attachment -------------------------------------------------------------------------------- /project/Common.scala: -------------------------------------------------------------------------------- 1 | import sbt.Keys._ 2 | import sbt._ 3 | import sbt.plugins.JvmPlugin 4 | 5 | object Common extends AutoPlugin { 6 | override def trigger = allRequirements 7 | 8 | override def requires = JvmPlugin 9 | 10 | val repoName = "play-mailer" 11 | 12 | override def globalSettings = 13 | Seq( 14 | organization := "org.playframework", 15 | organizationName := "The Play Framework Project", 16 | organizationHomepage := Some(url("https://playframework.com/")), 17 | homepage := Some(url(s"https://github.com/playframework/${repoName}")), 18 | licenses := Seq("Apache-2.0" -> url("https://www.apache.org/licenses/LICENSE-2.0.html")), 19 | 20 | scalacOptions ++= Seq("-deprecation", "-feature", "-unchecked", "-encoding", "utf8"), 21 | javacOptions ++= Seq("-encoding", "UTF-8", "-Xlint:-options"), 22 | 23 | scmInfo := Some(ScmInfo(url(s"https://github.com/playframework/${repoName}"), s"scm:git:git@github.com:playframework/${repoName}.git")), 24 | developers += Developer("playframework", 25 | "The Play Framework Contributors", 26 | "contact@playframework.com", 27 | url("https://github.com/playframework")), 28 | 29 | description := "Play mailer plugin") 30 | } 31 | -------------------------------------------------------------------------------- /samples/runtimeDI/app/controllers/ApplicationJava.java: -------------------------------------------------------------------------------- 1 | package controllers; 2 | 3 | import org.apache.commons.mail2.jakarta.EmailAttachment; 4 | import play.api.libs.mailer.MailerClient; 5 | import play.libs.mailer.Email; 6 | import play.mvc.Controller; 7 | import play.mvc.Result; 8 | import play.Environment; 9 | 10 | import jakarta.inject.Inject; 11 | import java.io.File; 12 | 13 | public class ApplicationJava extends Controller { 14 | 15 | private final Environment environment; 16 | private final MailerClient mailer; 17 | 18 | @Inject 19 | public ApplicationJava(Environment environment, MailerClient mailer) { 20 | this.environment = environment; 21 | this.mailer = mailer; 22 | } 23 | 24 | public Result send() { 25 | String cid = "1234"; 26 | final Email email = new Email() 27 | .setSubject("Simple email") 28 | .setFrom("Mister FROM ") 29 | .addTo("Miss TO ") 30 | .addAttachment("favicon.png", new File(environment.getFile("public/images/favicon.png"), cid)) 31 | .addAttachment("data.txt", "data".getBytes(), "text/plain", "Simple data", EmailAttachment.INLINE) 32 | .setBodyText("A text message") 33 | .setBodyHtml("

An html message with cid

"); 34 | String id = mailer.send(email); 35 | return ok("Email " + id + " sent!"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /samples/compile-timeDI/app/controllers/ApplicationScala.scala: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import java.io.File 4 | 5 | import play.api.Environment 6 | import org.apache.commons.mail2.jakarta.EmailAttachment 7 | import play.api.libs.mailer._ 8 | import play.api.mvc._ 9 | 10 | class ApplicationScala(mailer: MailerClient, environment: Environment, components: ControllerComponents) extends AbstractController(components) { 11 | 12 | def send = Action { 13 | val cid = "1234" 14 | val email = Email( 15 | "Simple email", 16 | "Mister FROM ", 17 | Seq("Miss TO "), 18 | attachments = Seq( 19 | AttachmentFile("favicon.png", new File(environment.classLoader.getResource("public/images/favicon.png").getPath), contentId = Some(cid)), 20 | AttachmentData("data.txt", "data".getBytes, "text/plain", Some("Simple data"), Some(EmailAttachment.INLINE)) 21 | ), 22 | bodyText = Some("A text message"), 23 | bodyHtml = Some(s"""

An html message with cid

""") 24 | ) 25 | val id = mailer.send(email) 26 | Ok(s"Email $id sent!") 27 | } 28 | 29 | def configureAndSend = Action { 30 | val mailer = new SMTPMailer(SMTPConfiguration("example.org", 1234)) 31 | val id = mailer.send(Email("Simple email", "Mister FROM ", Seq("Miss TO "))) 32 | Ok(s"Email $id sent!") 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /samples/runtimeDI/app/controllers/ApplicationScala.scala: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import java.io.File 4 | import jakarta.inject.Inject 5 | 6 | import org.apache.commons.mail2.jakarta.EmailAttachment 7 | import play.api.Environment 8 | import play.api.libs.mailer._ 9 | import play.api.mvc._ 10 | 11 | class ApplicationScala @Inject()(mailer: MailerClient, environment: Environment, val controllerComponents: ControllerComponents) extends BaseController { 12 | 13 | def send = Action { 14 | val cid = "1234" 15 | val email = Email( 16 | "Simple email", 17 | "Mister FROM ", 18 | Seq("Miss TO "), 19 | attachments = Seq( 20 | AttachmentFile("favicon.png", new File(environment.classLoader.getResource("public/images/favicon.png").getPath), contentId = Some(cid)), 21 | AttachmentData("data.txt", "data".getBytes, "text/plain", Some("Simple data"), Some(EmailAttachment.INLINE)) 22 | ), 23 | bodyText = Some("A text message"), 24 | bodyHtml = Some(s"""

An html message with cid

""") 25 | ) 26 | val id = mailer.send(email) 27 | Ok(s"Email $id sent!") 28 | } 29 | 30 | def sendWithCustomMailer = Action { 31 | val mailer = new SMTPMailer(SMTPConfiguration("example.org", 1234)) 32 | val id = mailer.send(Email("Simple email", "Mister FROM ")) 33 | Ok(s"Email $id sent!") 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /play-mailer/src/main/resources/reference.conf: -------------------------------------------------------------------------------- 1 | play { 2 | mailer { 3 | host = null 4 | port = 25 5 | ssl = no 6 | tls = no 7 | tlsRequired = no 8 | user = null 9 | password = null 10 | // Defaults to no, to take effect you also need to set the log level to "DEBUG" for the application logger 11 | debug = no 12 | // Defaults to no, will only log all the email properties instead of sending an email 13 | mock = no 14 | // Set the socket I/O timeout value in milliseconds. Default is 60 second timeout. 15 | timeout = null 16 | // Set the socket connection timeout value in milliseconds. Default is a 60 second timeout. 17 | connectiontimeout = null 18 | props { 19 | // Additional SMTP properties used by JavaMail. Can override existing configuration keys from above. 20 | // A given property will be set for both the "mail.smtp.*" and the "mail.smtps.*" prefix. 21 | // For a list of properties see: 22 | // https://javaee.github.io/javamail/docs/api/com/sun/mail/smtp/package-summary.html#properties 23 | 24 | // Example: 25 | // To set the local host name used in the SMTP HELO or EHLO command: 26 | // localhost = 127.0.0.1 27 | // Results in "mail.smtp.localhost=127.0.0.1" and "mail.smtps.localhost=127.0.0.1" in the JavaMail session. 28 | 29 | // If using SSL, we want to default to verifying that we trust the SSL certificate provided by the server. 30 | ssl.checkserveridentity = true 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /.github/workflows/build-test.yml: -------------------------------------------------------------------------------- 1 | name: Check 2 | 3 | on: 4 | pull_request: 5 | 6 | push: 7 | branches: 8 | - main # Check branch after merge 9 | 10 | concurrency: 11 | # Only run once for latest commit per ref and cancel other (previous) runs. 12 | group: ci-${{ github.ref }} 13 | cancel-in-progress: true 14 | 15 | jobs: 16 | # check-code-style: 17 | # name: Code Style 18 | # uses: playframework/.github/.github/workflows/cmd.yml@v4 19 | # with: 20 | # cmd: sbt validateCode 21 | 22 | check-binary-compatibility: 23 | name: Binary Compatibility 24 | uses: playframework/.github/.github/workflows/binary-check.yml@v4 25 | 26 | check-docs: 27 | name: Docs 28 | uses: playframework/.github/.github/workflows/cmd.yml@v4 29 | with: 30 | cmd: sbt doc 31 | 32 | tests: 33 | name: Tests 34 | needs: 35 | # - "check-code-style" 36 | - "check-binary-compatibility" 37 | - "check-docs" 38 | uses: playframework/.github/.github/workflows/cmd.yml@v4 39 | with: 40 | java: 21, 17 41 | scala: 2.13.x, 3.x 42 | cmd: | 43 | sbt ++$MATRIX_SCALA test 44 | # Test sample applications 45 | sbt ++$MATRIX_SCALA publishLocal 46 | pushd samples/compile-timeDI/ && sbt ++$MATRIX_SCALA test && popd 47 | pushd samples/runtimeDI/ && sbt ++$MATRIX_SCALA test && popd 48 | 49 | finish: 50 | name: Finish 51 | if: github.event_name == 'pull_request' 52 | needs: # Should be last 53 | - "tests" 54 | uses: playframework/.github/.github/workflows/rtm.yml@v4 55 | -------------------------------------------------------------------------------- /play-mailer/src/main/scala/play/api/libs/mailer/SMTPConfiguration.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import com.typesafe.config.{ Config, ConfigFactory } 4 | 5 | import scala.util.Try 6 | 7 | case class SMTPConfiguration( 8 | host: String, 9 | port: Int, 10 | ssl: Boolean = false, 11 | tls: Boolean = false, 12 | tlsRequired: Boolean = false, 13 | user: Option[String] = None, 14 | password: Option[String] = None, 15 | debugMode: Boolean = false, 16 | timeout: Option[Int] = None, 17 | connectionTimeout: Option[Int] = None, 18 | props: Config = ConfigFactory.empty(), 19 | mock: Boolean = false 20 | ) 21 | 22 | object SMTPConfiguration { 23 | 24 | @inline 25 | private def getOptionString(config: Config, name: String) = { 26 | Try(config.getString(name)).toOption 27 | } 28 | 29 | @inline 30 | private def getOptionInt(config: Config, name: String) = { 31 | Try(config.getInt(name)).toOption 32 | } 33 | 34 | def apply(config: Config) = new SMTPConfiguration( 35 | resolveHost(config), 36 | config.getInt("port"), 37 | config.getBoolean("ssl"), 38 | config.getBoolean("tls"), 39 | config.getBoolean("tlsRequired"), 40 | getOptionString(config, "user"), 41 | getOptionString(config, "password"), 42 | config.getBoolean("debug"), 43 | getOptionInt(config, "timeout"), 44 | getOptionInt(config, "connectiontimeout"), 45 | config.getConfig("props"), 46 | config.getBoolean("mock") 47 | ) 48 | 49 | def resolveHost(config: Config): String = { 50 | if (config.getBoolean("mock")) { 51 | // host won't be used anyway... 52 | "" 53 | } else { 54 | getOptionString(config, "host").getOrElse(throw new RuntimeException("host needs to be set in order to use this plugin (or set play.mailer.mock to true in application.conf)")) 55 | } 56 | } 57 | 58 | } 59 | 60 | -------------------------------------------------------------------------------- /play-mailer/src/main/scala/play/api/libs/mailer/MailerClient.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import play.libs.mailer.{ Email => JEmail, MailerClient => JMailerClient } 4 | 5 | import scala.jdk.CollectionConverters._ 6 | 7 | trait MailerClient extends JMailerClient { 8 | 9 | /** 10 | * Sends an email with the provided data. 11 | * 12 | * @param data data to send 13 | * @return the message id 14 | */ 15 | def send(data: Email): String 16 | 17 | override def send(data: JEmail): String = { 18 | val email = convert(data) 19 | send(email) 20 | } 21 | 22 | protected def convert(data: JEmail): Email = { 23 | val attachments = data.getAttachments.asScala.map { attachment => 24 | if (Option(attachment.getFile).isDefined) { 25 | AttachmentFile( 26 | attachment.getName, 27 | attachment.getFile, 28 | Option(attachment.getDescription), Option(attachment.getDisposition), Option(attachment.getContentId)) 29 | } else if (Option(attachment.getData).isDefined) { 30 | AttachmentData( 31 | attachment.getName, 32 | attachment.getData, 33 | attachment.getMimetype, 34 | Option(attachment.getDescription), Option(attachment.getDisposition), Option(attachment.getContentId)) 35 | } else if (Option(attachment.getDataSource).isDefined) { 36 | AttachmentDataSource( 37 | attachment.getName, 38 | attachment.getDataSource, 39 | Option(attachment.getDescription), Option(attachment.getDisposition), Option(attachment.getContentId)) 40 | } else { 41 | AttachmentURL( 42 | attachment.getName, 43 | attachment.getUrl, 44 | Option(attachment.getDescription), Option(attachment.getDisposition), Option(attachment.getContentId)) 45 | } 46 | } 47 | Email( 48 | Option(data.getSubject).getOrElse(""), 49 | Option(data.getFrom).getOrElse(""), 50 | data.getTo.asScala.toSeq, 51 | Option(data.getBodyText), 52 | Option(data.getBodyHtml), 53 | Option(data.getCharset), 54 | data.getCc.asScala.toSeq, 55 | data.getBcc.asScala.toSeq, 56 | data.getReplyTo.asScala.toSeq, 57 | Option(data.getBounceAddress), 58 | attachments.toSeq, 59 | data.getHeaders.asScala.toSeq) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /play-mailer-guice/src/test/scala/play/api/libs/mailer/MailerPluginGuiceSpec.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import com.typesafe.config.ConfigFactory 4 | import org.mockito.Mockito 5 | import org.mockito.Mockito._ 6 | import org.specs2.mutable._ 7 | import play.api.Application 8 | import play.api.inject.bind 9 | import play.api.inject.guice.GuiceApplicationBuilder 10 | import play.api.test._ 11 | 12 | class MailerPluginGuiceSpec extends Specification { 13 | 14 | "The mailer module" should { 15 | import play.libs.mailer.{ MailerClient => JMailerClient } 16 | 17 | val mockedConfigurationProvider = mock(classOf[SMTPConfigurationProvider]) 18 | when(mockedConfigurationProvider.get()).thenReturn(SMTPConfiguration("example.org", 25, mock = true)) 19 | 20 | def createApp(additionalConfiguration: Map[String, ?]): Application = { 21 | new GuiceApplicationBuilder() 22 | .configure(additionalConfiguration) 23 | .overrides(new ConfigModule) // Play 2.5.x "hack" 24 | .build() 25 | } 26 | 27 | val applicationWithMinimalMailerConfiguration = createApp(additionalConfiguration = Map("play.mailer.host" -> "example.org", "play.mailer.port" -> 25)) 28 | 29 | val applicationWithMockedConfigurationProvider = new GuiceApplicationBuilder() 30 | .overrides(new ConfigModule) // Play 2.5.x "hack" 31 | .overrides(bind[SMTPConfiguration].to(mockedConfigurationProvider)) 32 | .build() 33 | val applicationWithMoreMailerConfiguration = createApp(additionalConfiguration = Map("play.mailer.host" -> "example.org", "play.mailer.port" -> 25, "play.mailer.user" -> "johndoe", "play.mailer.password" -> "randompw")) 34 | 35 | "provide the Scala mailer client" in new WithApplication(applicationWithMinimalMailerConfiguration) { 36 | override def running() = { 37 | app.injector.instanceOf[MailerClient] must beAnInstanceOf[SMTPDynamicMailer] 38 | } 39 | } 40 | "provide the Java mailer client" in new WithApplication(applicationWithMinimalMailerConfiguration) { 41 | override def running() = { 42 | app.injector.instanceOf[JMailerClient] must beAnInstanceOf[SMTPDynamicMailer] 43 | } 44 | } 45 | "provide the Scala mocked mailer client" in new WithApplication(applicationWithMinimalMailerConfiguration) { 46 | override def running() = { 47 | app.injector.instanceOf(bind[MailerClient].qualifiedWith("mock")) must beAnInstanceOf[MockMailer] 48 | } 49 | } 50 | "provide the Java mocked mailer client" in new WithApplication(applicationWithMinimalMailerConfiguration) { 51 | override def running() = { 52 | app.injector.instanceOf(bind[JMailerClient].qualifiedWith("mock")) must beAnInstanceOf[MockMailer] 53 | } 54 | } 55 | "call the configuration each time we send an email" in new WithApplication(applicationWithMockedConfigurationProvider) { 56 | override def running() = { 57 | val mail = Email("Test Configurable Mailer", "root@example.org") 58 | app.injector.instanceOf[MailerClient].send(mail) 59 | app.injector.instanceOf[MailerClient].send(mail) 60 | Mockito.verify(mockedConfigurationProvider, times(2)).get() 61 | } 62 | } 63 | "validate the configuration" in new WithApplication(applicationWithMoreMailerConfiguration) { 64 | override def running() = { 65 | app.injector.instanceOf(bind[SMTPConfiguration]) must ===(SMTPConfiguration("example.org", 25, 66 | user = Some("johndoe"), password = Some("randompw"), props = ConfigFactory.parseString("ssl.checkserveridentity=true"))) 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /play-mailer/src/main/java/play/libs/mailer/Attachment.java: -------------------------------------------------------------------------------- 1 | package play.libs.mailer; 2 | 3 | import jakarta.activation.DataSource; 4 | import java.io.File; 5 | import java.net.URL; 6 | 7 | public class Attachment { 8 | 9 | private String name; 10 | private File file; 11 | private String description; 12 | private String disposition; 13 | private byte[] data; 14 | private DataSource dataSource; 15 | private URL url; 16 | private String mimetype; 17 | private String contentId; 18 | 19 | public Attachment(String name, File file, String description, String disposition) { 20 | this.name = name; 21 | this.file = file; 22 | this.description = description; 23 | this.disposition = disposition; 24 | } 25 | 26 | public Attachment(String name, File file) { 27 | this.name = name; 28 | this.file = file; 29 | } 30 | 31 | public Attachment(String name, File file, String contentId) { 32 | this.name = name; 33 | this.file = file; 34 | this.contentId = contentId; 35 | } 36 | 37 | public Attachment(String name, byte[] data) { 38 | this.name = name; 39 | this.data = data; 40 | } 41 | 42 | public Attachment(String name, byte[] data, String mimetype) { 43 | this.name = name; 44 | this.data = data; 45 | this.mimetype = mimetype; 46 | } 47 | 48 | public Attachment(String name, byte[] data, String mimetype, String contentId) { 49 | this.name = name; 50 | this.data = data; 51 | this.mimetype = mimetype; 52 | this.contentId = contentId; 53 | } 54 | 55 | public Attachment(String name, byte[] data, String mimetype, String description, String disposition) { 56 | this.name = name; 57 | this.data = data; 58 | this.mimetype = mimetype; 59 | this.description = description; 60 | this.disposition = disposition; 61 | } 62 | 63 | public Attachment(String name, DataSource dataSource) { 64 | this.name = name; 65 | this.dataSource = dataSource; 66 | } 67 | 68 | public Attachment(String name, DataSource dataSource, String contentId) { 69 | this.name = name; 70 | this.dataSource = dataSource; 71 | this.contentId = contentId; 72 | } 73 | 74 | public Attachment(String name, DataSource dataSource, String description, String disposition) { 75 | this.name = name; 76 | this.dataSource = dataSource; 77 | this.description = description; 78 | this.disposition = disposition; 79 | } 80 | 81 | public Attachment(String name, URL url) { 82 | this.name = name; 83 | this.url = url; 84 | } 85 | 86 | public Attachment(String name, URL url, String contentId) { 87 | this.name = name; 88 | this.url = url; 89 | this.contentId = contentId; 90 | } 91 | 92 | public Attachment(String name, URL url, String description, String disposition) { 93 | this.name = name; 94 | this.url = url; 95 | this.description = description; 96 | this.disposition = disposition; 97 | } 98 | 99 | public String getName() { 100 | return name; 101 | } 102 | 103 | public void setName(String name) { 104 | this.name = name; 105 | } 106 | 107 | public File getFile() { 108 | return file; 109 | } 110 | 111 | public void setFile(File file) { 112 | this.file = file; 113 | } 114 | 115 | public String getDescription() { 116 | return description; 117 | } 118 | 119 | public void setDescription(String description) { 120 | this.description = description; 121 | } 122 | 123 | public String getDisposition() { 124 | return disposition; 125 | } 126 | 127 | public void setDisposition(String disposition) { 128 | this.disposition = disposition; 129 | } 130 | 131 | public byte[] getData() { 132 | return data; 133 | } 134 | 135 | public void setData(byte[] data) { 136 | this.data = data; 137 | } 138 | 139 | public DataSource getDataSource() { 140 | return dataSource; 141 | } 142 | 143 | public void setDataSource(DataSource dataSource) { 144 | this.dataSource = dataSource; 145 | } 146 | 147 | public URL getUrl() { 148 | return url; 149 | } 150 | 151 | public void setUrl(URL url) { 152 | this.url = url; 153 | } 154 | 155 | public String getMimetype() { 156 | return mimetype; 157 | } 158 | 159 | public void setMimetype(String mimetype) { 160 | this.mimetype = mimetype; 161 | } 162 | 163 | public String getContentId() { 164 | return contentId; 165 | } 166 | 167 | public void setContentId(String contentId) { 168 | this.contentId = contentId; 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /play-mailer/src/main/java/play/libs/mailer/Email.java: -------------------------------------------------------------------------------- 1 | package play.libs.mailer; 2 | 3 | import jakarta.activation.DataSource; 4 | import java.io.File; 5 | import java.net.URL; 6 | import java.util.ArrayList; 7 | import java.util.HashMap; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | public class Email { 12 | 13 | private String subject; 14 | private String from; 15 | private String bodyText; 16 | private String bodyHtml; 17 | private List to = new ArrayList(); 18 | private List cc = new ArrayList(); 19 | private List bcc = new ArrayList(); 20 | private List replyTo = new ArrayList(); 21 | private String bounceAddress; 22 | private List attachments = new ArrayList(); 23 | private String charset; 24 | private Map headers = new HashMap(); 25 | 26 | public String getSubject() { 27 | return subject; 28 | } 29 | 30 | public Email setSubject(String subject) { 31 | this.subject = subject; 32 | return this; 33 | } 34 | 35 | public String getFrom() { 36 | return from; 37 | } 38 | 39 | public Email setFrom(String from) { 40 | this.from = from; 41 | return this; 42 | } 43 | 44 | public String getBodyText() { 45 | return bodyText; 46 | } 47 | 48 | public Email setBodyText(String bodyText) { 49 | this.bodyText = bodyText; 50 | return this; 51 | } 52 | 53 | public String getBodyHtml() { 54 | return bodyHtml; 55 | } 56 | 57 | public Email setBodyHtml(String bodyHtml) { 58 | this.bodyHtml = bodyHtml; 59 | return this; 60 | } 61 | 62 | public Email addTo(String address) { 63 | this.to.add(address); 64 | return this; 65 | } 66 | 67 | public List getTo() { 68 | return to; 69 | } 70 | 71 | public Email setTo(List to) { 72 | this.to = to; 73 | return this; 74 | } 75 | 76 | public Email addCc(String address) { 77 | this.cc.add(address); 78 | return this; 79 | } 80 | 81 | public List getCc() { 82 | return cc; 83 | } 84 | 85 | public Email setCc(List cc) { 86 | this.cc = cc; 87 | return this; 88 | } 89 | 90 | public Email addBcc(String address) { 91 | this.bcc.add(address); 92 | return this; 93 | } 94 | 95 | public List getBcc() { 96 | return bcc; 97 | } 98 | 99 | public Email setBcc(List bcc) { 100 | this.bcc = bcc; 101 | return this; 102 | } 103 | 104 | public List getReplyTo() { 105 | return replyTo; 106 | } 107 | 108 | public Email addReplyTo(String replyTo) { 109 | this.replyTo.add(replyTo); 110 | return this; 111 | } 112 | 113 | public Email setReplyTo(List replyTo) { 114 | this.replyTo = replyTo; 115 | return this; 116 | } 117 | 118 | public String getBounceAddress() { 119 | return bounceAddress; 120 | } 121 | 122 | public Email setBounceAddress(String bounceAddress) { 123 | this.bounceAddress = bounceAddress; 124 | return this; 125 | } 126 | 127 | public Email addAttachment(String name, File file) { 128 | this.attachments.add(new Attachment(name, file)); 129 | return this; 130 | } 131 | 132 | public Email addAttachment(String name, File file, String contentId) { 133 | this.attachments.add(new Attachment(name, file, contentId)); 134 | return this; 135 | } 136 | 137 | public Email addAttachment(String name, File file, String description, String disposition) { 138 | this.attachments.add(new Attachment(name, file, description, disposition)); 139 | return this; 140 | } 141 | 142 | public Email addAttachment(String name, byte[] data, String mimeType) { 143 | this.attachments.add(new Attachment(name, data, mimeType)); 144 | return this; 145 | } 146 | 147 | public Email addAttachment(String name, byte[] data, String mimeType, String contentId) { 148 | this.attachments.add(new Attachment(name, data, mimeType, contentId)); 149 | return this; 150 | } 151 | 152 | public Email addAttachment(String name, byte[] data, String mimeType, String description, String disposition) { 153 | this.attachments.add(new Attachment(name, data, mimeType, description, disposition)); 154 | return this; 155 | } 156 | 157 | public Email addAttachment(String name, DataSource dataSource) { 158 | this.attachments.add(new Attachment(name, dataSource)); 159 | return this; 160 | } 161 | 162 | public Email addAttachment(String name, DataSource dataSource, String contentId) { 163 | this.attachments.add(new Attachment(name, dataSource, contentId)); 164 | return this; 165 | } 166 | 167 | public Email addAttachment(String name, DataSource dataSource, String description, String disposition) { 168 | this.attachments.add(new Attachment(name, dataSource, description, disposition)); 169 | return this; 170 | } 171 | 172 | public Email addAttachment(String name, URL url) { 173 | this.attachments.add(new Attachment(name, url)); 174 | return this; 175 | } 176 | 177 | public Email addAttachment(String name, URL url, String contentId) { 178 | this.attachments.add(new Attachment(name, url, contentId)); 179 | return this; 180 | } 181 | 182 | public Email addAttachment(String name, URL url, String description, String disposition) { 183 | this.attachments.add(new Attachment(name, url, description, disposition)); 184 | return this; 185 | } 186 | 187 | public List getAttachments() { 188 | return attachments; 189 | } 190 | 191 | public Email setAttachments(List attachments) { 192 | this.attachments = attachments; 193 | return this; 194 | } 195 | 196 | public String getCharset() { 197 | return charset; 198 | } 199 | 200 | public Email setCharset(String charset) { 201 | this.charset = charset; 202 | return this; 203 | } 204 | 205 | public Email addHeader(String key, String value) { 206 | this.headers.put(key, value); 207 | return this; 208 | } 209 | 210 | public Map getHeaders() { 211 | return headers; 212 | } 213 | 214 | public Email setHeaders(Map headers) { 215 | this.headers = headers; 216 | return this; 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /play-mailer/src/main/scala/play/api/libs/mailer/CommonsMailer.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import jakarta.activation.URLDataSource 4 | import jakarta.mail.Session 5 | import jakarta.mail.internet.InternetAddress 6 | import org.apache.commons.mail2.jakarta.{ DefaultAuthenticator, EmailAttachment, HtmlEmail, MultiPartEmail } 7 | import org.slf4j.LoggerFactory 8 | 9 | import java.io.{ FilterOutputStream, PrintStream } 10 | import java.time 11 | import scala.jdk.CollectionConverters._ 12 | import scala.util.control.NonFatal 13 | 14 | abstract class CommonsMailer(conf: SMTPConfiguration) extends MailerClient { 15 | 16 | protected val logger = LoggerFactory.getLogger("play.mailer") 17 | 18 | def send(email: MultiPartEmail): String 19 | 20 | def createMultiPartEmail(): MultiPartEmail 21 | 22 | def createHtmlEmail(): HtmlEmail 23 | 24 | override def send(data: Email): String = send(createEmail(data)) 25 | 26 | def createEmail(data: Email): MultiPartEmail = { 27 | val email = createEmail(data.bodyText, data.bodyHtml, data.charset.getOrElse("utf-8")) 28 | email.setSubject(data.subject) 29 | setAddress(data.from) { (address, name) => email.setFrom(address, name) } 30 | data.replyTo.foreach(setAddress(_) { (address, name) => email.addReplyTo(address, name) }) 31 | data.bounceAddress.foreach(email.setBounceAddress) 32 | data.to.foreach(setAddress(_) { (address, name) => email.addTo(address, name) }) 33 | data.cc.foreach(setAddress(_) { (address, name) => email.addCc(address, name) }) 34 | data.bcc.foreach(setAddress(_) { (address, name) => email.addBcc(address, name) }) 35 | data.headers.foreach { 36 | header => email.addHeader(header._1, header._2) 37 | } 38 | conf.timeout.foreach(timeout => email.setSocketTimeout(java.time.Duration.ofMillis(timeout))) 39 | conf.connectionTimeout.foreach(timeout => email.setSocketConnectionTimeout(time.Duration.ofMillis(timeout))) 40 | data.attachments.foreach { 41 | case attachmentData: AttachmentData => 42 | handleAttachmentData(email, attachmentData) 43 | case attachmentFile: AttachmentFile => 44 | handleAttachmentFile(email, attachmentFile) 45 | case attachmentDataSource: AttachmentDataSource => 46 | handleAttachmentDataSource(email, attachmentDataSource) 47 | case attachmentURL: AttachmentURL => 48 | handleAttachmentURL(email, attachmentURL) 49 | } 50 | email.setHostName(conf.host) 51 | email.setSmtpPort(conf.port) 52 | email.setSSLOnConnect(conf.ssl) 53 | if (conf.ssl) { 54 | email.setSslSmtpPort(conf.port.toString) 55 | } 56 | email.setStartTLSEnabled(conf.tls || conf.tlsRequired) 57 | email.setStartTLSRequired(conf.tlsRequired) 58 | val authenticator = for (u <- conf.user; p <- conf.password) yield new DefaultAuthenticator(u, p) 59 | authenticator.foreach(email.setAuthenticator(_)) 60 | 61 | // After the email was set up we can now also manipulate the session properties directly 62 | val mailProperties = email.getMailSession.getProperties() 63 | conf.props.entrySet().asScala.foreach(prop => { 64 | mailProperties.setProperty("mail.smtp." + prop.getKey(), prop.getValue().unwrapped().toString) 65 | mailProperties.setProperty("mail.smtps." + prop.getKey(), prop.getValue().unwrapped().toString) 66 | }) 67 | email.setMailSession(Session.getInstance(mailProperties, authenticator.orNull)) 68 | 69 | if (conf.debugMode && logger.isDebugEnabled) { 70 | email.setDebug(conf.debugMode) 71 | email.getMailSession.setDebugOut(new PrintStream(new FilterOutputStream(null) { 72 | override def write(b: Array[Byte]): Unit = { 73 | logger.debug(new String(b)) 74 | } 75 | 76 | override def write(b: Array[Byte], off: Int, len: Int): Unit = { 77 | logger.debug(new String(b, off, len)) 78 | } 79 | 80 | override def write(b: Int): Unit = { 81 | this.write(new Array(b): Array[Byte]) 82 | } 83 | })) 84 | } 85 | email 86 | } 87 | 88 | /** 89 | * Creates an appropriate email object based on the content type. 90 | */ 91 | private def createEmail(bodyText: Option[String], bodyHtml: Option[String], charset: String): MultiPartEmail = { 92 | (bodyHtml.filter(_.trim.nonEmpty), bodyText.filter(_.trim.nonEmpty)) match { 93 | case (Some(htmlMsg), bodyTextOpt) => 94 | val htmlEmail = createHtmlEmail() 95 | htmlEmail.setCharset(charset) 96 | htmlEmail.setHtmlMsg(htmlMsg) 97 | bodyTextOpt.foreach { bodyText => 98 | htmlEmail.setTextMsg(bodyText) 99 | } 100 | htmlEmail 101 | case (None, Some(msg)) => 102 | val multiPartEmail = createMultiPartEmail() 103 | multiPartEmail.setCharset(charset) 104 | multiPartEmail.setMsg(msg) 105 | multiPartEmail 106 | case _ => 107 | createMultiPartEmail() 108 | } 109 | } 110 | 111 | /** 112 | * Extracts an email address from the given string and passes to the enclosed method. 113 | */ 114 | private def setAddress(emailAddress: String)(setter: (String, String) => Unit) = { 115 | if (emailAddress != null) { 116 | try { 117 | val iAddress = new InternetAddress(emailAddress) 118 | val address = iAddress.getAddress 119 | val name = iAddress.getPersonal 120 | setter(address, name) 121 | } catch { 122 | case NonFatal(_) => setter(emailAddress, null) 123 | } 124 | } 125 | } 126 | 127 | private def handleAttachmentData(email: MultiPartEmail, attachmentData: AttachmentData): Unit = { 128 | val description = attachmentData.description.getOrElse(attachmentData.name) 129 | val disposition = attachmentData.disposition.getOrElse(EmailAttachment.ATTACHMENT) 130 | val dataSource = new jakarta.mail.util.ByteArrayDataSource(attachmentData.data, attachmentData.mimetype) 131 | attachmentData.contentId match { 132 | case Some(cid) => 133 | email match { 134 | case htmlEmail: HtmlEmail => htmlEmail.embed(dataSource, attachmentData.name, cid) 135 | case _ => if (conf.debugMode && logger.isDebugEnabled) { 136 | logger.debug("You need to set an HTML body to embed images with cid") 137 | } 138 | } 139 | case None => email.attach(dataSource, attachmentData.name, description, disposition) 140 | } 141 | } 142 | 143 | private def handleAttachmentFile(email: MultiPartEmail, attachmentFile: AttachmentFile): Unit = { 144 | val description = attachmentFile.description.getOrElse(attachmentFile.name) 145 | val disposition = attachmentFile.disposition.getOrElse(EmailAttachment.ATTACHMENT) 146 | val emailAttachment = new EmailAttachment() 147 | emailAttachment.setName(attachmentFile.name) 148 | emailAttachment.setPath(attachmentFile.file.getPath) 149 | emailAttachment.setDescription(description) 150 | emailAttachment.setDisposition(disposition) 151 | attachmentFile.contentId match { 152 | case Some(cid) => 153 | email match { 154 | case htmlEmail: HtmlEmail => htmlEmail.embed(attachmentFile.file, cid) 155 | case _ => if (conf.debugMode && logger.isDebugEnabled) { 156 | logger.debug("You need to set an HTML body to embed images with cid") 157 | } 158 | } 159 | case None => email.attach(emailAttachment) 160 | } 161 | } 162 | 163 | private def handleAttachmentDataSource(email: MultiPartEmail, attachmentDataSource: AttachmentDataSource): Unit = { 164 | val description = attachmentDataSource.description.getOrElse(attachmentDataSource.name) 165 | val disposition = attachmentDataSource.disposition.getOrElse(EmailAttachment.ATTACHMENT) 166 | val dataSource = attachmentDataSource.dataSource 167 | attachmentDataSource.contentId match { 168 | case Some(cid) => 169 | email match { 170 | case htmlEmail: HtmlEmail => htmlEmail.embed(dataSource, attachmentDataSource.name, cid) 171 | case _ => if (conf.debugMode && logger.isDebugEnabled) { 172 | logger.debug("You need to set an HTML body to embed images with cid") 173 | } 174 | } 175 | case None => email.attach(dataSource, attachmentDataSource.name, description, disposition) 176 | } 177 | } 178 | 179 | private def handleAttachmentURL(email: MultiPartEmail, attachmentURL: AttachmentURL): Unit = { 180 | val description = attachmentURL.description.getOrElse(attachmentURL.name) 181 | val disposition = attachmentURL.disposition.getOrElse(EmailAttachment.ATTACHMENT) 182 | val url = attachmentURL.url 183 | attachmentURL.contentId match { 184 | case Some(cid) => 185 | email match { 186 | case htmlEmail: HtmlEmail => htmlEmail.embed(new URLDataSource(url), attachmentURL.name, cid) 187 | case _ => if (conf.debugMode && logger.isDebugEnabled) { 188 | logger.debug("You need to set an HTML body to embed images with cid") 189 | } 190 | } 191 | case None => email.attach(url, attachmentURL.name, description, disposition) 192 | } 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Play Mailer 2 | 3 | [![Twitter Follow](https://img.shields.io/twitter/follow/playframework?label=follow&style=flat&logo=twitter&color=brightgreen)](https://twitter.com/playframework) 4 | [![Discord](https://img.shields.io/discord/931647755942776882?logo=discord&logoColor=white)](https://discord.gg/g5s2vtZ4Fa) 5 | [![GitHub Discussions](https://img.shields.io/github/discussions/playframework/playframework?&logo=github&color=brightgreen)](https://github.com/playframework/playframework/discussions) 6 | [![StackOverflow](https://img.shields.io/static/v1?label=stackoverflow&logo=stackoverflow&logoColor=fe7a16&color=brightgreen&message=playframework)](https://stackoverflow.com/tags/playframework) 7 | [![YouTube](https://img.shields.io/youtube/channel/views/UCRp6QDm5SDjbIuisUpxV9cg?label=watch&logo=youtube&style=flat&color=brightgreen&logoColor=ff0000)](https://www.youtube.com/channel/UCRp6QDm5SDjbIuisUpxV9cg) 8 | [![Twitch Status](https://img.shields.io/twitch/status/playframework?logo=twitch&logoColor=white&color=brightgreen&label=live%20stream)](https://www.twitch.tv/playframework) 9 | [![OpenCollective](https://img.shields.io/opencollective/all/playframework?label=financial%20contributors&logo=open-collective)](https://opencollective.com/playframework) 10 | 11 | [![Build Status](https://github.com/playframework/play-mailer/actions/workflows/build-test.yml/badge.svg)](https://github.com/playframework/play-mailer/actions/workflows/build-test.yml) 12 | [![Maven](https://img.shields.io/maven-central/v/org.playframework/play-mailer_2.13.svg?logo=apache-maven)](https://mvnrepository.com/artifact/org.playframework/play-mailer_2.13) 13 | [![Repository size](https://img.shields.io/github/repo-size/playframework/play-mailer.svg?logo=git)](https://github.com/playframework/play-mailer) 14 | [![Scala Steward badge](https://img.shields.io/badge/Scala_Steward-helping-blue.svg?style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAQCAMAAAARSr4IAAAAVFBMVEUAAACHjojlOy5NWlrKzcYRKjGFjIbp293YycuLa3pYY2LSqql4f3pCUFTgSjNodYRmcXUsPD/NTTbjRS+2jomhgnzNc223cGvZS0HaSD0XLjbaSjElhIr+AAAAAXRSTlMAQObYZgAAAHlJREFUCNdNyosOwyAIhWHAQS1Vt7a77/3fcxxdmv0xwmckutAR1nkm4ggbyEcg/wWmlGLDAA3oL50xi6fk5ffZ3E2E3QfZDCcCN2YtbEWZt+Drc6u6rlqv7Uk0LdKqqr5rk2UCRXOk0vmQKGfc94nOJyQjouF9H/wCc9gECEYfONoAAAAASUVORK5CYII=)](https://scala-steward.org) 15 | [![Mergify Status](https://img.shields.io/endpoint.svg?url=https://api.mergify.com/v1/badges/playframework/play-mailer&style=flat)](https://mergify.com) 16 | 17 | Play Mailer is a powerful Scala Mailing library. It provides a simple configurable mailer. 18 | 19 | ## Getting Started 20 | 21 | To get started you add `play-mailer` and `play-mailer-guice` as a dependency in SBT: 22 | 23 | ```scala 24 | libraryDependencies += "org.playframework" %% "play-mailer" % -version- 25 | libraryDependencies += "org.playframework" %% "play-mailer-guice" % -version- 26 | 27 | // Until version 9.x: 28 | libraryDependencies += "com.typesafe.play" %% "play-mailer" % -version- 29 | libraryDependencies += "com.typesafe.play" %% "play-mailer-guice" % -version- 30 | ``` 31 | 32 | ## Versioning 33 | 34 | The Play Mailer plugin supports several different versions of Play. 35 | 36 | | Plugin version | Play version | 37 | |------------------|-----------------| 38 | | 10.x | 3.0.x | 39 | | 9.x | 2.9.x | 40 | | 8.x | 2.8.x | 41 | | 7.x | 2.7.x | 42 | 43 | See [GitHub releases](https://github.com/playframework/play-mailer/releases) for the latest versions. 44 | 45 | After that you need to configure the mailer inside your `application.conf`: 46 | 47 | ```HOCON 48 | play.mailer { 49 | host = "example.com" // (mandatory) 50 | port = 25 // (defaults to 25) 51 | ssl = no // (defaults to no) 52 | tls = no // (defaults to no) 53 | tlsRequired = no // (defaults to no) 54 | user = null // (optional) 55 | password = null // (optional) 56 | debug = no // (defaults to no, to take effect you also need to set the log level to "DEBUG" for the "play.mailer" logger) 57 | timeout = null // (defaults to 60s in milliseconds) 58 | connectiontimeout = null // (defaults to 60s in milliseconds) 59 | mock = no // (defaults to no, will only log all the email properties instead of sending an email) 60 | props { 61 | // Additional SMTP properties used by JavaMail. Can override existing configuration keys from above. 62 | // A given property will be set for both the "mail.smtp.*" and the "mail.smtps.*" prefix. 63 | // For a list of properties see: 64 | // https://javaee.github.io/javamail/docs/api/com/sun/mail/smtp/package-summary.html#properties 65 | 66 | // Example: 67 | // To set the local host name used in the SMTP HELO or EHLO command: 68 | // localhost = 127.0.0.1 69 | // Results in "mail.smtp.localhost=127.0.0.1" and "mail.smtps.localhost=127.0.0.1" in the JavaMail session. 70 | } 71 | } 72 | ``` 73 | 74 | ## Usage 75 | 76 | ### Scala 77 | 78 | #### Runtime Injection 79 | 80 | Use the `@Inject` annotation on the constructor, service of your component or controller: 81 | 82 | ```scala 83 | import play.api.libs.mailer._ 84 | import java.io.File 85 | import org.apache.commons.mail2.jakarta.EmailAttachment 86 | import jakarta.inject.Inject 87 | 88 | class MailerService @Inject() (mailerClient: MailerClient) { 89 | 90 | def sendEmail = { 91 | val cid = "1234" 92 | val email = Email( 93 | "Simple email", 94 | "Mister FROM ", 95 | Seq("Miss TO "), 96 | // adds attachment 97 | attachments = Seq( 98 | AttachmentFile("attachment.pdf", new File("/some/path/attachment.pdf")), 99 | // adds inline attachment from byte array 100 | AttachmentData("data.txt", "data".getBytes, "text/plain", Some("Simple data"), Some(EmailAttachment.INLINE)), 101 | // adds cid attachment 102 | AttachmentFile("image.jpg", new File("/some/path/image.jpg"), contentId = Some(cid)) 103 | ), 104 | // sends text, HTML or both... 105 | bodyText = Some("A text message"), 106 | bodyHtml = Some(s"""

An html message with cid

""") 107 | ) 108 | mailerClient.send(email) 109 | } 110 | 111 | } 112 | ``` 113 | 114 | > Configuration will be retrieved each time mailerClient.send(email) is called. 115 | > This means that mailer client will always be up to date if you have a dynamic configuration. 116 | 117 | #### Compile Time Injection 118 | 119 | If you use Compile time Injection you can remove `libraryDependencies += "org.playframework" %% "play-mailer-guice" % -version-` from your `build.sbt`. 120 | 121 | Create the MailerService without the `@Inject` annotation: 122 | 123 | ```scala 124 | import play.api.libs.mailer._ 125 | 126 | class MyComponent(mailerClient: MailerClient) { 127 | 128 | def sendEmail = { 129 | val email = Email("Simple email", "Mister FROM ", Seq("Miss TO "), bodyText = Some("A text message")) 130 | mailerClient.send(email) 131 | } 132 | } 133 | ``` 134 | 135 | Then you need to register the `MailerComponents` trait in your main Components file: 136 | 137 | ```scala 138 | import play.api._ 139 | import play.api.ApplicationLoader.Context 140 | import router.Routes 141 | import play.api.libs.mailer._ 142 | 143 | class MyApplicationLoader extends ApplicationLoader { 144 | def load(context: Context) = { 145 | new ApplicationComponents(context).application 146 | } 147 | } 148 | 149 | class ApplicationComponents(context: Context) extends BuiltInComponentsFromContext(context) with MailerComponents { 150 | lazy val myComponent = new MyComponent(mailerClient) 151 | // create your controllers here ... 152 | lazy val router = new Routes(...) // inject your controllers here 153 | lazy val config = configuration.underlying 154 | } 155 | ``` 156 | 157 | #### Dynamic Configuration 158 | 159 | By default the Mailer Plugin will automatically configure the injected instance with the `application.conf`. 160 | 161 | If you want to configure the injected instances from another source, you will need to override the default provider: 162 | 163 | Create a new file named `CustomSMTPConfigurationProvider.scala`: 164 | 165 | ```scala 166 | class CustomSMTPConfigurationProvider extends Provider[SMTPConfiguration] { 167 | override def get() = { 168 | // Custom configuration 169 | new SMTPConfiguration("example.org", 1234) 170 | } 171 | } 172 | 173 | class CustomMailerConfigurationModule extends Module { 174 | def bindings(environment: Environment, configuration: Configuration) = Seq( 175 | bind[SMTPConfiguration].toProvider[CustomSMTPConfigurationProvider] 176 | ) 177 | } 178 | ``` 179 | 180 | And override the default provider inside you `application.conf`: 181 | 182 | ```HOCON 183 | play.modules { 184 | # Disable the default provider 185 | disabled += "play.api.libs.mailer.SMTPConfigurationModule" 186 | # Enable the custom provider (see above) 187 | enabled += "controllers.CustomMailerConfigurationModule" 188 | } 189 | ``` 190 | 191 | > The get() method of your CustomSMTPConfigurationProvider will be called multiple times. 192 | > As a consequence, we recommend that code inside the get() method should be fast. 193 | 194 | 195 | #### Multiple SMTPMailer instances 196 | 197 | You can also use the SMTPMailer constructor to create new instances with custom configuration: 198 | 199 | ```scala 200 | val email = Email("Simple email", "Mister FROM ") 201 | new SMTPMailer(SMTPConfiguration("example.org", 1234)).send(email) 202 | new SMTPMailer(SMTPConfiguration("playframework.com", 5678)).send(email) 203 | ``` 204 | 205 | ### Java 206 | 207 | For Java you can just create a simple MailerService and Inject the MailerClient into it: 208 | 209 | ```java 210 | import play.libs.mailer.Email; 211 | import play.libs.mailer.MailerClient; 212 | import jakarta.inject.Inject; 213 | import java.io.File; 214 | import org.apache.commons.mail.EmailAttachment; 215 | 216 | public class MailerService { 217 | @Inject MailerClient mailerClient; 218 | 219 | public void sendEmail() { 220 | String cid = "1234"; 221 | Email email = new Email() 222 | .setSubject("Simple email") 223 | .setFrom("Mister FROM ") 224 | .addTo("Miss TO ") 225 | // adds attachment 226 | .addAttachment("attachment.pdf", new File("/some/path/attachment.pdf")) 227 | // adds inline attachment from byte array 228 | .addAttachment("data.txt", "data".getBytes(), "text/plain", "Simple data", EmailAttachment.INLINE) 229 | // adds cid attachment 230 | .addAttachment("image.jpg", new File("/some/path/image.jpg"), cid) 231 | // sends text, HTML or both... 232 | .setBodyText("A text message") 233 | .setBodyHtml("

An html message with cid

"); 234 | mailerClient.send(email); 235 | } 236 | } 237 | ``` 238 | 239 | ## Releasing a new version 240 | 241 | See https://github.com/playframework/.github/blob/main/RELEASING.md 242 | 243 | ## License 244 | 245 | This software is licensed under the Apache 2 license, quoted below. 246 | 247 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. 248 | 249 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 250 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /play-mailer/src/test/scala/play/api/libs/mailer/MailerPluginSpec.scala: -------------------------------------------------------------------------------- 1 | package play.api.libs.mailer 2 | 3 | import com.typesafe.config.{ Config, ConfigFactory } 4 | import jakarta.mail.Part 5 | import org.apache.commons.mail2.core.EmailConstants 6 | import org.apache.commons.mail2.jakarta.{ HtmlEmail, MultiPartEmail } 7 | import org.specs2.mutable._ 8 | 9 | import java.io.File 10 | 11 | class MailerPluginSpec extends Specification { 12 | 13 | object SimpleMailerClient extends MailerClient { 14 | override def send(data: Email): String = "" 15 | override def convert(data: play.libs.mailer.Email) = super.convert(data) 16 | } 17 | class MockMultiPartEmail extends MultiPartEmail { 18 | override def getPrimaryBodyPart = super.getPrimaryBodyPart 19 | override def getContainer = super.getContainer 20 | } 21 | class MockHtmlEmail extends HtmlEmail { 22 | override def getPrimaryBodyPart = super.getPrimaryBodyPart 23 | override def getContainer = super.getContainer 24 | } 25 | object MockCommonsMailer extends MockCommonsMailerWithTimeouts(None, None) 26 | 27 | class MockCommonsMailerWithProps(props: Config = ConfigFactory.empty()) extends MockCommonsMailerWithTimeouts(None, None, props) 28 | 29 | class MockCommonsMailerWithTimeouts(smtpTimeout: Option[Int], smtpConnectionTimeout: Option[Int], props: Config = ConfigFactory.empty()) 30 | extends CommonsMailer(SMTPConfiguration("example.org", 1234, ssl = true, tls = false, tlsRequired = false, Some("user"), Some("password"), debugMode = false, smtpTimeout, smtpConnectionTimeout, props, mock = false)) { 31 | override def send(email: MultiPartEmail) = "" 32 | override def createMultiPartEmail(): MultiPartEmail = new MockMultiPartEmail 33 | override def createHtmlEmail(): HtmlEmail = new MockHtmlEmail 34 | } 35 | 36 | "The CommonsMailer" should { 37 | "configure SMTP" in { 38 | val mailer = MockCommonsMailer 39 | val email = mailer.createEmail(Email( 40 | subject = "Subject", 41 | from = "John Doe " 42 | )) 43 | email.getSmtpPort mustEqual "1234" 44 | email.getSslSmtpPort mustEqual "1234" 45 | email.getMailSession.getProperty("mail.smtp.auth") mustEqual "true" 46 | email.getMailSession.getProperty("mail.smtp.host") mustEqual "example.org" 47 | email.getMailSession.getProperty("mail.smtp.starttls.enable") mustEqual "false" 48 | email.getMailSession.getProperty("mail.smtp.starttls.required") mustEqual "false" 49 | email.getMailSession.getProperty("mail.smtp.localhost") must beNull 50 | email.getMailSession.getProperty("mail.debug") mustEqual "false" 51 | } 52 | 53 | "configure the SMTP timeouts if configured" in { 54 | val mailer = new MockCommonsMailerWithTimeouts(Some(10), Some(99)) 55 | val email = mailer.createEmail(Email( 56 | subject = "Subject", 57 | from = "John Doe " 58 | )) 59 | email.getSocketTimeout mustEqual 10 60 | email.getSocketConnectionTimeout mustEqual 99 61 | } 62 | 63 | "leave default SMTP timeouts if they are not configured" in { 64 | val mailer = new MockCommonsMailerWithTimeouts(None, None) 65 | val email = mailer.createEmail(Email( 66 | subject = "Subject", 67 | from = "John Doe " 68 | )) 69 | email.getSocketTimeout mustEqual EmailConstants.SOCKET_TIMEOUT.toMillis.toInt 70 | email.getSocketConnectionTimeout mustEqual EmailConstants.SOCKET_TIMEOUT.toMillis.toInt 71 | } 72 | 73 | "configure the SMTP local host if configured" in { 74 | val mailer = new MockCommonsMailerWithProps(ConfigFactory.parseString("localhost=127.0.0.1")) 75 | val email = mailer.createEmail(Email( 76 | subject = "Subject", 77 | from = "John Doe " 78 | )) 79 | email.getMailSession.getProperty("mail.smtp.localhost") mustEqual "127.0.0.1" 80 | email.getMailSession.getProperty("mail.smtps.localhost") mustEqual "127.0.0.1" 81 | } 82 | 83 | "create an empty email" in { 84 | val mailer = MockCommonsMailer 85 | val messageId = mailer.send(Email( 86 | subject = "Subject", 87 | from = "John Doe ", 88 | to = Seq("Guillaume Grossetie ") 89 | )) 90 | messageId mustEqual "" 91 | } 92 | 93 | "create a simple email" in { 94 | val mailer = MockCommonsMailer 95 | val email = mailer.createEmail(Email( 96 | subject = "Subject", 97 | from = "John Doe ", 98 | to = Seq("Guillaume Grossetie "), 99 | replyTo = Seq("Aviv Shafir "), 100 | bodyText = Some("A text message"), 101 | bodyHtml = Some("

An html message

") 102 | )) 103 | simpleEmailMust(email) 104 | email must beAnInstanceOf[HtmlEmail] 105 | email must beAnInstanceOf[MockHtmlEmail] 106 | email.asInstanceOf[MockHtmlEmail].getText mustEqual "A text message" 107 | email.asInstanceOf[MockHtmlEmail].getHtml mustEqual "

An html message

" 108 | } 109 | 110 | "create a simple email with attachment" in { 111 | val mailer = MockCommonsMailer 112 | val email = mailer.createEmail(Email( 113 | subject = "Subject", 114 | from = "John Doe ", 115 | to = Seq("Guillaume Grossetie "), 116 | replyTo = Seq("Aviv Shafir "), 117 | bodyText = Some("A text message"), 118 | attachments = Seq(AttachmentFile("play icon", getPlayIcon)) 119 | )) 120 | simpleEmailMust(email) 121 | email must beAnInstanceOf[MultiPartEmail] 122 | email must beAnInstanceOf[MockMultiPartEmail] 123 | email.asInstanceOf[MockMultiPartEmail].getContainer.getCount mustEqual 2 124 | val textPart = email.asInstanceOf[MockMultiPartEmail].getContainer.getBodyPart(0) 125 | textPart.getContentType mustEqual "text/plain" 126 | textPart.getContent mustEqual "A text message" 127 | email.asInstanceOf[MockMultiPartEmail].getPrimaryBodyPart.getContent mustEqual "A text message" 128 | val attachmentPart = email.asInstanceOf[MockMultiPartEmail].getContainer.getBodyPart(1) 129 | attachmentPart.getFileName mustEqual "play icon" 130 | attachmentPart.getDescription mustEqual "play icon" 131 | attachmentPart.getDisposition mustEqual Part.ATTACHMENT 132 | } 133 | 134 | "create a simple email with cid" in { 135 | val mailer = MockCommonsMailer 136 | val cid = "1234" 137 | val email = mailer.createEmail(Email( 138 | subject = "Subject", 139 | from = "John Doe ", 140 | to = Seq("Guillaume Grossetie "), 141 | replyTo = Seq("Aviv Shafir "), 142 | bodyHtml = Some(s"""

An html message with cid

"""), 143 | attachments = Seq(AttachmentFile("play icon", getPlayIcon, contentId = Some(cid))) 144 | )) 145 | simpleEmailMust(email) 146 | email must beAnInstanceOf[HtmlEmail] 147 | email must beAnInstanceOf[MockHtmlEmail] 148 | email.asInstanceOf[MockHtmlEmail].getHtml mustEqual "

An html message with cid

" 149 | email.asInstanceOf[MockHtmlEmail].getContainer.getContentType startsWith "multipart/mixed;" 150 | } 151 | 152 | "create a simple email with inline attachment and description" in { 153 | val mailer = MockCommonsMailer 154 | val email = mailer.createEmail(Email( 155 | subject = "Subject", 156 | from = "John Doe ", 157 | to = Seq("Guillaume Grossetie "), 158 | replyTo = Seq("Aviv Shafir "), 159 | bodyText = Some("A text message"), 160 | attachments = Seq(AttachmentFile("play icon", getPlayIcon, Some("A beautiful icon"), Some(Part.INLINE))) 161 | )) 162 | simpleEmailMust(email) 163 | email must beAnInstanceOf[MultiPartEmail] 164 | email must beAnInstanceOf[MockMultiPartEmail] 165 | email.asInstanceOf[MockMultiPartEmail].getContainer.getCount mustEqual 2 166 | val textPart = email.asInstanceOf[MockMultiPartEmail].getContainer.getBodyPart(0) 167 | textPart.getContentType mustEqual "text/plain" 168 | textPart.getContent mustEqual "A text message" 169 | email.asInstanceOf[MockMultiPartEmail].getPrimaryBodyPart.getContent mustEqual "A text message" 170 | val attachmentPart = email.asInstanceOf[MockMultiPartEmail].getContainer.getBodyPart(1) 171 | attachmentPart.getFileName mustEqual "play icon" 172 | attachmentPart.getDescription mustEqual "A beautiful icon" 173 | attachmentPart.getDisposition mustEqual Part.INLINE 174 | } 175 | 176 | "set address with name" in { 177 | val mailer = MockCommonsMailer 178 | val email = mailer.createEmail(Email( 179 | subject = "Subject", 180 | from = "John Doe ", 181 | to = Seq("Guillaume Grossetie "), 182 | replyTo = Seq("Aviv Shafir "), 183 | cc = Seq("Guillaume Grossetie "), 184 | bcc = Seq("Guillaume Grossetie ") 185 | )) 186 | email.getFromAddress.getAddress mustEqual "john.doe@example.com" 187 | email.getFromAddress.getPersonal mustEqual "John Doe" 188 | email.getToAddresses.get(0).getAddress mustEqual "ggrossetie@localhost.com" 189 | email.getToAddresses.get(0).getPersonal mustEqual "Guillaume Grossetie" 190 | email.getCcAddresses.get(0).getAddress mustEqual "ggrossetie@localhost.com" 191 | email.getCcAddresses.get(0).getPersonal mustEqual "Guillaume Grossetie" 192 | email.getBccAddresses.get(0).getAddress mustEqual "ggrossetie@localhost.com" 193 | email.getBccAddresses.get(0).getPersonal mustEqual "Guillaume Grossetie" 194 | email.getReplyToAddresses.get(0).getPersonal mustEqual "Aviv Shafir" 195 | email.getReplyToAddresses.get(0).getAddress mustEqual "avivshafir@github.com" 196 | } 197 | 198 | "set address without name" in { 199 | val mailer = MockCommonsMailer 200 | val email = mailer.createEmail(Email( 201 | subject = "Subject", 202 | from = "john.doe@example.com", 203 | to = Seq(""), 204 | cc = Seq("ggrossetie@localhost.com"), 205 | replyTo = Seq("avivshafir@github.com"), 206 | bcc = Seq("ggrossetie@localhost.com") 207 | )) 208 | email.getFromAddress.getAddress mustEqual "john.doe@example.com" 209 | email.getFromAddress.getPersonal must beNull 210 | email.getToAddresses.get(0).getAddress mustEqual "ggrossetie@localhost.com" 211 | email.getToAddresses.get(0).getPersonal must beNull 212 | email.getCcAddresses.get(0).getAddress mustEqual "ggrossetie@localhost.com" 213 | email.getCcAddresses.get(0).getPersonal must beNull 214 | email.getBccAddresses.get(0).getAddress mustEqual "ggrossetie@localhost.com" 215 | email.getBccAddresses.get(0).getPersonal must beNull 216 | email.getReplyToAddresses.get(0).getAddress mustEqual "avivshafir@github.com" 217 | email.getReplyToAddresses.get(0).getPersonal must beNull 218 | } 219 | } 220 | 221 | "The MailerAPI" should { 222 | "convert email from Java to Scala" in { 223 | val data = new play.libs.mailer.Email() 224 | data.setSubject("Subject") 225 | data.setFrom("John Doe ") 226 | data.addTo("Guillaume Grossetie ") 227 | data.addCc("Daniel Spasojevic ") 228 | data.addBcc("Sparkbitpl ") 229 | data.addReplyTo("Aviv Shafir ") 230 | data.setBodyText("A text message") 231 | data.setBodyHtml("

An html message

") 232 | data.setCharset("UTF-16") 233 | data.addHeader("key", "value") 234 | data.addAttachment("play icon", getPlayIcon, "A beautiful icon", Part.ATTACHMENT) 235 | data.addAttachment("data.txt", "data".getBytes, "text/plain", "Simple data", Part.INLINE) 236 | data.addAttachment("image.jpg", getPlayIcon, "1234") 237 | 238 | val convert = SimpleMailerClient.convert(data) 239 | convert.subject mustEqual "Subject" 240 | convert.from mustEqual "John Doe " 241 | convert.to.size mustEqual 1 242 | convert.to.head mustEqual "Guillaume Grossetie " 243 | convert.cc.size mustEqual 1 244 | convert.cc.head mustEqual "Daniel Spasojevic " 245 | convert.bcc.size mustEqual 1 246 | convert.bcc.head mustEqual "Sparkbitpl " 247 | convert.replyTo.size mustEqual 1 248 | convert.replyTo.head mustEqual "Aviv Shafir " 249 | convert.bodyText mustEqual Some("A text message") 250 | convert.bodyHtml mustEqual Some("

An html message

") 251 | convert.charset mustEqual Some("UTF-16") 252 | convert.headers.size mustEqual 1 253 | convert.headers.head mustEqual ("key" -> "value") 254 | convert.attachments.size mustEqual 3 255 | convert.attachments.head must beAnInstanceOf[AttachmentFile] 256 | convert.attachments.head.asInstanceOf[AttachmentFile].name mustEqual "play icon" 257 | convert.attachments.head.asInstanceOf[AttachmentFile].file mustEqual getPlayIcon 258 | convert.attachments.head.asInstanceOf[AttachmentFile].description mustEqual Some("A beautiful icon") 259 | convert.attachments.head.asInstanceOf[AttachmentFile].disposition mustEqual Some(Part.ATTACHMENT) 260 | convert.attachments(1) must beAnInstanceOf[AttachmentData] 261 | convert.attachments(1).asInstanceOf[AttachmentData].name mustEqual "data.txt" 262 | convert.attachments(1).asInstanceOf[AttachmentData].data mustEqual "data".getBytes 263 | convert.attachments(1).asInstanceOf[AttachmentData].description mustEqual Some("Simple data") 264 | convert.attachments(1).asInstanceOf[AttachmentData].disposition mustEqual Some(Part.INLINE) 265 | convert.attachments(2) must beAnInstanceOf[AttachmentFile] 266 | convert.attachments(2).asInstanceOf[AttachmentFile].name mustEqual "image.jpg" 267 | convert.attachments(2).asInstanceOf[AttachmentFile].file mustEqual getPlayIcon 268 | convert.attachments(2).asInstanceOf[AttachmentFile].contentId mustEqual Some("1234") 269 | } 270 | } 271 | 272 | def simpleEmailMust(email: MultiPartEmail): Unit = { 273 | email.getSubject mustEqual "Subject" 274 | email.getFromAddress.getPersonal mustEqual "John Doe" 275 | email.getFromAddress.getAddress mustEqual "john.doe@example.com" 276 | email.getToAddresses must have size 1 277 | email.getToAddresses.get(0).getPersonal mustEqual "Guillaume Grossetie" 278 | email.getToAddresses.get(0).getAddress mustEqual "ggrossetie@localhost.com" 279 | email.getReplyToAddresses.get(0).getAddress mustEqual "avivshafir@github.com" 280 | } 281 | 282 | def getPlayIcon: File = { 283 | new File(this.getClass.getResource("/play_icon_full_color.png").toURI) 284 | } 285 | } 286 | --------------------------------------------------------------------------------