• Stars
    star
    250
  • Rank 162,397 (Top 4 %)
  • Language
    Scala
  • License
    Apache License 2.0
  • Created about 10 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Play mailer plugin

Play Mailer

Twitter Follow Discord GitHub Discussions StackOverflow YouTube Twitch Status OpenCollective

Build Status Maven Repository size Scala Steward badge Mergify Status

Play Mailer is a powerful Scala Mailing library. It provides a simple configurable mailer.

Getting Started

To get started you add play-mailer and play-mailer-guice as a dependency in SBT:

libraryDependencies += "com.typesafe.play" %% "play-mailer" % -version-
libraryDependencies += "com.typesafe.play" %% "play-mailer-guice" % -version-

Versioning

The Play Mailer plugin supports several different versions of Play.

Plugin version Play version
8.x 2.8.x
7.x 2.7.x

See GitHub releases for the latest versions.

After that you need to configure the mailer inside your application.conf:

play.mailer {
  host = "example.com" // (mandatory)
  port = 25 // (defaults to 25)
  ssl = no // (defaults to no)
  tls = no // (defaults to no)
  tlsRequired = no // (defaults to no)
  user = null // (optional)
  password = null // (optional)
  debug = no // (defaults to no, to take effect you also need to set the log level to "DEBUG" for the "play.mailer" logger)
  timeout = null // (defaults to 60s in milliseconds)
  connectiontimeout = null // (defaults to 60s in milliseconds)
  mock = no // (defaults to no, will only log all the email properties instead of sending an email)
  props {
    // Additional SMTP properties used by JavaMail. Can override existing configuration keys from above.
    // A given property will be set for both the "mail.smtp.*" and the "mail.smtps.*" prefix.
    // For a list of properties see:
    // https://javaee.github.io/javamail/docs/api/com/sun/mail/smtp/package-summary.html#properties

    // Example:
    // To set the local host name used in the SMTP HELO or EHLO command:
    // localhost = 127.0.0.1
    // Results in "mail.smtp.localhost=127.0.0.1" and "mail.smtps.localhost=127.0.0.1" in the JavaMail session.
  }
}

Usage

Scala

Runtime Injection

Use the @Inject annotation on the constructor, service of your component or controller:

import play.api.libs.mailer._
import java.io.File
import org.apache.commons.mail.EmailAttachment
import javax.inject.Inject

class MailerService @Inject() (mailerClient: MailerClient) {

  def sendEmail = {
    val cid = "1234"
    val email = Email(
      "Simple email",
      "Mister FROM <[email protected]>",
      Seq("Miss TO <[email protected]>"),
      // adds attachment
      attachments = Seq(
        AttachmentFile("attachment.pdf", new File("/some/path/attachment.pdf")),
        // adds inline attachment from byte array
        AttachmentData("data.txt", "data".getBytes, "text/plain", Some("Simple data"), Some(EmailAttachment.INLINE)),
        // adds cid attachment
        AttachmentFile("image.jpg", new File("/some/path/image.jpg"), contentId = Some(cid))
      ),
      // sends text, HTML or both...
      bodyText = Some("A text message"),
      bodyHtml = Some(s"""<html><body><p>An <b>html</b> message with cid <img src="cid:$cid"></p></body></html>""")
    )
    mailerClient.send(email)
  }

}

Configuration will be retrieved each time mailerClient.send(email) is called. This means that mailer client will always be up to date if you have a dynamic configuration.

Compile Time Injection

If you use Compile time Injection you can remove libraryDependencies += "com.typesafe.play" %% "play-mailer-guice" % -version- from your build.sbt.

Create the MailerService without the @Inject annotation:

import play.api.libs.mailer._

class MyComponent(mailerClient: MailerClient) {

  def sendEmail = {
     val email = Email("Simple email", "Mister FROM <[email protected]>", Seq("Miss TO <[email protected]>"), bodyText = Some("A text message"))
     mailerClient.send(email)
  }
}

Then you need to register the MailerComponents trait in your main Components file:

import play.api._
import play.api.ApplicationLoader.Context
import router.Routes
import play.api.libs.mailer._

class MyApplicationLoader extends ApplicationLoader {
  def load(context: Context) = {
    new ApplicationComponents(context).application
  }
}

class ApplicationComponents(context: Context) extends BuiltInComponentsFromContext(context) with MailerComponents {
  lazy val myComponent = new MyComponent(mailerClient)
  // create your controllers here ...
  lazy val router = new Routes(...) // inject your controllers here
  lazy val config = configuration.underlying
}

Dynamic Configuration

By default the Mailer Plugin will automatically configure the injected instance with the application.conf.

