Writing Simple Clients in Java Using Sockets using the JavaMail API
Using Sockets (Linden Chapter 17) // See page 571 of Linden's Just Java Fifth Edition import java.io.*; import java.net.*; public class Simple Client { public static void main(String args[]) throws IOException { Socket sock; DataInputStream dis; PrintStream ps;
// open a socket to an server on port 25 sock = new Socket("cyrus.andrew.cmu.edu",25); dis = new DataInputStream(sock.getInputStream()); ps = new PrintStream(sock.getOutputStream()); // talk ps.println("mail from: System.out.println(dis.readLine()); String Addressee = ps.println("rcpt to: " + Addressee); System.out.println(dis.readLine());
ps.println("data"); System.out.println(dis.readLine()); ps.println("A message sent by a Java client using sockets"); ps.println("."); System.out.println(dis.readLine()); ps.flush(); sock.close(); }
Output Echos from Cyrus D:\McCarthy\www\95-713\JavaMail>java Simple Client 220-mail-fe2.andrew.cmu.edu ESMTP Sendmail Beta2/ Beta2 220-Mis-identifing the sender of mail is an abuse of computing facilites. 220 ESMTP spoken here Sender ok
Using JavaMail // A simple example using JavaMail import java.io.*; import java.net.InetAddress; import java.util.Properties; import java.util.Date; import javax.mail.*; import javax.mail.internet.*; public class Mailer { String to, from, msg;
public Mailer(String to, String from, String msg) { this.to = to; this.from = from; this.msg = msg; } public void send() { Session s = createSession(); try { Message mess = createMessage(s, msg); Transport.send(mess); } catch(MessagingException e) { System.out.println("Messaging Exception: "+e); }
catch(Exception e ) { System.out.println("Exception thrown" + e); } private Session createSession() { Properties p = System.getProperties(); p.setProperty("mail.transport.protocol", "smtp"); p.setProperty("mail.smtp.host","cyrus.andrew.cmu.edu"); Session sess = Session.getDefaultInstance(p); return sess; }
private Message createMessage(Session sess, String msg)throws MessagingException{ Message mess = new MimeMessage(sess); mess.setFrom(new InternetAddress(from)); mess.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); mess.setSubject("Warning"); mess.setText(msg); mess.setSentDate(new Date()); return mess; }
public static void main(String a[]) { Mailer mailman = new "It's hot"); mailman.send(); }
Installation Instructions 1.Download the JavaMail API Implementation Version 1.3ea 2.Download the JavaBeans Activation Framework 1.0.2ea 3.Unzip both files. 4.Add the following files to your classpath: –mail.jar (JavaMail) –activation.jar (JAF file) Visit