1. 概要

In this quick tutorial, we’re going to look at sending an email with and without attachments using the core Java mail library.

2. プロジェクトの設定と依存関係

この記事では、Javaメールライブラリに依存する単純なMavenベースのプロジェクトを使用します。

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</version>
</dependency>

最新バージョンはここにあります。

3. プレーンテキストとHTMLメールの送信

まず、電子メールサービスプロバイダーの資格情報を使用してライブラリを構成する必要があります。 Then we’ll create a Session that’ll be used in constructing our message for sending.

構成は、Javaプロパティオブジェクトを介して行われます。

Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "smtp.mailtrap.io");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.ssl.trust", "smtp.mailtrap.io");

In the properties configuration above, we configured the email host as Mailtrap and used the port provided by the service as well.

Now let’s create a session with our username and password:

Session session = Session.getInstance(prop, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
});

ユーザー名とパスワードは、ホストとポートのパラメーターとともにメールサービスプロバイダーによって提供されます。

メールセッションオブジェクトができたので、送信する Mimeメッセージを作成しましょう。

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(
  Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Mail Subject");

String msg = "This is my first email using JavaMailer";

MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html; charset=utf-8");

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);

message.setContent(multipart);

Transport.send(message);

In the snippet above, we first created a message instance with the necessary properties — to, from and subject. This is followed by a mimeBodyPart that has an encoding of text/html since our message is styled in HTML.

Next, we created an instance of MimeMultipart object that we can use to wrap the mimeBodyPart we created.

Finally, we set the multipart object as the content of our message and used the send() of Transport object to do the mail sending.

So, we can say that the mimeBodyPart is contained in the multipart that is contained in the message. This way, a multipart can contain more than one mimeBodyPart.

これが次のセクションの焦点になります。

4. 添付ファイル付きの電子メールの送信

Next, to send an attachment, we only need to create another MimeBodyPart and attach the file(s) to it:

MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(new File("path/to/file"));

We can then add the new body part to the MimeMultipart object we created earlier:

multipart.addBodyPart(attachmentBodyPart);

それが私たちがする必要があるすべてです。

Once again, we set the multipart instance as the content of the message object, and finally we’ll use the send() to do the mail sending.

5. 電子メールテキストのフォーマット

To format and style our email text, we can use HTML and CSS tags.

For example, if we want our text to be bold, we will implement the  tag. For coloring the text, we can use the style tag. We can also combine HTML tags with CSS tags if we want to have additional properties, such as bold.

Let’s create a String containing bold-red text:

String msgStyled = "This is my <b style='color:red;'>bold-red email</b> using JavaMailer";

この文字列は、メール本文で送信されるスタイル付きテキストを保持します。

6. 結論

In this article, we’ve seen how to use the native Java mail library to send emails even with attachments.

As always, the complete source code is available over on GitHub.