You are on page 1of 6

SMTP Program

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMailSSL {
public static void main(String[] args) {
String to="sonoojaiswal1987@gmail.com";//change accordingly
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("yourgmailid@gmail.com","password");//change accordingly
}
});
//compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("yourgmailid@gmail.com"));//change accordingly
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Hello");
message.setText("Testing.......");
//send message
Transport.send(message);
System.out.println("message sent successfully");
}
catch (MessagingException e)
{
throw new RuntimeException(e);
}

POP3 Program
import
import
import
import
import
import
import
import

java.io.IOException;
java.util.Properties;
javax.mail.Folder;
javax.mail.Message;
javax.mail.MessagingException;
javax.mail.NoSuchProviderException;
javax.mail.Session;
com.sun.mail.pop3.POP3Store;

public class ReceiveMail{


public static void receiveEmail(String pop3Host, String storeType,
String user, String password) {
try {
//1) get the session object
Properties properties = new Properties();
properties.put("mail.pop3.host", pop3Host);

Session emailSession = Session.getDefaultInstance(properties);


//2) create the POP3 store object and connect with the pop server
POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
emailStore.connect(user, password);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//5) close the store and folder objects
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {e.printStackTrace();}
catch (MessagingException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
public static void main(String[] args) {
String
String
String
String

host = "mail.javatpoint.com";//change accordingly


mailStoreType = "pop3";
username= "sonoojaiswal@javatpoint.com";
password= "xxxxx";//change accordingly

receiveEmail(host, mailStoreType, username, password);


}
}

Http request Program


import java.net.*;
import java.io.*;
public class URLConnDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL("http://www.amrood.com");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)
{
connection = (HttpURLConnection) urlConnection;
}
else
{
System.out.println("Please enter an HTTP URL.");
return;

}
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String urlString = "";
String current;
while((current = in.readLine()) != null)
{
urlString += current;
}
System.out.println(urlString);
}catch(IOException e)
{
e.printStackTrace();
}
}
}

FTP Program
FTP Client:
import java.io.*;
import java.net.*;
public class FTPClient
{
public static void main(String[] args)
{
try
{
Socket client = new Socket("127.0.0.1",10000);
PrintWriter writer = new PrintWriter(client.getOutputStream());
writer.println("f:/demo/HTTP.java");
writer.flush();
InputStreamReader stream = new InputStreamReader(client.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String str = null;
while((str = reader.readLine()) != null)
{
System.out.println(str);
}
reader.close();
}
catch(Exception e)
{
System.out.println("Connection is terminated by the Server");
}}}

FTP Server:
import java.io.*;
import java.net.*;
public class FTPServer

{
public static void main(String[] arg)
{
try
{
ServerSocket server = new ServerSocket(10000);
Socket client;
client= server.accept();
InputStreamReader stream = new InputStreamReader(client.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String filename = reader.readLine();
PrintWriter writer = new PrintWriter(client.getOutputStream());
FileInputStream fileStream = new FileInputStream(new File(filename));
int ch;
while((ch = fileStream.read()) != -1)
{
writer.write(ch);
writer.flush();
}
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}}}

Simple chat program


Server Side
import java.io.*;
import java.net.*;
class Server
{
public static DatagramSocket serversocket;
public static DatagramPacket dp;
public static BufferedReader dis;
public static InetAddress ia;
public static byte buf[]=new byte[1024];
public static int cport=789,sport=790;
public static void main(String a[])throws IOException
{
serversocket=new DatagramSocket(sport);
dp=new DatagramPacket(buf,buf.length);
dis=new BufferedReader(new InputStreamReader(System.in));
ia=InetAddress.getLocalHost();
System.out.println("Server is waiting for data from client");
while(true)
{
serversocket.receive(dp);
String s=new String(dp.getData(),0,dp.getLength());
System.out.println(s);
}
}
}
Client Side
import java.io.*;
import java.net.*;
class Client

{
public static DatagramSocket clientsocket;
public static BufferedReader dis;
public static InetAddress ia;
public static byte buf[]=new byte[1024];
public static int cport=789,sport=790;
public static void main(String a[])throws IOException
{
clientsocket = new DatagramSocket(cport);
dis=new BufferedReader(new InputStreamReader(System.in));
ia=InetAddress.getLocalHost();
System.out.println("Client is sending data to Server ");
while(true)
{
String str=dis.readLine();
buf=str.getBytes();
clientsocket.send(new DatagramPacket(buf,str.length(),ia,sport));
}
}
}
Parsing XML file
Test.xml
<?xml version="1.0"?>
<students>
<student>
<name>John</name>
<grade>B</grade>
<age>12</age>
</student>
<student>
<name>Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18</age>
</student>
</students>
XMLParser1.java
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLParser1
{
public void getAllUserNames(String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);

if (file.exists()) {
Document doc = db.parse(file);
Element docEle = doc.getDocumentElement();
// Print root element of the document
System.out.println("Root element of the document: "+ docEle.getNodeName());
NodeList studentList = docEle.getElementsByTagName("student");
// Print total student elements in document
System.out.println("Total students: " + studentList.getLength());
if (studentList != null && studentList.getLength() > 0) {
for (int i = 0; i < studentList.getLength(); i++) {
Node node = studentList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("=====================");
Element e = (Element) node;
NodeList nodeList = e.getElementsByTagName("name");
System.out.println("Name: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());
nodeList = e.getElementsByTagName("grade");
System.out.println("Grade: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());
nodeList = e.getElementsByTagName("age");
System.out.println("Age: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());
}
}
} else {
System.exit(1);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
XMLParser1 parser = new XMLParser1();
parser.getAllUserNames("test.xml");
}
}

You might also like