14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PlayFramework 2.4:ダミーサーバーにメール送信

Last updated at Posted at 2015-07-02

#準備

##変更する設定ファイル
###build.sbt

libraryDependenciesに追記

libraryDependencies ++= Seq(
 javaJdbc,
 cache,
 javaWs,
 "com.typesafe.play" %% "play-mailer" % "3.0.1"
)

conf/application.conf

以下を追記
ローカルのダミーサーバーに送る

play.mailer {   host=localhost   port=25 }

Model

models.api.Mail.java
package models.api;

import play.libs.mailer.Email;
import play.libs.mailer.MailerClient;

public class Mail {

  public void sendEmail(MailerClient mailerClient) {
    Email email = new Email();
    email.setSubject("Simple email 漢字");
    email.setFrom("sender@play-testmail.com");
    email.addTo("receiver@play-testmail.com");
    email.setBodyText("A text message\r\n日本語");
    mailerClient.send(email);
  }
}

Controller

controllers.Application.java
package controllers;

import javax.inject.Inject;

import models.api.Mail;
import play.*;
import play.libs.mailer.MailerClient;
import play.mvc.*;
import views.html.*;

public class Application extends Controller {

	@Inject MailerClient mailerClient;

	public Result mail() {
		Mail mailer = new Mail();
		mailer.sendEmail(mailerClient);
		return ok(send.render());
	}

}

適当なViewを作り、routesでマッピングしてアクセス

http://localhost:9000/mail

mailserver.jpg

mail.jpg

##余談

最初はplay-mailerのgitページにあるJavaのソースをコピペして作ったが、
MailerClientにインスタンスが入っていないらしく、ぬるぽが出て動かなかった

そこでDIコンテナについて勉強したところ、どうやら自分でnewした先では@Injectが効かないらしい
コントローラーにやって貰ってとりあえずうまく行ったが、あまりこのコードには自信がない

14
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?