Você está na página 1de 5

Sending Email From a Web Application

April 2006 [Revision number: V2-4]


Copyright 2006 Sun Microsystems, Inc.

In this tutorial you use the Sun Java Studio Creator integrated development environment (IDE) to create a web application that enables users to send comments to a predefined email address. Contents - Designing the Application - Adding Code to Send Email - Running and Testing the Application Doing More: Sending Localized Messages

Designing the Application


1. Create a web application project and name it EmailProject. Figure 1 shows the page that you create in the following steps.

Figure 1: Email Project Design Layout 2. From the Basic section of the Palette, drag a Text Area component onto the page and then drag the edges of the Text Area to enlarge it. 3. Right-click the Text Area and choose Set Initial Focus from the pop-up menu. This action ensures that the text area is in focus when the page is displayed and that the user can immediately start typing. 4. Drag a Label component onto the page and drop it above the Text Area component. Set the text of the Label to Please enter your comments below. 5. Connect the Label to the Text Area. Select the Label, hold down the Ctrl+Shift keys, and drag a line to the Text Area. This action sets the Label's for property to textArea1. 6. Drag a Button component onto the page. Set the text of the Button to Send Us Your Comments. 7. In the Properties window, set the id property of the Button to cmdSend.

Adding Code to Send Email


1. In the Visual Designer, double-click the Send Us Your Comments button to view the Java code for the button. 2. Click the Code Clips tab in the Palette and expand the Web App Functions node. 3. Drag the Send Email code clip to the cmdSend_action method and drop it right before the return null statement. 4. In the dialog box, type the To and From email addresses. Enter the SMTP mail server name to use for sending the email. If you are not sure what to enter, try your own email address and use the SMTP mail server setting in your email program. If necessary, include the port number in the mail server setting. The following figure shows an example.