If you want to configure the injected instances from another source, you will need to override the default provider:

Create a new file named CustomSMTPConfigurationProvider.scala:

class CustomSMTPConfigurationProvider extends Provider[SMTPConfiguration] {
  override def get() = {
    // Custom configuration
    new SMTPConfiguration("typesafe.org", 1234)
  }
}

class CustomMailerConfigurationModule extends Module {
  def bindings(environment: Environment, configuration: Configuration) = Seq(
    bind[SMTPConfiguration].toProvider[CustomSMTPConfigurationProvider]
  )
}

And override the default provider inside you application.conf:

play.modules {
    # Disable the default provider
    disabled += "play.api.libs.mailer.SMTPConfigurationModule"
    # Enable the custom provider (see above)
    enabled += "controllers.CustomMailerConfigurationModule"
}

The get() method of your CustomSMTPConfigurationProvider will be called multiple times. As a consequence, we recommend that code inside the get() method should be fast.

Multiple SMTPMailer instances

You can also use the SMTPMailer constructor to create new instances with custom configuration:

val email = Email("Simple email", "Mister FROM <[email protected]>")
new SMTPMailer(SMTPConfiguration("typesafe.org", 1234)).send(email)
new SMTPMailer(SMTPConfiguration("playframework.com", 5678)).send(email)

Java

For Java you can just create a simple MailerService and Inject the MailerClient into it:

import play.libs.mailer.Email;
import play.libs.mailer.MailerClient;
import javax.inject.Inject;
import java.io.File;
import org.apache.commons.mail.EmailAttachment;

public class MailerService {
  @Inject MailerClient mailerClient;

  public void sendEmail() {
    String cid = "1234";
    Email email = new Email()
      .setSubject("Simple email")
      .setFrom("Mister FROM <[email protected]>")
      .addTo("Miss TO <[email protected]>")
      // adds attachment
      .addAttachment("attachment.pdf", new File("/some/path/attachment.pdf"))
      // adds inline attachment from byte array
      .addAttachment("data.txt", "data".getBytes(), "text/plain", "Simple data", EmailAttachment.INLINE)
      // adds cid attachment
      .addAttachment("image.jpg", new File("/some/path/image.jpg"), cid)
      // sends text, HTML or both...
      .setBodyText("A text message")
      .setBodyHtml("<html><body><p>An <b>html</b> message with cid <img src=\"cid:" + cid + "\"></p></body></html>");
    mailerClient.send(email);
  }
}

Releasing a new version

See https://github.com/playframework/.github/blob/main/RELEASING.md

License

This software is licensed under the Apache 2 license, quoted below.

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.

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.

More Repositories

1

playframework

The Community Maintained High Velocity Web Framework For Java and Scala.
Scala
12,527
star
2

play1

Play framework
Java
1,580
star
3

play-slick

Slick Plugin for Play
Scala
803
star
4

twirl

Twirl is Play's default template engine
Scala
542
star
5

play-samples

Play Framework Sample Projects
JavaScript
525
star
6

play-plugins

CachePlugin
JavaScript
444
star
7

play-json

The Play JSON library
Scala
359
star
8

anorm

The Anorm database library
Scala
237
star
9

play-scala-starter-example

Play Scala Starter Template (ideal for new users!)
CSS
236
star
10

play-ws

Standalone Play WS, an async HTTP client with fluent API
Scala
222
star
11

play-scala-rest-api-example

Example Play Scala application showing REST API
Scala
213
star
12

play-scala-react-seed

❄️ Scala Play + React seed project with full-fledged build process
Shell
203
star
13

play-scala-websocket-example

Example Play Scala application showing WebSocket use with Akka actors
Scala
195
star
14

play-java-starter-example

Play starter project in Java (ideal for new users!)
CSS
161
star
15

play-scala-isolated-slick-example

Example Play Slick Project
Scala
154
star
16

netty-reactive-streams

Reactive streams implementation for Netty.
Java
113
star
17

scalatestplus-play

ScalaTest + Play
Scala
110
star
18

play-ebean

Play Ebean module
Java
103
star
19

play-socket.io

Play socket.io support
Scala
93
star
20

play-java-websocket-example

Example Play Java application showing Websocket usage with Akka actors
Java
88
star
21

play-scala-angular-seed

🍀 Scala Play 2.7.x + Angular 8 with Angular CLI seed project with full-fledged build process
TypeScript
84
star
22

prune

Performance testing tool for Play Framework
Scala
81
star
23

play-silhouette

Silhouette is an authentication library for Play Framework applications that supports several authentication methods, including OAuth1, OAuth2, OpenID, CAS, 2FA, TOTP, Credentials, Basic Authentication or custom authentication schemes.
Scala
78
star
24

