Email in Java

I have been using direct socket connections to SMTP server to send out emails through JSP / Java code, but it turns out that no of email clients found that insufficient since, the emails sent out this way had bad chars in the headers that most clients did not understand, I guess its because of not using the SMTP protocal in detail , finally decided to use JavaMail API and it turns out that its quite a simple and easy integration using JavaMail, although I am using J2SE but the only additional files required to use JavaMail is the JavaMail API class and JavaBeans Activation Framework in your classpath and you are all ready to go, here is my simple code in JSP to send out an email.

<%@ page contentType=”text/html; charset=iso-8859-1″ language=”java” import=” java.util.*, java.sql.* , javax.mail.*,javax.mail.internet.*,*, java.text.*,*” errorPage=”” %>


String[] strrecipients = {“”, “”,””};

String strsubject;
String strmessage;
String strfrom ;

boolean debug = false;

strsubject = “this is a test”;

strmessage = “This is a test message  “;
strfrom = “”;

//Set the host smtp address
Properties props = new Properties();
props.put(“”, “”);

// create some properties and get the default Session
javax.mail.Session mailsession = Session.getDefaultInstance(props, null);

// create a message
Message msg = new MimeMessage(mailsession);

// set the from and to address
InternetAddress addressFrom = new InternetAddress(strfrom);

InternetAddress[] addressTo = new InternetAddress[strrecipients.length];
for (int i = 0; i < strrecipients.length; i++)
addressTo[i] = new InternetAddress(strrecipients[i]);
msg.setRecipients(Message.RecipientType.TO, addressTo);

// Optional : You can also set your custom headers in the Email if you Want
//    msg.addHeader(“MyHeaderName”, “myHeaderValue”);

// Setting the Subject and Content Type
msg.setContent(strmessage, “text/plain”);
catch (MessagingException ex)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s