Mailerリファレンスガイド
このガイドは、 Mailer 入門ガイドの続編です。このガイドでは、Quarkus Mailerの設定と使用方法について詳しく説明しています。
Mailerエクステンション
Mailerを使用するには、 quarkus-mailer
エクステンションを追加する必要があります。
次のコマンドでプロジェクトにエクステンションを追加することができます。
> ./mvnw quarkus:add-extensions -Dextensions="mailer"
あるいは、以下の依存関係をプロジェクトに追加するだけです。
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-mailer</artifactId>
</dependency>
Mailerへのアクセス
次のようにしてアプリケーションにmailerを注入することができます。
@Inject
Mailer mailer;
@Inject
ReactiveMailer reactiveMailer;
APIは2つあります。
-
io.quarkus.mailer.Mailer
は、命令型(ブロッキング、同期)APIを提供しています。 -
io.quarkus.mailer.reactive.ReactiveMailer
は、リアクティブ(ノンブロッキング、非同期)なAPIを提供しています。
この2つのAPIは機能的には同等です。実際、 Mailer の実装は、 ReactiveMailer の実装の上に構築されています。
|
非推奨
|
簡単なメールを送信するには、次のようにします。
// Imperative API:
mailer.send(Mail.withText("to@acme.org", "A simple email from quarkus", "This is my body."));
// Reactive API:
Uni<Void> stage = reactiveMailer.send(Mail.withText("to@acme.org", "A reactive email from quarkus", "This is my body."));
例えば、 Mailer
を HTTP のエンドポイントで使用する場合は次のようになります。
@GET
@Path("/imperative")
public void sendASimpleEmail() {
mailer.send(Mail.withText("to@acme.org", "A simple email from quarkus", "This is my body"));
}
@GET
@Path("/reactive")
public Uni<Void> sendASimpleEmailAsync() {
return reactiveMailer.send(
Mail.withText("to@acme.org", "A reactive email from quarkus", "This is my body"));
}
メールオブジェクトの作成
Mailerでは、 io.quarkus.mailer.Mail
のオブジェクトを送信することができます。新しい io.quarkus.mailer.Mail
インスタンスは、コンストラクタや Mail.withText
および Mail.withHtml
といったヘルパーメソッドから作成できます。 Mail
インスタンスでは、受信者(to、cc、bcc)の追加、件名、ヘッダー、送信者(from)アドレスの設定などができます。
また、1回の呼び出しで複数の Mail
オブジェクトを送信することもできます。
mailer.send(mail1, mail2, mail3);
添付ファイルの送信
添付ファイルを送信するには、 io.quarkus.mailer.Mail
インスタンスの addAttachment
メソッドを使用するだけです。
@GET
@Path("/attachment")
public void sendEmailWithAttachment() {
mailer.send(Mail.withText("clement.escoffier@gmail.com", "An email from quarkus with attachment",
"This is my body")
.addAttachment("my-file-1.txt",
"content of my file".getBytes(), "text/plain")
.addAttachment("my-file-2.txt",
new File("my-file.txt"), "text/plain")
);
}
添付ファイルは、(スニペットで示したように)生のバイトまたはファイルから作成できます。ファイルは、アプリケーションのワーキングディレクトリを基準に解決されることに注意してください。
添付ファイルがインライン化されたHTMLメールの送信
HTMLメールを送信する際に、インラインで添付ファイルを追加することができます。例えば、メールに画像を添付して送信すると、その画像がメールの内容に表示されます。画像ファイルを META-INF/resources
フォルダーに置く場合は、ファイルのフルパスを指定する必要があります。 例えば 、 META-INF/resources/quarkus-logo.png
です。そうしないと、Quarkusはルートディレクトリでファイルを探します。
@GET
@Path("/html")
public void sendingHTML() {
String body = "<strong>Hello!</strong>" + "\n" +
"<p>Here is an image for you: <img src=\"cid:my-image@quarkus.io\"/></p>" +
"<p>Regards</p>";
mailer.send(Mail.withHtml("to@acme.org", "An email in HTML", body)
.addInlineAttachment("quarkus-logo.png",
new File("quarkus-logo.png"),
"image/png", "<my-image@quarkus.io>"));
}
content-id のフォーマットと参照先に注意してください。仕様では、インラインの添付ファイルを作成する際、content-idは次のような構造になっていなければなりません: <id@domain>
。 <>
の間で content-id をラップしない場合は、自動的にラップされます。添付ファイルを src
属性などで参照したい場合は、 cid:id@domain
を使用します( <
と >
なし)。
Quteテンプレートに基づくメッセージボディ
It’s possible to inject a mail template, where the message body is created automatically using Qute templates.
@Path("")
public class MailingResource {
@CheckedTemplate
static class Templates {
public static native MailTemplateInstance hello(String name); (1)
}
@GET
@Path("/mail")
public Uni<Void> send() {
// the template looks like: Hello {name}! (2)
return Templates.hello("John")
.to("to@acme.org") (3)
.subject("Hello from Qute template")
.send(); (4)
}
}
1 | 規約では、テンプレートの位置を特定するために、囲んでいるクラス名とメソッド名が使用されます。この例では、 src/main/resources/templates/MailingResource/hello.html と src/main/resources/templates/MailingResource/hello.txt のテンプレートを使ってメッセージ本文を作成します。 |
2 | テンプレートで使用するデータを設定します。 |
3 | メールテンプレートのインスタンスを作成し、受信者を設定します。 |
4 | MailTemplate.send() がレンダリングのトリガーとなり、終了すると Mailer のインスタンスを介してメールを送信します。 |
挿入されたメールテンプレートはビルド時に検証されます。 src/main/resources/templates に一致するテンプレートがない場合、ビルドは失敗します。
|
タイプセーフのテンプレートを使わずに行うこともできます。
@Inject
@Location("hello")
MailTemplate hello; (1)
@GET
@Path("/mail")
public Uni<Void> send() {
return hello.to("to@acme.org") (2)
.subject("Hello from Qute template")
.data("name", "John") (3)
.send() (4)
}
1 | @Location 修飾子が指定されていない場合は、フィールド名を使ってテンプレートを探します。それ以外の場合は、指定された場所としてテンプレートを検索します。この例では、 src/main/resources/templates/hello.html と src/main/resources/templates/hello.txt のテンプレートを使ってメッセージ・ボディを作成します。 |
2 | メールテンプレートのインスタンスを作成し、受信者を設定します。 |
3 | テンプレートで使用するデータを設定します。 |
4 | MailTemplate.send() がレンダリングのトリガーとなり、終了すると Mailer のインスタンスを介してメールを送信します。 |
実行モデル
リアクティブ型Mailerはノンブロッキングで、結果はI/Oスレッドで提供されます。このトピックの詳細については、 Quarkus Reactive Architectureのドキュメントを参照してください。
非リアクティブ型Mailerは、メッセージがSMTPサーバーに送信されるまでブロックします。これは、メッセージが配信されたことを意味するのではなく、配信を担当するSMTPサーバに正常に送信されたことを意味することに注意してください。
メール送信のテスト
開発やテスト中に電子メールを送信するのは非常に不便なため、 quarkus.mailer.mock
ブーリアン構成を true
に設定することで、実際に電子メールを送信せず、代わりに標準出力に印刷し、代わりに MockMailbox
ビーンに収集することができます。これは、Quarkusを DEV
または TEST
モードで実行している場合のデフォルトです。
そして、例えばRESTエンドポイントでメールが送信されたことを検証するテストを書くことができます。
@QuarkusTest
class MailTest {
private static final String TO = "foo@quarkus.io";
@Inject
MockMailbox mailbox;
@BeforeEach
void init() {
mailbox.clear();
}
@Test
void testTextMail() throws MessagingException, IOException {
// call a REST endpoint that sends email
given()
.when()
.get("/send-email")
.then()
.statusCode(202)
.body(is("OK"));
// verify that it was sent
List<Mail> sent = mailbox.getMessagesSentTo(TO);
assertThat(sent).hasSize(1);
Mail actual = sent.get(0);
assertThat(actual.getText()).contains("Wake up!");
assertThat(actual.getSubject()).isEqualTo("Alarm!");
assertThat(mailbox.getTotalMessagesSent()).isEqualTo(6);
}
}
基盤となるVert.xメールクライアントの使用
Quarkus Mailerは Vert.x Mail Clientの上に実装されており、非同期かつノンブロッキングでメールを送信することができます。メールの送信方法を細かく制御する必要がある場合(例えば、メッセージIDを取得する必要がある場合)、基礎となるクライアントを注入し、直接使用することができます。
@Inject MailClient client;
3つのAPIフレーバーが公開されています。
-
Mutinyクライアント (
io.vertx.mutiny.ext.mail.MailClient
) -
ベアクライアント (
io.vertx.ext.mail.MailClient
)
Check the Using Vert.x guide for further details about these different APIs and how to select the most suitable for you.
取得された MailClient
は、上記で紹介した設定キーを使って設定されます。独自のインスタンスを作成して、独自の設定を渡すこともできます。
Gmail特有の設定
GmailのSMTPサーバーを使用する場合は、まず、 Google Account > Security > App passwords
で専用のパスワードを作成するか、 https://myaccount.google.com/apppasswords にアクセスしてください。
App passwords ページにアクセスするには、 https://myaccount.google.com/security 、2段階認証をオンにする必要があります。 |
完了したら、 application.properties
に以下のプロパティーを追加して、Quarkusアプリケーションを設定することができます。
TLSの場合:
quarkus.mailer.auth-methods=DIGEST-MD5 CRAM-SHA256 CRAM-SHA1 CRAM-MD5 PLAIN LOGIN
quarkus.mailer.from=YOUREMAIL@gmail.com
quarkus.mailer.host=smtp.gmail.com
quarkus.mailer.port=587
quarkus.mailer.start-tls=REQUIRED
quarkus.mailer.username=YOUREMAIL@gmail.com
quarkus.mailer.password=YOURGENERATEDAPPLICATIONPASSWORD
SSLの場合:
quarkus.mailer.auth-methods=DIGEST-MD5 CRAM-SHA256 CRAM-SHA1 CRAM-MD5 PLAIN LOGIN
quarkus.mailer.from=YOUREMAIL@gmail.com
quarkus.mailer.host=smtp.gmail.com
quarkus.mailer.port=465
quarkus.mailer.ssl=true
quarkus.mailer.username=YOUREMAIL@gmail.com
quarkus.mailer.password=YOURGENERATEDAPPLICATIONPASSWORD
The |
ネイティブ実行可能ファイルでのSSLの使用
Note that if you enable SSL for the mailer and you want to build a native executable, you will need to enable the SSL support. Please refer to the Using SSL With Native Executables guide for more information.
SMTP認証情報の設定
quarkus.mailer.password
のような機密データは暗号化することをお勧めします。一つの方法として、HashiCorp Vaultのような安全なストアに値を保存し、設定からそれを参照することができます。例えば、Vaultがパス myapps/myapp/myconfig
にキー mail-password
を含んでいるとすると、Mailerエクステンションは次のように簡単に設定できます。
...
# path within the kv secret engine where is located the application sensitive configuration
quarkus.vault.secret-config-kv-path=myapps/myapp/myconfig
...
quarkus.mailer.password=${mail-password}
パスワードの値は、起動時に一度だけ評価されることに注意してください。Vault で mail-password
が変更された場合、新しい値を取得するには、アプリケーションを再起動するしかありません。
Mailerの設定については、 設定リファレンスを参照してください。 |
trust storeの設定
SMTPにtrust storeが必要な場合は、以下のようにtrust storeを設定します。
quarkus.mailer.host=...
quarkus.mailer.port=...
quarkus.mailer.ssl=true
quarkus.mailer.trust-store.paths=truststore.jks # the path to your trust store
quarkus.mailer.trust-store.password=secret # the trust store password if any
quarkus.mailer.trust-store.type=JKS # the type of trust store if it can't be deduced from the file extension
Quarkus mailer supports JKS, PKCS#12 and PEM trust stores. For PEM, you can configure multiple files. For JKS and PKCS#12, you can configure the password if any.
quarkus.mailer.trust-store.type
is optional and allows configuring the type of trust store (among JKS
, PEM
and PKCS
). When not set, Quarkus tries to deduce the type from the file name.
また、 quarkus.mailer.trust-all=true を設定し、検証をバイパスするように設定することも可能です。
|
Mailer設定リファレンス
ビルド時に固定される設定プロパティ - それ以外の設定プロパティは実行時に上書き可能
タイプ |
デフォルト |
|
---|---|---|
Caches data from attachment’s Stream to a temporary file. It tries to delete it after sending email. Environment variable: |
boolean |
|
Sets the default Environment variable: |
string |
|
Enables the mock mode. When enabled, mails are not sent, but stored in an in-memory mailbox. The content of the emails is also printed on the console. Disabled by default on PROD, enabled by default on DEV and TEST modes. Environment variable: |
boolean |
|
Sets the default bounce email address. A bounced email, or bounce, is an email message that gets rejected by a mail server. Environment variable: |
string |
|
Sets the SMTP host name. Environment variable: |
string |
|
The SMTP port. The default value depends on the configuration. The port 25 is used as default when Environment variable: |
int |
|
Sets the username to connect to the SMTP server. Environment variable: |
string |
|
Sets the password to connect to the SMTP server. Environment variable: |
string |
|
Enables or disables the TLS/SSL. Environment variable: |
boolean |
|
Set whether all server certificates should be trusted. This option is only used when Environment variable: |
boolean |
|
Sets the max number of open connections to the mail server. Environment variable: |
int |
|
Sets the hostname to be used for HELO/EHLO and the Message-ID. Environment variable: |
string |
|
Sets if connection pool is enabled. If the connection pooling is disabled, the max number of sockets is enforced nevertheless. Environment variable: |
boolean |
|
Disable ESMTP. The RFC-1869 states that clients should always attempt Environment variable: |
boolean |
|
Sets the TLS security mode for the connection. Either Environment variable: |
string |
|
Enables DKIM signing. Environment variable: |
boolean |
|
Configures the PKCS#8 format private key used to sign the email. Environment variable: |
string |
|
Configures the PKCS#8 format private key file path. Environment variable: |
string |
|
Configures the Agent or User Identifier (AUID). Environment variable: |
string |
|
Configures the selector used to query the public key. Environment variable: |
string |
|
Configures the Signing Domain Identifier (SDID). Environment variable: |
string |
|
Configures the canonicalization algorithm for signed headers. Environment variable: |
|
|
Configures the canonicalization algorithm for mail body. Environment variable: |
|
|
Configures the body limit to sign. Must be greater than zero. Environment variable: |
int |
|
Configures to enable or disable signature sign timestamp. Environment variable: |
boolean |
|
Configures the expire time in seconds when the signature sign will be expired. Must be greater than zero. Environment variable: |
long |
|
Configures the signed headers in DKIM, separated by commas. The order in the list matters. Environment variable: |
list of string |
|
Sets the login mode for the connection. Either Environment variable: |
string |
|
Sets the allowed authentication methods. These methods will be used only if the server supports them. If not set, all supported methods may be used. The list is given as a space separated list, such as Environment variable: |
string |
|
Sets the trust store password if any. Note that the password is only used for JKS and PCK#12 trust stores. Environment variable: |
string |
|
Sets the location of the trust store files. If you use JKS or PCK#12, only one path is allowed. If you use PEM files, you can specify multiple paths. The relative paths are relative to the application working directly. Environment variable: |
list of string |
|
Sets the trust store type. By default, it guesses the type from the file name extension. For instance, Environment variable: |
string |
|
Whether the mail should always been sent as multipart even if they don’t have attachments. When sets to true, the mail message will be encoded as multipart even for simple mails without attachments. Environment variable: |
boolean |
|
Sets if sending allows recipients errors. If set to true, the mail will be sent to the recipients that the server accepted, if any. Environment variable: |
boolean |
|
Enables or disables the pipelining capability if the SMTP server supports it. Environment variable: |
boolean |
|
Sets the connection pool cleaner period. Zero disables expiration checks and connections will remain in the pool until they are closed. Environment variable: |
|
|
Set the keep alive timeout for the SMTP connection. This value determines how long a connection remains unused in the pool before being evicted and closed. A timeout of 0 means there is no timeout. Environment variable: |
|
|
Sets the workstation used on NTLM authentication. Environment variable: |
string |
|
Sets the domain used on NTLM authentication. Environment variable: |
string |
期間フォーマットについて
期間のフォーマットは標準の 数値で始まる期間の値を指定することもできます。この場合、値が数値のみで構成されている場合、コンバーターは値を秒として扱います。そうでない場合は、 |