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.net.*, java.text.*,java.io.*” errorPage=”” %>

<%

String[] strrecipients = {“imran@mydomain.com”, “user@hotmail.com”,”user@gmail.com”};

String strsubject;
String strmessage;
String strfrom ;

boolean debug = false;

strsubject = “this is a test”;

strmessage = “This is a test message  http://www.mydomain.com  “;
strfrom = “admin@mydomain.com”;

//Set the host smtp address
try
{
Properties props = new Properties();
props.put(“mail.smtp.host”, “mail.mydomain.com”);

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

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

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

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.setSubject(strsubject);
msg.setContent(strmessage, “text/plain”);
Transport.send(msg);
}
catch (MessagingException ex)
{
out.println(ex.toString());
}

%>

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s