Figure 2 : Dialog Box to Set Parameters for Send Email Code 5. Click OK. The Send Email code clip is added to the cmdSend_action method. The code includes the values you entered in the dialog box as shown in bold in the following sample code. Press Ctrl+Shift+F to reformat the code. Code Sample 1: Send Mail Code Clip public String cmdSend_action() { // Send Email // This clip can be used in a button action // method to send an e-mail via SMTP // (if no authentication is required from the mailserver) // TODO: Create a Text Area component on the page and // a Button, place this code in the Button's action method // TODO: set the from, to addresses and the mail server String from = "sender-email@somecompany.com"; // from address String to = "receive-comments@yourcompany.com"; // to address String mailserver = "your-SMTP-mail-server@yourcompany.com"; // please note that if your mail server requires authentication, // this code may not work try { sun.net.smtp.SmtpClient client = new sun.net.smtp.SmtpClient( mailserver ); client.from(from); client.to(to); java.io.PrintStream message = client.startMessage(); message.println("To: " + to); // TODO: set the subject line message.println("Subject: Customer Comments"); // TODO: set the body of the message message.println(getTextArea1().getValue().toString()); client.closeServer(); } catch (java.io.IOException ex) { // in the case of an exception, print a message to the output log log("ERROR SENDING EMAIL:"+ex); } return null; }

6. Add the following code in bold to the cmdSend_action method, following the client.closeServer statement.

Code Sample 2: Send Comments Java Code // TODO: set the body of the message message.println(getTextArea1().getValue().toString()); client.closeServer(); textArea1.setText("Your comments have been submitted.");

7. To send a localized message, see Doing More: Sending Localized Messages. for additional changes to make to the cmdSend_action method.

Running and Testing the Application


1. Deploy and run the application. 2. Type some comments and click the Send Us Your Comments button. The following figure shows the results.

Figure 3 : Email Project: Output

Doing More: Sending Localized Messages


To send localized messages, you must change the cmdSend_action() method as follows:
q q

Add the appropriate headers to the message Encode the message body for your locale. For example, ISO-2022-JP for Japanese

The following sample shows code to add to the cmdSend_action() method to localize your message in Japanese. Add the code immediately before the client.closeServer statement.

Code Sample 3: Code to Send Localized Message in Japanese public String cmdSend_action() { ... // Add correct headers to the message message.println("Content-type: text/plain; charset=iso-2022-jp"); message.println("Content-language: ja"); message.println("Content-transfer-encoding: 7bit"); message.println(""); // Encode the message body correctly String mesg = getTextArea1().getText().toString() + "\r\n"; Charset charset = Charset.forName("ISO2022JP"); CharsetEncoder encoder = charset.newEncoder(); CharBuffer charBuff = CharBuffer.wrap(mesg.toCharArray()); ByteBuffer byteBuff = encoder.encode(charBuff); String newMesg = new String(byteBuff.array()); message.println(newMesg); client.closeServer(); ... }

If the Java Editor displays an error because the IDE cannot resolve a symbol, you can correct the problem with the Java Editor's Fix Imports feature. Right-click in the Java Editor and choose Fix Imports from the pop-up menu. The Fix Imports feature adds the following statement to the imports block: import import import import java.nio.ByteBuffer; java.nio.CharBuffer; java.nio.charset.Charset; java.nio.charset.CharsetEncoder;

See Also:
q q

Using Simple Page Navigation Using Dynamic Page Navigation

More Developer Resources: For more tutorials, articles, tips, forums, updates, and expert advice for developers, visit the Java Studio Creator developer resources on the Sun Developer Network (SDN) at http://developers.sun.com/jscreator/.

This page was last modified: April 27, 2006

Sun and Third-party Trademarked Terminology


The following Sun trademarked terms might be used in the Sun Java(tm) Studio Creator tutorials:
q q q q q q q q q

Sun Java Studio Creator integrated development environment (IDE) Sun Java System Application Server version number (Application Server) Java Platform, Standard Edition technology (Java SE(tm) platform) JavaServer(tm) Faces technology JavaServer Pages(tm) technology (JSP(tm) technology) Sun Java System Web Server version number (Web Server) Java Database Connectivity software (JDBC software) Enterprise JavaBeans(tm) specification (EJB(tm) specification) Solaris(tm) Operating System software (Solaris OS software)

The following third-party trademarked terms might be used in the Sun Java Studio Creator tutorials:
q q

UNIX(R) software SPARC(R) processor

Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved. Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed at http://www.sun.com/ patents and one or more additional patents or pending patent applications in the U.S. and in other countries. U.S. Government Rights - Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions of the FAR and its supplements. Use is subject to license terms. Sun, Sun Microsystems, the Sun logo, Java and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.This product is covered and controlled by U.S. Export Control laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities identified on U.S. export exclusion lists, including, but not limited to, the denied persons and specially designated nationals lists is strictly prohibited. Note: Sun is not responsible for the availability of third-party web sites mentioned in this document and does not endorse and is not responsible or liable for any content, advertising, products, or other materials on or available from such sites or resources. Sun will not be responsible or liable for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods, or services available on or through any such sites or resources.

Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, tats-Unis. Tous droits rservs. Sun Microsystems, Inc. dtient les droits de proprit intellectuels relatifs la technologie incorpore dans le produit qui est dcrit dans ce document. En particulier, et ce sans limitation, ces droits de proprit intellectuelle peuvent inclure un ou plus des brevets amricains lists l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires ou les applications de brevet en attente aux tats-Unis et dans les autres pays. L'utilisation est soumise aux termes de la Licence. Sun, Sun Microsystems, le logo Sun, Java et le logo Java Coffee Cup sont des marques de fabrique ou des marques dposes de Sun Microsystems, Inc. aux tats-Unis et dans d'autres pays.Ce produit est soumis la lgislation amricaine en matire de contrle des exportations et peut tre soumis la rglementation en vigueur dans d'autres pays dans le domaine des exportations et importations. Les utilisations, ou utilisateurs finaux, pour des armes nuclaires,des missiles, des armes biologiques et chimiques ou du nuclaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ou rexportations vers les pays sous embargo amricain, ou vers des entits figurant sur les listes d'exclusion d'exportation amricaines, y compris, mais de manire non exhaustive, la liste de personnes qui font objet d'un ordre de ne pas participer, d'une faon directe ou indirecte, aux exportations des produits ou des services qui sont rgis par la lgislation amricaine en matire de contrle des exportations et la liste de ressortissants spcifiquement dsigns, sont rigoureusement interdites. Sun Microsystems n'est pas responsable de la disponibilit de tiers emplacements d'enchanement mentionns dans ce document et n'approuve pas et n'est pas responsable ou iresponsable d'aucun contenu, de la publicit, de produits, ou d'autres matriaux dessus ou fournis par de tels emplacements ou ressources. Sun ne sera pas responsable ou iresponsable d'aucuns dommages ou perte causs ou allgus pour tre caus par ou en liaison avec l'utilisation de ce produit ou la confiance dans des tels contenu, marchandises, ou services disponibles sur ou par des tels emplacements ou ressources.

Você também pode gostar