2

ここでこのチュートリアルを入手しました...

jsp/サーブレットからメールを送信するには?

ただし、メールを送信したいデータベースからのメールアドレスのリストがある場合はどうなりますか

TestMail クラス

public class TestMail {
    public static void main(String... args) throws Exception {
        // Create mailer.
        String hostname = "smtp.example.com";
        int port = 2525;
        String username = "nobody";
        String password = "idonttellyou";
        Mailer mailer = new Mailer(hostname, port, username, password);

        // Send mail.
        String from = "john.doe@example.com";
        String to = "jane.doe@example.com";
        String subject = "Interesting news";
        String message = "I've got JavaMail to work!";
        mailer.send(from, to, subject, message);
    }
}

jsp

<form action="contact" method="post">
    <p>Your email address: <input name="email"></p>
    <p>Mail subject: <input name="subject"></p>
    <p>Mail message: <textarea name="message"></textarea></p>
    <p><input type="submit"><span class="message">${message}</span></p>
</form>

サーブレット

public class ContactServlet extends HttpServlet {
    private Mailer mailer;
    private String to;

    public void init() {
        // Create mailer. You could eventually obtain the settings as
        // web.xml init parameters or from some properties file.
        String hostname = "smtp.example.com";
        int port = 2525;
        String username = "nobody";
        String password = "forgetit";
        this.mailer = new Mailer(hostname, port, username, password);
        this.to = "you@example.com";
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("email");
        String subject = request.getParameter("subject");
        String message = request.getParameter("message");
        // Do some validations and then send mail:

        try {
            mailer.send(email, to, subject, message);
            request.setAttribute("message", "Mail succesfully sent!");
            request.getRequestDispatcher("/WEB-INF/contact.jsp").forward(request, response);
        } catch (MailException e) {
            throw new ServletException("Mailer failed", e);
        }
    }
}
4

4 に答える 4