How to send emails from a JSP page or a servlet ? Print

  • 45

To send an email from your java applications hosted on our servers, you can use the JavaMail library in the following way:

  1. Download the latest version of JavaMail:
    http://java.sun.com/products/javamail/
  2. Install the library in the WEB-INF/lib/ directory of your application

You can then use the following code example (Servlet sending a message) :

package com.tizoo;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;


public class Mailer extends HttpServlet
{
public void init() {}

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
props.put("mail.from", "adresse@expediteur.com");
Session sess = Session.getInstance(props, null);
try
{
MimeMessage msg = new MimeMessage(sess);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,
"adresse@destinataire.net");
msg.setSubject("Subject of message");
msg.setSentDate(new Date());
msg.setText("Message body!");
Transport.send(msg);
}
catch (MessagingException mex)
{
System.out.println("send failed, exception: " + mex);
}
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Message sent");
out.close();
}
}

 


Was this answer helpful?

Back