KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > uk > org > primrose > web > 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 package uk.org.primrose.web;
22
23 import javax.mail.*;
24 import javax.mail.internet.*;
25 import java.util.*;
26 import java.io.*;
27 import javax.activation.*;
28
29 /**
30  * @author Ben Keeping
31  *
32  * Generic sendMail class, allows for sending emails with attachements.
33  */

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

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

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

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

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

161     public static void main(String JavaDoc args[]) throws Exception JavaDoc {
162         if (args.length < 5) {
163             System.out.println("Usuage :: <mxServer> <toAddress> <fromAddress> <subject> <text>");
164             System.exit(1);
165         }
166         //BufferedReader br1 = new BufferedReader(new FileReader("C:/email_list_primrose_2.4.txt"));
167
//String line1 = "";
168
//while ((line1 = br1.readLine()) != null) {
169
// args[1] = line1;
170

171             String JavaDoc text = "";
172             // Read in the text for the body ...
173
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(args[4])));
174             String JavaDoc line = "";
175             //System.err.println("Getting body of email ...");
176
while ((line = br.readLine()) != null) {
177                 text += line +"\n";
178             }
179
180             //String msgText = "";
181
// for (int i = 4; i < args.length; i++) {
182
// msgText += (" " +args[i]);
183
//}
184

185             new SendMail(args[0], args[1], args[2], args[3], text).send();
186         //}
187

188
189 /*
190 if (args.length < 5) {
191             System.out.println("Usuage :: <mxServer> <toAddress> <fromAddress> <subject> <text>");
192             System.exit(1);
193         }
194         BufferedReader br1 = new BufferedReader(new FileReader("C:/java/primrose/email_list_2.4.6.txt"));
195         String line1 = "";
196         while ((line1 = br1.readLine()) != null) {
197
198             System.err.println("Sending to : " +line1);
199
200             args[1] = line1;
201
202             String text = "";
203             // Read in the text for the body ...
204             BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(args[4])));
205             String line = "";
206             while ((line = br.readLine()) != null) {
207                 text += line +"\n";
208             }
209
210             //String msgText = "";
211             // for (int i = 4; i < args.length; i++) {
212             // msgText += (" " +args[i]);
213             //}
214
215             SendMail sm = new SendMail(args[0], args[1], args[2], args[3], text);
216             sm.attach(new File("C:/java/primrose/web/downloads/primrose.jar"));
217             sm.send();
218         }
219
220 */

221     }
222 }
223
Popular Tags