Sending Mail Using Java

In this post, I would like to discuss how to send an e-mail using javax.mail library.

I will discuss how to send an e-mail for the simplest case. ie: I present my example for a scenario without authorization and other related issues. Once you get this mail application up and running, you can extend it further. I would regard my example as a beginner's starting position.
As I preffer to say, "Start from trivial" Dont't start your application with all complications and Network issues. You will get frustrated very soon. Once you get the trivial running, add the other requirements as features to your application.

In order to get started, you need an SMTP server. (When I mean a server, it does not necessarily mean a seperate machine running as a server. You can simply run a server application on your own machine)
An SMTP(Simple Mail Transfer Protocol) server is very similar to a post box. You pop a mail with the destination address stamped and, it takes care of delivering to the respected address.

If you are using Windows XP, you can use the SMTP server that comes along with the Windows CD. However, it is to be noted that this SMTP server does not get installed by default. You need to browse the CD and Add them.(Basic procedure for anyone) Add IIS and SMTP server and click install.

You can check that the installations were complete by right clicking on MyComputer->Manage

If successfully installed, you would get a similar picture as below.




Once you get the installation done, its time for coding.

Sending a mail becomes very simple with javax.mail API.

First, you need to create a Properties Object to store the
details of your mail server. You hold the key value pairs just as a Hashtable in Java.

Properties prop = new Properties();
prop.put("mail.smtp.host", "localhost");
prop.put("mail.smtp.port", "25");

Here, I have set the SMTP server's address to "localhost" indicating that the SMTP server is installed on my computer. You can also use "127.0.0.1" instead of "localhost". Makes no difference. The second property added is the port at which the SMTP server works. By default, these are Well known services which operate at so called "Well known ports". Port 25 is reserved for SMTP traffic.(Put for clarity. Should work even without that line. I have tested so)

Next, you need to get a session. It can be done via either of the following LOC(Line Of Code)
Note that, you need to pass the Properties object in any of the cases.

Session session = Session.getInstance(prop, null);
Session session = Session.getInstance(prop);

On the firsr LOC, we have a null object passed on to the overloaded method getInstance()
The second parameter is used when the mail server requires authentication. You need to pass an Authenticator object as the second parameter.
If the authentication system used by the SMTP server is password authentication(there may be other authentication systems other than password authentication), you can pass in a "PasswordAuthentication" object in the following way.

Session session = Session.getInstance(prop, new PasswordAuthentication("accountName","password"));

As in our very basic example, it is enough to use the second option as we do not bother about authentication. Make sure that you have switched off authentication mechanisms on your SMTP server. It can be easily found if you mess a little with the settings. Windows SMTP server by default allows annonymous users to send mail via the Server.

Here is how it appears on Windows SMTP server







Our Actual Message to send is used by an object of

javax.mail.internet.MimeMessage

We can create an object by the following LOC(Assume that you import javax.mail.internet package)

MimeMessage mimeMessage = new MimeMessage(session);

Then we need to set the TO and FROM address. The following LOC does them. They are very much self explained

InternetAddress from = new InternetAddress("anything@anything.com");
InternetAddress to = new InternetAddress("sendersAddress@gmail.com");
mimeMessage.setFrom(from);
mimeMessage.addRecipient(Message.RecipientType.TO, to);

You can send the messages to any address. I just used well known domain for clarity.
A serious issue with SMTP is that it accepts any address which is given as the sender. So you can add any address as the senders address and it would show up as that person actually sent it.

The subject and message could be set using the following LOC

mimeMessage.setSubject("TEST MAIL");
mimeMessage.setText("Hello World! This is Coooooooll");

Then sending the mail is done by the Transport Class's static method

Transport.send(mimeMessage);

You can write a simple programme with the above mentioned LOC and try it. Make sure you add try catch blocks! I removed them as they just obstruct the learnability of new Code.

The following is a simple programme which I wrote. Just try to run it on your computer.





package Main;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
*
* @author Ruchira
*/
public class SMTP_Sender {

public static void main(String[] ar){
try {
new SMTP_Sender().send();
} catch (AddressException ex) {
Logger.getLogger(SMTP_Sender.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessagingException ex) {
Logger.getLogger(SMTP_Sender.class.getName()).log(Level.SEVERE, null, ex);
}
}

public void send() throws AddressException, MessagingException{

Properties prop = new Properties();
prop.put("mail.smtp.host", "localhost");
prop.put("mail.smtp.port", "25");
Session session = Session.getInstance(prop);

MimeMessage mimeMessage = new MimeMessage(session);

InternetAddress from = new InternetAddress("from@ruchira.com");
InternetAddress to = new InternetAddress("to@gmail.com");
mimeMessage.setFrom(from);
mimeMessage.addRecipient(Message.RecipientType.TO, to);

mimeMessage.setSubject("TEST MAIL");
mimeMessage.setText("Hello World! This is Coooooooll");

Transport.send(mimeMessage);


}


}




Compile this and try to run. If you set the destination address outside your domain, most probably you would get an Error saying something related to "Relay".
By Default, SMTP servers are not privileged to send mail outside its domain for security issues. But for our app, we can safely remove the relaying settings.

It can be done by clicking on the "Relay" button under "Relay restriction" of the above picture. Once you click that, you would get a similar picture as below(Your address 127.0.0.1 is Not added by default), where you can add your IP address to allow sending mails from your machine to other domains by clicking Add button.




Once added, it would show up as above picture, where you have given privilege for your computer only.

Now try and run the above application and hopefully you will be able to send tha mail.

NOTE: Even though you sent the mail. It may be spammed by yahoo or gmail. So, instead of any senders address try using a valid username of a reputed mail server.

Have fun!!!!!!!!!!!!!!

Comments

Isuru Udana said…
It sounds like very interesting. Thanks for sharing!

Popular posts from this blog

Encrypt and Decrypt Images Using Java

Build your own Network sniffer

ASP Response.Write newline