devxlogo

Send E-Mails Using the java.net.URLConnection Class

Send E-Mails Using the java.net.URLConnection Class

Recently, I found I needed to send e-mail from my program. Because I did not want to create any external dependencies, I decided not to use JavaMail. However, I wanted something really simple to send just plain text. The solution I found uses only the classes from standard Java distribution, making it quite limited in its capabilities. It does not support attachments, signatures, etc., but it does the job. The only thing needed to make it work is a valid and running SMTP host.

  /**   * Actually sends email using URLConnection class.   * This method is made static, so it can be called all    * by itself. It actually   * has all the info it needs passed in thru parameters.   * 

* One important piece of the information that this method * needs in order to work * is a reference to a valid SMTP host. This reference * is picked up from the system * property . That's why it is * important that this property is * either set before the program runs, or the valid * host name is entered in the code * instead of a placeholder [VALID SMTP HOST]. * * @param from The sender of the message. * @param to The adressee. Should be standard * email address, like [email protected]. * @param subject The subject of the message. * @param message The text of the message. */ public static void sendEmail(String from, String to, String subject, String message) { // valid SMTP has to be set up and running, // and system property mail.host should point to it; // let's see if we have anything set up for //this property, and if not, // set it up to our mail server String mailHost = System.getProperty("mail.host"); if (mailHost == null) { System.setProperty("mail.host", [VALID_SMTP_HOST]); } try { // open connection using internal "mailto" protocol handler URL url = new URL("mailto:" + to); URLConnection conn = url.openConnection(); conn.setDoInput(false); conn.setDoOutput(true); conn.connect(); // get writer into the stream PrintWriter out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream() ) ); // write out mail headers // From header in the form From: "alias" out.println("From: "" + from + "" "); out.println("To: " + to); out.println("Subject: " + subject); out.println(); // blank line to end the list of headers // write out the message out.println(message); // close the stream to terminate the message out.close(); } catch(Exception err) { System.err.println(err); err.printStackTrace(System.err); } }

size=3>

devx-admin

Share the Post: