Sending an email with JSP
Below is a simple JSP page to send an email using a datasource. Each user has a preconfigured
datasource with the name "smtp_username" where username is your webspace name. Using datasources
is preferable to making a standard SMTP connection as if we make any changes to our mail configuration
you will not need to update your application.
Note: Do not include mail.jar or activation.jar files in your applications classpath ('WEB-INF/lib')
as these are already in Tomcat's classpath by default and you may receive class cast exceptions.
<%@ page language="java" import="javax.naming.*,java.io.*,javax.mail.*,javax.mail.internet.*"%>
<%
try{
out.println("Sending an email");
Context initCtx = new InitialContext();
javax.mail.Session mailSession = (javax.mail.Session) initCtx.lookup("java:/comp/env/mail/smtp_username");
Transport trans = mailSession.getTransport("smtp");
trans.connect(mailSession.getProperty("mail.smtp.host"),
mailSession.getProperty("mail.smtp.user"),
mailSession.getProperty("mail.smtp.password")
);
MimeMessage m = new MimeMessage(mailSession);
m.setFrom(new InternetAddress("username@devisland.net"));
Address[] toAddr = new InternetAddress[] {
new InternetAddress("user@test.org")
};
m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr );
m.setSubject("JavaMail Test");
m.setSentDate(new java.util.Date());
m.setContent("Test", "text/plain");
trans.sendMessage(m,m.getAllRecipients());
trans.close();
}
catch(Exception e){
out.println(e.getMessage());
e.printStackTrace();
}
%>
|