Java Code for sending messages(text or multimedia) from 1 pc to another in LAN.
Example Code
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.smtp.SMTPTransport;
import java.io.*;
import java.util.*;
public class MailSender
{
private Transport transport;
private Message message;
private Session session;
public static void main(String[] args) throws Exception{
MailSender mailSender = new MailSender();
String from = "
[email protected] ";
String to[] = new String[]{"vinod@localhost"};
String subject = "news";
String content = "Hi, how are you?";
mailSender.setMessage(from,to,subject,content);
mailSender.setSMTPServer("localhost",25,null,null);
mailSender.send();
}
public void setMessage(String fromAddress,String toAddress,String subject,String content)
throws Exception
{
String[] addresses = {toAddress};
setMessage(fromAddress,addresses,subject,content);
}
public void setMessage(String fromAddress,String[] toAddresses,String subject,String content)
throws Exception
{
session = Session.getInstance(System.getProperties());
message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
InternetAddress[] toIntAdds = new InternetAddress[toAddresses.length];
for (int i=0;i<toAddresses.length;i++)
toIntAdds[i] = new InternetAddress(toAddresses[i]);
message.setRecipients(Message.RecipientType.TO,toIntAdds);
message.setSubject(subject);
message.setSentDate(new java.util.Date());
message.setText(content);
File f = new File("Message.properties");
Properties pro = new Properties();
FileInputStream in = new FileInputStream(f);
pro.load(in);
//String companyName="Cinbell";
//String messageIdKey=pro.getProperty(companyName);
//System.out.println("messageIdKey:"+messageIdKey);
message.setHeader(messageIdKey,"1000");
/* File f = new File("Message.properties");
Properties pro = new Properties();
FileInputStream in = new FileInputStream(f);
pro.load(in);
Enumeration em = pro.keys();
while(em.hasMoreElements()){
String key = (String)em.nextElement();
String val = pro.getProperty(key);
message.setHeader(val,"1000"); } */
}
public void setSMTPServer(String host,int port,String user,String password) throws Exception{
transport = new SMTPTransport(session,new URLName(host));
transport.connect(host,port,null,null); }
public void send() throws Exception{
message.saveChanges();
transport.sendMessage(message, message.getAllRecipients());
System.out.println("Message is sent.");
transport.close(); } }