play-scala-seed.g8

Play Scala Seed Template: run "sbt new playframework/play-scala-seed.g8"
Scala
74
star
25

play-scala-slick-example

Example Play Scala project with Slick
Scala
59
star
26

modules.playframework.org

Java
57
star
27

play-scala-secure-session-example

An example Play application showing encrypted session management
Scala
56
star
28

play-java-ebean-example

Example Play application showing Java with Ebean
Java
53
star
29

play-java-angular-seed

🍁 Java Play 2.7.x + Angular 8 with Angular CLI seed project with full-fledged build process
TypeScript
53
star
30

play-scala-macwire-di-example

Sample project for compile-time DI with Macwire
Scala
47
star
31

play-java-rest-api-example

REST API using Play in Java
Java
45
star
32

play-scala-chatroom-example

Play chatroom with Scala API
Scala
44
star
33

play-scala-tls-example

A Play application using HTTPS and WS with optional client authentication
Scala
44
star
34

play-java-react-seed

🌀 Java Play 2.7.x + React seed project with full-fledged build process
Shell
44
star
35

playframework.com

The Play Framework website
Scala
43
star
36

play-scala-streaming-example

Example Play application showing Comet and Server Sent Events in Scala
Scala
43
star
37

play-scala-anorm-example

Example Play Database Application using Anorm
Scala
41
star
38

play-java-dagger2-example

Play Application using Dagger 2 for Compile Time DI
Java
40
star
39

play-scala-compile-di-example

Example Play Project using compile time dependency injection and Play WS with ScalaTest
Scala
38
star
40

play-soap

Play SOAP support
Scala
35
star
41

play-grpc

Play + Pekko gRPC
Scala
35
star
42

play-java-jpa-example

Example Play Java project with JPA database integration
Java
35
star
43

play-java-chatroom-example

Example Chatroom with Java API
Java
34
star
44

play-scala-fileupload-example

An example Play application showing custom multiform fileupload in Scala
Scala
29
star
45

play-java-seed.g8

Play Java Seed template: use "sbt new playframework/play-java-seed.g8"
Java
23
star
46

play-doc

Play documentation rendering support
Scala
21
star
47

play-webgoat

A vulnerable Play application for attackers.
Scala
18
star
48

play-iteratees

Scala
18
star
49

play-scala-forms-example

Example Play Project showing form processing
Scala
16
star
50

play-glassfish

Play container for Glassfish
Java
16
star
51

cachecontrol

Minimal HTTP cache management library in Scala
Scala
14
star
52

play-file-watch

This is the Play File Watch library
Java
14
star
53

play-enhancer

Java
14
star
54

play-scala-log4j2-example

An example Play project using Log4J 2 as the logging engine
Scala
14
star
55

play-java-fileupload-example

An example Play application showing custom multiform fileupload in Java
Java
14
star
56

interplay

Common sbt plugins for Play modules
Scala
12
star
57

play-generated-docs

Generated docs for publishing to the Play website.
11
star
58

play-scala-hello-world-tutorial

Hello World Tutorial for Play in Scala
HTML
10
star
59

play-spring-loader

An application loader for Play that uses Spring as the dependency injection framework
Scala
10
star
60

play-java-streaming-example

Example Play application showing Comet and Server Sent Events in Java
JavaScript
9
star
61

play-scala-grpc-example

Example for akka-grpc services embedded in Play framework applications (Scala)
CSS
9
star
62

play-meta

Team management & cross-repository effort tracking
Shell
8
star
63

play-java-hello-world-tutorial

Play Hello World tutorial in Java
HTML
6
star
64

omnidoc

Play aggregated documentation
Scala
6
star
65

.github

Scala
5
star
66

play-java-forms-example

Play Project Template showing Java Forms Processing
Java
5
star
67

play-java-compile-di-example

Example Play application using compile time DI with Java API
Java
4
star
68

play-java-grpc-example

Example for akka-grpc services embedded in Play framework applications (Java)
CSS
4
star
69

templatecontrol

Template Control for Play templates and other examples
Scala
4
star
70

play-quota-scala-example

An example of User Quotas using Play and Scala
Scala
3
star
71

modules.playframework.com

The Play Framework module index
Scala
3
star
72

play-native-loader

Loading native libraries in Play Framework
Java
3
star
73

play-quota-java-example

An example application using Play Quota with Java API
Java
3
star
74

playframework.github.io

2
star
75

jnotify

Scala
2
star
76

play-courses

Courses on play using the course management tools
CSS
1
star
77

play-antora-ui

CSS
1
star