Sending Mail #
Diego comes with basic utility classes for sending mail. To enable the mail plugin, mark it as a dependency on your main application class:
@Uses(MailPlugin.class)
class MyApp extends WebMvcConfiguration { ... }
Using the Mailer
class
#
You can use the Mailer
class to send emails directly from a request handler. Here is an example of a sending a password reset message:
First we create our password-reset.ftl
template in the {diego.resourceBase}/templates/mail
directory:
Dear ${name},
Please use the following link to reset your password:
${baseUrl}/auth/reset-password?token=${token}
Regards,
Administrator
Next, we create and populate an instance of diego.mail.Email
:
import diego.mail.Mailer;
import com.google.inject.Inject;
import static diego.mail.Email.renderText;
public class UserAuthController extends Controller {
private final Mailer mailer;
@Inject
public UserAuthController(Mailer mailer) {
this.mailer = mailer;
}
@POST("/password-reset")
public Result passwordReset(@Param String email) {
User user = findUserByEmail(email);
String token = generateToken();
/* renderText() creates a plain text email. renderHtml() creates an HTML email */
Content textContent = renderText("password-reset", Map.of("name", user.name, "token", token));
Email passwordResetEmail = new Email()
.to(user.emil)
.subject("Reset your password")
.body(textContent);
mailer.send(passwordResetEmail);
}
}
If you’re using Groovy, you can use the version of Mailer#send()
that accepts a closure which delegates to an Email instance:
@POST("/password-reset")
Result passwordReset(@Param String email) {
User user = getUser()
String token = generateToken()
mailer.send({
to user.email
subject "Reset your password"
body renderText("password-reset", [name: user.name, token: token])
})
})
Configuration #
These are the available configuration settings for the Mail extension:
# Use the Mock SMTP mailer which prints mail output to the console
diego.mail.mock = false
# Set a default "from" address (Required)
diego.mail.defaultSender = <you@example.com>
# SMTP host
diego.mail.host = <host@mail-provider.com>
# SMTP port
diego.mail.port = 587
# SMTP connection timeout
diego.mail.timeout = 5s
# Use authentication
diego.mail.auth = false
# Use TLS encryption
diego.mail.tls = true
# Used for SMTP authentication
diego.mail.username = <your_username@example.com>
diego.mail.password = <your_password>
Notes:
- You must provide a
defaultSender
address. It can be as simple asno-reply@yourapp.com
.
Next: Dependency injection