Tuesday, November 22, 2011

A java program to send a mail


Here is java code to send a mail to a mail address.To implements this we use library mail.jar with the jdk.
Program code:-
import java.io.IOException;
import java.util.*;
import javax.mail.*;        //import classes from mail.jar
import javax.activation.*;
import javax.mail.internet.*;

public class javamail {
public static void main(String args[]) throws AddressException, MessagingException, IOException
{
 Properties props=new Properties();
 props.put("mail.transport.protocol","smtp");    // define protocol

 props.put("mail.smtp.host","localhost");           // defile the host address
 props.put("mail.smtp.port","25");                   // define a port address of protocol
 Session mailSession=Session.getInstance(props);
 Message msg=new MimeMessage(mailSession);
 msg.setFrom(new InternetAddress("navin@localhost"));
 msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse
                      ("raj@localhost"));
 msg.setSentDate(new Date());
 msg.setSubject("Test mail");
msg.setText("hello mail");

 msg.writeTo(System.out);    // to write the detail on the consol
  }

}
Here getSession() contain three arguments:-
1. Protocol name.
2. Host address or server address.
3. Port number of the service. Here this service is open on port no. 25.

Output:-
 Date: Wed, 23 Nov 2011 10:52:52 +0530 (IST)
From: navin@localhost
To: raj@localhost
Message-ID: <32320232.0.1322025772561.JavaMail."Navin Bansal"@Navin-PC>
Subject: Test mail
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
hello mail


For Further Reading,
General, Java

1 comments:

Unknown on May 3, 2012 at 5:38 PM said...

test comment

Post a Comment


 

Site Status

Man Behind Technical Today

Hello, I am Navin Bansal. I am a student of MCA in Rajsthan Institute of Engineering and Technology and owner of this blog. I share my view and ideas among people.