Javaでメールを送る

Javaでメールを送信する

1. 概要

このクイックチュートリアルでは、コアJavaメールライブラリを使用して、添付ファイル付きと添付ファイルなしでメールを送信する方法を見ていきます。

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

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


    javax.mail
    mail
    1.5.0-b01

最新バージョンはhereで見つけることができます。

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

まず、メールサービスプロバイダーの資格情報を使用してライブラリを構成する必要があります。 次に、送信するメッセージの作成に使用されるSession を作成します。

構成は、JavaのProperties objectを介して行われます。

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");

上記のプロパティ設定では、メールホストをMailtrapとして設定し、サービスが提供するポートも使用します。

それでは、ユーザー名とパスワードを使用してセッションを作成して、さらに進んでみましょう。

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

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

メールSession オブジェクトができたので、送信用のMimeMessage を作成しましょう。

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");

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

message.setContent(multipart);

Transport.send(message);

上記のスニペットでは、最初に、必要なプロパティ(to、from、subject)を使用してmessage インスタンスを作成しました。 メッセージはHTMLでスタイル設定されているため、その後にtext/html,のエンコーディングを持つmimeBodyPartが続きます。

次に行ったのは、作成したmimeBodyPartをラップするために使用できるMimeMultipart objectのインスタンスを作成することです。

最後に、multipart objectをmessageのコンテンツとして設定し、send()ofTransport objectを使用してメールを送信します。

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

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

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

次に、添付ファイルを送信するには、別のMimeBodyPartを作成し、それにファイルを添付するだけです。

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

次に、前に作成したMimeMultipartobjectに新しいボディパーツを追加できます。

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. 結論

結論として、ネイティブJavaメールライブラリを使用して、添付ファイルがあってもメールを送信する方法を見てきました。

いつものように、完全なソースコードはover on Githubで利用できます。