KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > uk > org > primrose > pool > jmx > SendMail


1 /**
2 * Library name : Primrose - A Java Database Connection Pool.
3 * Published by Ben Keeping, http://primrose.org.uk .
4 * Copyright (C) 2004 Ben Keeping, primrose.org.uk
5 * Email: Use "Contact Us Form" on website
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */

21
22 package uk.org.primrose.pool.jmx;
23
24 import javax.mail.*;
25 import javax.mail.internet.*;
26 import java.util.*;
27 import java.io.*;
28 import javax.activation.*;
29
30 /**
31  * @author Ben Keeping
32  *
33  * Generic sendMail class, allows for sending emails with attachements.
34  */

35 public class SendMail {
36     static String JavaDoc mxServer;
37     String JavaDoc toAddress, fromAddress;
38     String JavaDoc subject, text;
39     MimeBodyPart mbp = null;
40     Multipart mp = new MimeMultipart();
41
42
43     /**
44     * Construct an email. <BR>
45     * If the mxServer is unknown, then the static method SendMail.nslookup() can be called to retrieve the domain's mx server. <BR>
46     * Attachments are optional. <BR>
47     * @param String mxServer - The Mail eXchange server to send the mail to.
48     * @param String toAddress - The recipient.
49     * @param String fromAddress - The sender - can be anyting as long as looks like an email address - eg 'me@somewhere.com'.
50     * @param String subject - The mail's subject.
51     * @param String text - The body of the mail.
52     */

53     public SendMail(String JavaDoc mxServer, String JavaDoc toAddress, String JavaDoc fromAddress, String JavaDoc subject, String JavaDoc text) {
54         this.mxServer = mxServer;
55         this.toAddress = toAddress;
56         this.fromAddress = fromAddress;
57         this.subject = subject;
58         this.text = text;
59
60     }
61
62     /**
63     * Add an attachment to the mail (from a file on disk).
64     * @param File file - the File object to attach.
65     */

66     public void attach(File file) {
67         try {
68             mbp = new MimeBodyPart();
69             mbp.setFileName(file.getName());
70             mbp.setDataHandler(new DataHandler(new FileDataSource(file)));
71             mp.addBodyPart(mbp);
72         } catch (MessagingException me) {
73             me.printStackTrace();
74         }
75     }
76
77     /**
78     * Send a message using the contstructor properties.
79     * If there is also an attachment to send, add it too.
80     */

81     public void send() {
82         Properties props = System.getProperties();
83         props.put("mail.smtp.host", mxServer);
84         Session session = Session.getDefaultInstance(props, null);
85
86         try {
87             Message msg = new MimeMessage(session);
88             msg.setFrom(new InternetAddress(fromAddress));
89             msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress, false));
90             msg.setSubject(subject);
91             msg.setHeader("X-Mailer", "JavaMail");
92
93             // If there have been attachments (one or more), then set the text/body
94
// as a MimeBodyPart, else set it on the Message. If this isn't done,
95
// then either text or an attachment is sent - not both !
96
if (mbp != null) {
97                 MimeBodyPart mbp2 = new MimeBodyPart();
98                 mbp2.setText(text);
99                 mp.addBodyPart(mbp2);
100                 msg.setContent(mp);
101             } else {
102                 msg.setText(text);
103             }
104
105             Transport.send(msg);
106         } catch (AddressException ae) {
107             ae.printStackTrace();
108         } catch (MessagingException me) {
109             me.printStackTrace();
110         }
111     }
112
113     /**
114     * Given a domain name like 'hotmail.com', perform an OS nslookup call,
115     * and loop it, looking for the word 'exchanger' in the line. On Linux and Windoze
116     * the mx mail server is always the last word/token in the line, so set it as such.
117     * This pays no attention to the preference of which mx server to use, but could (and should !)
118     * be built in really. Still, never mind.
119     * @param String domain - the domain to lookup.
120     */

121     public static String JavaDoc nslookup(String JavaDoc domain) {
122         String JavaDoc mailserver = null;
123         try {
124             Process JavaDoc p = Runtime.getRuntime().exec("nslookup -type=mx " +domain);
125             BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
126
127             boolean gotMxLine = false;
128             String JavaDoc line = null;
129             String JavaDoc token = null;
130
131             while ((line = br.readLine()) != null) {
132                 gotMxLine = false;
133                 //System.out.println(line);
134
StringTokenizer st = new StringTokenizer(line);
135                 while (st.hasMoreTokens()) {
136                     token = st.nextToken();
137                     if (token.equals("exchanger")) {
138                         gotMxLine = true;
139                     }
140                     if (gotMxLine) {
141                         mailserver = token;
142                     }
143                 }
144
145             }
146         } catch (IOException ioe) {
147             ioe.printStackTrace();
148             return null;
149         }
150
151         System.out.println("Mail Server to use is :: " +mailserver);
152         return mailserver;
153     }
154
155   /**
156    * Method main.
157    * @param args
158    * Usuage :: <mxServer> <toAddress> <fromAddress> <subject> <text>
159    */

160     public static void main(String JavaDoc args[]) {
161         if (args.length < 5) {
162             System.out.println("Usuage :: <mxServer> <toAddress> <fromAddress> <subject> <text>");
163             System.exit(1);
164         }
165         String JavaDoc msgText = "";
166                 for (int i = 4; i < args.length; i++) {
167             msgText += (" " +args[i]);
168         }
169
170         new SendMail(args[0], args[1], args[2], args[3], msgText).send();
171     }
172 }
173
Popular Tags