Javaでのメール送信の結果の取得方法

JavaMail APIを利用して、メールを送信することができます。その際、送信結果は送信後にチェックすることで取得可能です。以下は、メールを送信して送信結果を取得する方法のサンプルコードです。

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class SendEmail {
    public static void main(String[] args) {
        // 配置邮件服务器
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.example.com");
        properties.put("mail.smtp.port", "587");
        properties.put("mail.smtp.auth", "true");
        
        // 创建Session对象
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("your-email@example.com", "your-password");
            }
        });
        
        try {
            // 创建Message对象
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("your-email@example.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
            message.setSubject("Hello, World!");
            message.setText("This is a test email.");
            
            // 发送邮件
            Transport.send(message);
            
            // 邮件发送成功
            System.out.println("Email sent successfully!");
        } catch (MessagingException e) {
            // 邮件发送失败
            System.out.println("Email sending failed: " + e.getMessage());
        }
    }
}

先頭に示したコードにおいて、メールサーバの構成とSessionオブジェクトの作成をJavaMail APIを用いて行っています。Sessionオブジェクトにユーザ名とパスワードを渡すことで認証を実現しています。続いて、Messageオブジェクトを生成し、差出人、宛先、件名、本文を設定します。最後に、Transport.send()メソッドを呼び出すことでメールを送信します。

メール送信に成功した場合は「メールの送信に成功しました!」と表示し、失敗した場合は「メールの送信に失敗しました」とエラー情報をつけて表示する。

bannerAds