According to IAN F. Darwin's "Java Cookbook", the original book uses the text of the whole chapter to introduce how to send an email. It may be more chaotic. This article is concentrated into an article, strive to make people who don't understand JavaMail. It can be used in writing in the text, it can be used. If you are unclear with the principle, you can refer to the original book.
First, first you need to use three Java files:
1. MailConstants.java, the help notes of the Properties file: /// package usd2;
/ ** Simply a list of names for the Mail System to use. * If you "implement" this interface, you do not have to prefix * all the names with MailProps in your code. * / Public interface MailConstants {public static final String props_file_name = "mailclient.properties";
public static final String SEND_PROTO = "Mail.send.protocol"; public static final String SEND_USER = "Mail.send.user"; public static final String SEND_PASS = "Mail.send.password"; public static final String SEND_ROOT = "Mail .send.Root "; public static final string send_host =" mail.send.host "; public static final string send_debug =" mail.send.debug ";
public static final String RECV_PROTO = "Mail.receive.protocol"; public static final String RECV_PORT = "Mail.receive.port"; public static final String RECV_USER = "Mail.receive.user"; public static final String RECV_PASS = "Mail .receive.password "; public static final String RECV_ROOT =" Mail.receive.root "; public static final String RECV_HOST =" Mail.receive.host "; public static final String RECV_DEBUG =" Mail.receive.debug ";} / //
2.FileProperties.java, read Properties: /// package us from the file;
Import java.io. *; import java.util. *;
/ ** * The This subclass preserves the useful feature that * a property list can contain another property list as its * "defaults" THIS SECOND Property List Is Searched if * The property key is not found in the original property list. * * @Author ian f. darwin, Ian@darwinsys.com * @version $ ID: FileProperties.java, V 1.5 2001/04 / 28 13:22:37 ian Exp $ * / public class FileProperties extends Properties {protected String fileName = null; / ** * Construct a FileProperties given a fileName * @param loadsaveFileName the progerties file name * @throws IOException * / public. FileProperties (String LoadsaveFileName) throws ioException {super (); filename = loadingsavefilename; loading (); / ** Construct a FileProperties given a fileName and * a list of default properties. * @Param loadsaveFileName the properties file name * @param defProp the default properties * @throws IOException * / public FileProperties (String loadsaveFileName, Properties defProp) throws IOException { Super (Defprop); filename = loading; loading; loading; / ** the inputstream for loading * / protected input information; / ** the outputstream for loading * / protected outputstream outstr = null; / ** Load the properties from the saved filename. * If that fails, try again, tacking on the .properties extension * @throws IOException * / public void load () throws IOException {try {if (inStr == null) {inStr = new FileInputStream (fileName);}} catch (FileNotFoundException fnf) {if {inStr = new FileInputStream (fileName ".properties") (fileName.endsWith ()! "properties."); // If we succeeded, remember it : Filename = ".properties";} else {// it did end with .properties and failed, re-throw exception. Throw fnf;}} // Now message the superclass code to load the file. Load (instr); } / ** save the property for later loading. * * @Throws oException * / public void save () throws IOException {if (outStr == null) {outStr = new FileOutputStream (fileName);.} // Get the superclass to do most of the work for us store (outStr, "# Written by FileProperties.save () AT " new date ()); Public void close () {Try {if (INSTR! = null) {INSTR.CLOSE ();} if (outstr! = null) {outstr.close ();}} catch (ooException e) {// Don't Care}}} /// 3.Mailer.java, package the part of the Javamail email: /// package usd2; Import java.util. *; import java.io. *; import javax.mail. *; import javax.mail.internet. *; import javax.activation. *; public class Mailer {/ ** The javamail session object * / protected Session session;. / ** The sender's email address * / protected String from;. / ** The subject of the message * / protected String subject; / ** The Recipient ("to:"), as strings. * / protected arraylist tolist = new arraylist (); / ** The cc list, as strings. * / protected arraylist cclist = new arraylist (); / ** The BCC List, . as Strings * / protected ArrayList bccList = new ArrayList ();. / ** The text of the message * / protected String body; / ** The SMTP relay host * / protected String mailHost; / ** The accessories list, as . Strings * / protected ArrayList accessories = new ArrayList (); / ** The verbosity setting * / protected boolean verbose; / ** Get from * @return where the mail from * / public String getFrom () {return from;} / ** set from * @Param fm where the mail from * / public void setfrom (string fm) {from = fm;} / ** Get Subject * @return the mail subject * / public string getsubject () {Return Subject; / ** SET SUBJECT * @Param Subj The Mail Subject * / Public Void Setsubject (SUBJECT = Subj;} // setters / getters for to: list / ** Get Tolist, as an array of strings * @return the list of toaddress * / public arraylist gettolist () {Return Tolist;} / ** set to list to an arraylist of strings * @Param to the list of toaddress * / public void settolist (arraylist to) {tolist = to;} / ** set to as a string like "Tom, Mary, Robin @ Host". Loses any * previously-set values. * @Param s the list of toaddress * / public void settolist (String s) {TOLIST = tokenize (S } / ** Add one "to" Recipient * @Param to the toaddress * / public void addtto (string to) {tolist.add (to);} // setters / getters for cc: list / ** Get cclist, as an array of strings * @return the list of ccaddress * / public arraylist getclist () {return cclist;} / ** SET CC List to an arraylist of strings * @Param cc the list of ccaddress * / public void setclist (arraylist cc) {cclist = cc;} / ** SET CC AS A STRING LIKE "TOM, MARY, Robin @ Host". Loses any * previously-set value. * @Param s the list of ccaddress * / public void setclist (string s) {cclist = tokenize (s } / ** Add one "cc" Recipient * @Param cc the Address of cc * / public void addcc (string cc) {cclist.add (cc); // setters / getters for BCC: List / ** Get bcclist, as an array of strings * @return the list of bcc * / public arraylist getbclist () {return bcclist; / ** SET BCC List to an arraylist of strings * @Param BCC The Address of BCC * / Public Void SetBclist (arraylist bcc) {bcclist = bcc;} / ** SET BCC AS A STRING LIKE "TOM, MARY, Robin @ Host". Loses any * previously-set value. * @Param s the address of bcc * / public void setbclist (string s) {bcclist = tokenize (s } / ** Add One "BCC" Recipient * @Param BCC The Address Of BCC * / Public Void AddBCC (String BCC) {BCCList.Add (BCC); // setter / getter for message body / ** Get Message * @return the mail body * / public string getBody () {return body;} / ** SET Message * @Param text the mail body * / public void setbody (string text) {body = text; // setter / getter for accessories / ** Get accessories * @return the arrayList of the accessories * / public ArrayList getAccessories () {return accessories;} / ** Set accessories * @param accessories the arrayList of the accessories * / public void setAccessories (ArrayList accessories) {this .accessories = Accessories; // setter / getter for verbosit / ** Get Verbose * @return verbose * / public boolean isverbose () {return verbose;} / ** set verbose * @Param v the verbose * / public void setverbose (boolean v) {verbose = v;} / ** Check if all required fields have been set before sending. * Normally called eg, by a JSP before calling doSend. * Is also called by doSend for verification. * @Return if complete return true else return false * / public boolean isComplete () {If (from == null ||) {System.err.Println ("DOSEND: NO from"); Return False;} if (Subject == Null || Subject.Length () == 0) {System.err.Println ("DOSEND: No Subject"); Return False;} if (Tolist.size () == 0) {System.err.Println ("Dosend: No Recipients") Return false;} if (body == null || body.Length () == 0) {system.err.println ("DOSEND: NO BODY"); returnaf (} =} (mailhost == null || mailhost .length () == 0) {System.err.Println ("DOSEND: NO Server Host"); Return true;} Return true; Public void setserver (string s) {mailhost = s;} / ** send the message. * @Throws messageXception * / public synchronized void Dosend () throws message { if {throw new IllegalArgumentException ( "doSend called before message was complete");} (isComplete ()!) / ** Properties object used to pass props into the MAIL API * / Properties props = new Properties (); props.put ( "mail.smtp.host", mailhost); // create the session object if (session == null) {session = session.getDefaultInstance (props, null); if (verbose) {session.SetDebug (true); // verbose!}} // Create a Message Final Message Mesg = New MimeMessage (SESSION); Internet ADRESS [] Addresses; // to address list addresses = new internetdress [Tolist.size ()]; for (int i = 0; i // from address messg.setfrom (new internetdress (from)); // cc address list address = new internetdress [cclist.size ()]; for (int i = 0; i // bcc address list address = new internetdress [bcclist.size ()]; for (int i = 0; i // the subject meseg.setsubject (subject); // Now the message body. Multipart MP = new mimeMultipart (); MIMEBODYPART MIMEBP = NULL; MBP = new mimebodypart (); MP.Settext (body); mp.addbodypart (MBP); // Now the accessories. Int accessories.size (); file f; datasource ds; string uf; int J; for (int i = 0; i // finally, send the message! (Use static transport method) // do this in a thread as it sometimes is to slow for jserv // new thread () {// public void run () {// try { TRANSPORT.SEND (MESG); //} catch (messagingException e) {// throw new illegalargumentException (// "transport.send () threw:" E.TOSTRING ()); //} //} //} .start ();} . SMTP server host * @param recipient - - domain address of email (user@host.domain) * @param sender - your email address * @param subject / ** Convenience that does it all with one call * @param mailhost method - the subject line * @param message - the entire message body as a String with embedded / n's * @param accessories - the accessories list * @throws MessagingException * / public static void send (String mailhost, String recipient, String sender, String subject, String message, ArrayList accessories) throws MessagingException {Mailer m = new Mailer (); m.setServer (mailhost); m.addTo (recipient); m.setFrom (sender); m.setSubject (subject); m.setBody (message ); M.SetAccessories; m.dosend ();} / ** Convert a list of addresses to an arraylist. This will work * for simple name "Tom, Mary@foo.com, 123.45@catate. COM "* But Will Fail on Certain Complex (But Rfc-Valid) Names Like * "(Darwin, Ian) Second, create a Properties file: MailClient.properties :///_ This file contains my default mail pattern. # # Values for sendmail.address=xx@zsu.edu.cnmail.send.Proto=Smtpmail.send.host=student.zsu.edu.cnmail. send.debug = true ## Values for receivingMail.receive.host = student.zsu.edu.cnMail.receive.protocol = pop3Mail.receive.user = xxMail.receive.pass = ASKMail.receive.root = d: / test / // Third, create a main program, generate the object of the MAILER class, set the parameter, and send an email in MAILER.JAVA. First Import: /// Import Java.io. *; Import Java.util. *; Import Javax.mail.internet. *; Import Javax.mail. *; Import Javax.Activation. *; /// Then use the following code to complete: /// Try {MAILER M = New MAILER (); FileProperties props = new FileProperties (MailConstants.PROPS_FILE_NAME); String serverHost = props.getProperty (MailConstants.SEND_HOST); if (serverHost == null) {System.out.println ( "/" " MailConstants.SEND_HOST " / "must Be set in proties "; system.exit (0);} m.setserver (serverhost); String TMP = Props.getProperty (MailConstants.send_debug); M.SETVERBOSE (TMP! = Null && tmp.equals ("true")); String myaddress = props.getProperty ("mail.address"); if (myaddress == null) {system.out.println ("/" mail.address / "must be set in proties); system.exit (0) } M.SetFrom (myaddress); // The following is set according to the specific situation: ========================================== ===== M.Settolist ("xx@zsu.edu.cn"); // Recipient M.SetcClist ("xx @ 163.com, yy @ 163.com"); // Cc, each An address is separated by a comma; or use an ArrayList's object as a parameter // m.set (); M.SetSubject ("demo"); // Theme // Now copy the text from the compose textarea. M.SetBody ("this is a demo"); // body // xxx i18n: use setbody (msgtext.getText (), charset) arraylist v = new arraylist (); v.add ("d: //test.htm"); m.setAccessories (V); // attachment // or above is set according to the specific situation =================== =============================================================================================================================================================================================================== } Catch (MessagingException me) {me.printStackTrace (); while (! (Me = (MessagingException) me.getNextException ()) = null) {me.printStackTrace ();} System.out.println ( "Mail Sending Error: / N " me.tostring ());} catch (exception ex) {system.out.println (" mail sending error: / n " ex. TString ());} /// fileproperties code> class extends
Properties code>, * "a personistent set of proties [That] Can Be Saved to a stream * or loaded from a stream." This subclass attends to all the mundane * details of opening the Stream (s) for actually saving and loading * the Properties. * *