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)アドレスの設定などができます。
一度の呼び出しで複数の 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テンプレートに基づくメッセージ Body
Qute テンプレート を使って、メッセージBodyが自動的に作成されるメールテンプレートを注入することが可能です。
@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メールクライアント の上に実装されており、非同期でノンブロッキングな方法でメールを送信することができます。メールの送信方法を細かく制御する必要がある場合、例えばメッセージのIDを取得する必要がある場合などの場合は、基礎となるクライアントを注入して直接使用することができます。
@Inject MailClient client;
3つのAPIフレーバーが公開されています。
-
Mutinyクライアント (
io.vertx.mutiny.ext.mail.MailClient) -
ベアクライアント (
io.vertx.ext.mail.MailClient)
各APIの詳細および最適なAPIの選択方法については、 Vert.x のガイド をご参照ください。
取得した MailClient は、上記で提示した設定キーを使用して設定します。また、独自のインスタンスを作成し、独自の設定を渡すこともできます。
ネイティブ実行可能ファイルでSSLを使用する場合
なお、メーラーのSSLを有効にしていて、ネイティブ実行可能ファイルをビルドする場合は、SSLのサポートを有効にする必要があります。詳しくは、 ネイティブイメージでのSSLの利用をご参照ください。
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
# This uses the https://github.com/quarkiverse/quarkus-vault extension.
quarkus.vault.secret-config-kv-path=myapps/myapp/myconfig
...
quarkus.mailer.password=${mail-password}
パスワードの値は、起動時に一度だけ評価されることに注意してください。Vault で mail-password が変更された場合、新しい値を取得するには、アプリケーションを再起動するしかありません。
| Vaultを使用するには、 Quarkus Vault エクステンションが必要です。このエクステンションとその設定の詳細については、 エクステンションのドキュメント を参照してください。 |
| Mailerの設定については、 設定リファレンスを参照してください。 |
トラストストアの設定
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は、JKS、PCKS#12、PEMのトラストストアをサポートしています。PEMでは、複数のファイルを設定することができます。JKSとPCKS#12では、パスワードが存在する場合、設定することができます。
quarkus.mailer.trust-store.type はオプションで、トラストストアのタイプを設定できます( JKS 、 PEM 、 PCKS の中から選択)。設定されていない場合、Quarkusはファイル名からタイプを推測しようとします。
また、 quarkus.mailer.trust-all=true を設定し、認証をバイパスするように設定することも可能です。
|
一般的なメールサービスに対応したMailer設定
ここでは、一般的なメールサービスで使用するための設定について説明します。
Gmail特有の設定
GmailのSMTPサーバーを利用する場合は、まず、 Google Account > Security > App passwords で専用のパスワードを作成するか、 https://myaccount.google.com/apppasswords に行きます。
|
App passwords ページにアクセスするには、 https://myaccount.google.com/security 、2段階認証をオンにする必要があります。 |
完了したら、 application.properties .Quarkusアプリケーションに以下のプロパティーを追加して、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
quarkus.mailer.mock=false # In dev mode, prevent from using the mock SMTP server
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
quarkus.mailer.mock=false # In dev mode, prevent from using the mock SMTP server
|
Quarkus Mailer が Gmailでのパスワード認証をサポートするには、 |
AWS SES - Simple Email Service
前提条件
-
SES Identity Checkでは、手順に従ってDKIM認証を設定します
-
SMTPエンドポイントを https://us-east-1.console.aws.amazon.com/ses/home から取得します。例:
email-smtp.us-east-1.amazonaws.com -
必要に応じてSMTP認証情報を作成します
-
サンドボックスの場合は、受信者の確認も行います(メール認証を使用する)
設定
ses.smtp=...
ses.user=...
ses.password=...
ses.from=an email address from the verified domain
quarkus.mailer.host=${ses.smtp}
quarkus.mailer.port=587
quarkus.mailer.username=${ses.user}
quarkus.mailer.password=${ses.password}
quarkus.mailer.start-tls=REQUIRED
quarkus.mailer.login=REQUIRED
quarkus.mailer.from=${ses.from}
quarkus.mailer.mock=false # In dev mode, prevent from using the mock SMTP server
MailJet
MailJetの統合は、SMTPリレーで使用されます。このSMTPサーバーを使ってメールを送信することになります。
設定
mailjet.smtp-host=in-v3.mailjet.com
mailjet.api-key=...
mailjet.secret-key=...
mailjet.from=the verified sender address
quarkus.mailer.host=${mailjet.smtp-host}
quarkus.mailer.port=465
quarkus.mailer.username=${mailjet.api-key}
quarkus.mailer.password=${mailjet.secret-key}
quarkus.mailer.start-tls=OPTIONAL
quarkus.mailer.ssl=true
quarkus.mailer.login=REQUIRED
quarkus.mailer.from=${mailjet.from}
quarkus.mailer.mock=false # In dev mode, prevent from using the mock SMTP server
Sendgrid
設定
sendgrid.smtp-host=smtp.sendgrid.net
sendgrid.username=apikey
sendgrid.key=...
quarkus.mailer.host=${sendgrid.smtp-host}
quarkus.mailer.port=465
quarkus.mailer.username=${sendgrid.username}
quarkus.mailer.password=${sendgrid.key}
quarkus.mailer.start-tls=OPTIONAL
quarkus.mailer.ssl=true
quarkus.mailer.login=REQUIRED
quarkus.mailer.from=...
quarkus.mailer.mock=false # In dev mode, prevent from using the mock SMTP server
メーラー設定リファレンス
ビルド時に固定される設定プロパティ - 他のすべての設定プロパティは実行時にオーバーライド可能
タイプ |
デフォルト |
|
|---|---|---|
Caches data from attachment’s Stream to a temporary file. It tries to delete it after sending email. Environment variable: Show more |
boolean |
|
Sets the default Environment variable: Show more |
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: Show more |
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: Show more |
string |
|
string |
|
|
The SMTP port. The default value depends on the configuration. The port 25 is used as default when Environment variable: Show more |
int |
|
Sets the username to connect to the SMTP server. Environment variable: Show more |
string |
|
Sets the password to connect to the SMTP server. Environment variable: Show more |
string |
|
Enables or disables the TLS/SSL. Environment variable: Show more |
boolean |
|
Set whether all server certificates should be trusted. This option is only used when Environment variable: Show more |
boolean |
|
Sets the max number of open connections to the mail server. Environment variable: Show more |
int |
|
Sets the hostname to be used for HELO/EHLO and the Message-ID. Environment variable: Show more |
string |
|
Sets if connection pool is enabled. If the connection pooling is disabled, the max number of sockets is enforced nevertheless. Environment variable: Show more |
boolean |
|
Disable ESMTP. The RFC-1869 states that clients should always attempt Environment variable: Show more |
boolean |
|
Sets the TLS security mode for the connection. Either Environment variable: Show more |
string |
|
Enables DKIM signing. Environment variable: Show more |
boolean |
|
Configures the PKCS#8 format private key used to sign the email. Environment variable: Show more |
string |
|
Configures the PKCS#8 format private key file path. Environment variable: Show more |
string |
|
Configures the Agent or User Identifier (AUID). Environment variable: Show more |
string |
|
Configures the selector used to query the public key. Environment variable: Show more |
string |
|
Configures the Signing Domain Identifier (SDID). Environment variable: Show more |
string |
|
Configures the canonicalization algorithm for signed headers. Environment variable: Show more |
|
|
Configures the canonicalization algorithm for mail body. Environment variable: Show more |
|
|
Configures the body limit to sign. Must be greater than zero. Environment variable: Show more |
int |
|
Configures to enable or disable signature sign timestamp. Environment variable: Show more |
boolean |
|
Configures the expire time in seconds when the signature sign will be expired. Must be greater than zero. Environment variable: Show more |
long |
|
Configures the signed headers in DKIM, separated by commas. The order in the list matters. Environment variable: Show more |
文字列のリスト |
|
Sets the login mode for the connection. Either Environment variable: Show more |
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: Show more |
string |
|
Sets the trust store password if any. Note that the password is only used for JKS and PCK#12 trust stores. Environment variable: Show more |
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: Show more |
文字列のリスト |
|
Sets the trust store type. By default, it guesses the type from the file name extension. For instance, Environment variable: Show more |
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: Show more |
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: Show more |
boolean |
|
Enables or disables the pipelining capability if the SMTP server supports it. Environment variable: Show more |
boolean |
|
Sets the connection pool cleaner period. Zero disables expiration checks and connections will remain in the pool until they are closed. Environment variable: Show more |
|
|
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: Show more |
|
|
Sets the workstation used on NTLM authentication. Environment variable: Show more |
string |
|
Sets the domain used on NTLM authentication. Environment variable: Show more |
string |
|
期間フォーマットについて
期間のフォーマットは標準の 数値で始まる期間の値を指定することもできます。この場合、値が数値のみで構成されている場合、コンバーターは値を秒として扱います。そうでない場合は、 |