peony3000
YaBB Newbies
Offline
Posts: 5
Re: Sending an Email Programmatically?
Reply #5 - Apr 12th , 2006, 5:40pm
//This works without any extra libraries! //Code adapted from http://www.javaworld.com/javaworld/javatips/jw-javatip36-p3.html //and Craig Morrall <morrall at comp.lancs.ac.uk> String sender = "<me at gold.ac.uk>"; String reciever = "<someone else at gold.ac.uk>"; String subject = "This message is coming from Processing"; String message = "Mail Message"; String mailServer = "postbox.gold.ac.uk"; //strange java thing to get a correct carriage return String carriageReturn = System.getProperty("line.separator"); void setup() { sendMessage(); } void sendMessage() { println("Trying..."); try { //connect to the mail server Socket socket = new Socket(mailServer, 25); //create an in and out connection DataOutputStream out = new DataOutputStream(socket.getOutputStream()); DataInputStream in = new DataInputStream(socket.getInputStream()); //ask your machine what it's really called String hostname = InetAddress.getLocalHost().getHostName(); println("HOST: "+hostname); //converse with the mail server readIn(in); sendEmail(out, in, "HELO " + hostname + carriageReturn); readIn(in); sendEmail(out, in, "RSET" + carriageReturn); readIn(in); //tell the mail server your email sendEmail(out, in, "MAIL FROM: " + sender + carriageReturn); readIn(in); //tell the mail server where you want to send the message sendEmail(out, in, "RCPT TO: " + reciever + carriageReturn); readIn(in); //start the message body sendEmail(out, in, "DATA" + carriageReturn); readIn(in); sendEmail(out, in, "To:" + reciever + carriageReturn); sendEmail(out, in, "From:" + sender + carriageReturn); sendEmail(out, in, "Subject: " + subject + carriageReturn); sendEmail(out, in, message); //close the message body sendEmail(out, in, carriageReturn + "." + carriageReturn); //end of message body //end the conversation readIn(in); sendEmail(out, in, "QUIT" + carriageReturn); readIn(in); //close the connections in.close(); out.close(); println("Message '" + subject + "' sent to '" + reciever + "'"); }//end of try statement catch (UnknownHostException e) { println("Unknown Host Exception: " + e); }//end of catch statement catch(IOException e) { println("Send failure: " + e); }//end of catch statement }//end of method sendMessage void sendEmail(DataOutputStream out, DataInputStream in, String stringHolder) throws IOException { if(stringHolder != null) { out.writeBytes(stringHolder); println(stringHolder); }//end of if statement }//end of method sendEmail void readIn(DataInputStream in) throws IOException { String record; if ((record = in.readLine()) != null) { println("Message from host: "+record); }//end of if statement }//end of method readIn