001: /*
002: * The contents of this file are subject to the
003: * Mozilla Public License Version 1.1 (the "License");
004: * you may not use this file except in compliance with the License.
005: * You may obtain a copy of the License at http://www.mozilla.org/MPL/
006: *
007: * Software distributed under the License is distributed on an "AS IS"
008: * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
009: * See the License for the specific language governing rights and
010: * limitations under the License.
011: *
012: * The Initial Developer of the Original Code is Simulacra Media Ltd.
013: * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
014: *
015: * All Rights Reserved.
016: *
017: * Contributor(s):
018: */
019: package org.openharmonise.commons.net;
020:
021: import java.io.*;
022: import java.util.logging.*;
023: import java.util.logging.Level;
024:
025: import javax.activation.*;
026: import javax.mail.Multipart;
027: import javax.mail.internet.*;
028:
029: /**
030: *
031: * A convenience class to simplify the process of sending an email using
032: * the JavaMail API.
033: *
034: * @version $Revision: 1.2 $
035: *
036: */
037: public class Email extends Object {
038:
039: /**
040: * Plain text mime type
041: */
042: public static final String CTYPE_TXTPLAIN = "text/plain";
043:
044: /**
045: * HTML mime type
046: */
047: public static final String CTYPE_HTML = "text/html";
048:
049: /**
050: * Email importance header
051: */
052: protected static final String HEADER_IMPORTANCE = "Importance";
053:
054: /**
055: * Email importance header value of 'high'
056: */
057: public static final String IMPORTANCE_HIGH = "High";
058:
059: /**
060: * <code>boolean</code> flag indicating whether email has an attachment
061: */
062: private static boolean m_bAttachment = false;
063:
064: /**
065: * Importance header value
066: */
067: protected String m_sImportance = null;
068:
069: /**
070: * Email 'to' address
071: */
072: protected String to_address;
073:
074: /**
075: * Email 'from' address
076: */
077: protected String from_address;
078:
079: /**
080: * Email message text
081: */
082: protected String message_text;
083:
084: /**
085: * Email subject text
086: */
087: protected String subject_text;
088:
089: /**
090: * Email message mime type.
091: */
092: protected String message_contenttype = CTYPE_TXTPLAIN;
093:
094: /**
095: * Mail host for email.
096: */
097: protected String m_sMailhost = "";
098:
099: /**
100: * Attachment file.
101: */
102: protected File m_fAttachment = null;
103:
104: /**
105: * Logger for this class.
106: */
107: private static final Logger m_logger = Logger.getLogger(Email.class
108: .getName());
109:
110: /**
111: * The constructor allows you to create an email object. The object is then filled with all the information about the email, ie sender, reciever, subject and the actual message.
112: * The Email constructor does NOT send the message until the send method is called.
113: *
114: * @param mailhost - the mailhost to be used for email
115: * @param to_address - The email address of the RECIEVER , example: Mellon@yahoo.com
116: * @param from_address - The email address of the SENDER , example: Orange@hotmail.com
117: * @param subject_text - What the subject of the message is about
118: * @param message_text - The actual content of the message
119: */
120: public Email(String mailhost, String to_address,
121: String from_address, String subject_text,
122: String message_text) {
123: this .to_address = to_address;
124: this .from_address = from_address;
125: this .subject_text = subject_text;
126: this .message_text = message_text;
127: m_sMailhost = mailhost;
128: }
129:
130: /**
131: * The constructor allows you to create an email object. The object is then filled with all the information about the email, ie sender, reciever, subject and the actual message.
132: * The Email constructor does NOT send the message until the send method is called.
133: *
134: * @param mailhost - the mailhost to be used for email
135: * @param to_address - The email address of the RECIEVER , example: Mellon@yahoo.com
136: * @param from_address - The email address of the SENDER , example: Orange@hotmail.com
137: * @param subject_text - What the subject of the message is about
138: * @param message_text - The actual content of the message
139: */
140: public Email(String mailhost, String to_address,
141: String from_address, String subject_text,
142: String message_text, File attachment) throws Exception {
143: this .to_address = to_address;
144: this .from_address = from_address;
145: this .subject_text = subject_text;
146: this .message_text = message_text;
147: m_fAttachment = attachment;
148: m_bAttachment = true;
149: m_sMailhost = mailhost;
150: }
151:
152: /**
153: * This method will send all of the email details specified earlier
154: * when the email object was constructed.
155: * @return boolean - to say whether the msg was sent, or not.
156: */
157: public boolean send() {
158: try {
159: // create some properties and get the default Session
160: java.util.Properties props = new java.util.Properties();
161: String mail_host = m_sMailhost;
162: props.put("mail.smtp.host", mail_host);
163:
164: javax.mail.Session session = javax.mail.Session
165: .getInstance(props);
166:
167: if (!m_bAttachment) {
168: javax.mail.Message msg = new javax.mail.internet.MimeMessage(
169: session);
170:
171: if (m_sImportance != null) {
172: msg.setHeader(HEADER_IMPORTANCE, m_sImportance);
173: }
174:
175: msg.setFrom(new javax.mail.internet.InternetAddress(
176: from_address));
177:
178: msg.setRecipient(javax.mail.Message.RecipientType.TO,
179: new javax.mail.internet.InternetAddress(
180: to_address));
181: msg.setSubject(subject_text);
182: msg.setSentDate(new java.util.Date());
183:
184: msg.setContent(message_text, message_contenttype);
185:
186: javax.mail.Transport.send(msg);
187: } else {
188: // Define message from this session
189: MimeMessage msg = new MimeMessage(session);
190:
191: if (m_sImportance != null) {
192: msg.setHeader(HEADER_IMPORTANCE, m_sImportance);
193: }
194:
195: msg.setFrom(new javax.mail.internet.InternetAddress(
196: from_address));
197:
198: msg.setRecipient(javax.mail.Message.RecipientType.TO,
199: new javax.mail.internet.InternetAddress(
200: to_address));
201:
202: // set what the subject of this mail is about
203: msg.setSubject(subject_text);
204:
205: // create the messageBodypart , Its an object that is done in parts
206: // the mail text, and the attachments, these form the whole message
207: MimeBodyPart messageBodyPart = new MimeBodyPart();
208:
209: //**** Part one - Add the text to the email
210: //fill message (with the text)
211: messageBodyPart.setText(message_text);
212:
213: // create a mulipart object of which to compose the whole email from
214: // Think of it as some sort of email object VECTOR
215: // the first part to add is the message
216: Multipart multipart = new MimeMultipart();
217:
218: // add the text to the mutipart object
219: multipart.addBodyPart(messageBodyPart);
220:
221: //**** Part two is attachment (ie the file)
222: // reinitialise the messageBodyPart object
223: MimeBodyPart messageBodyPart2 = new MimeBodyPart();
224:
225: // get the data source(ie attachment path)
226: FileDataSource source = new FileDataSource(
227: this .m_fAttachment);
228:
229: //FileDataSource source = new FileDataSource(fileAttachment);
230: messageBodyPart2
231: .setDataHandler(new DataHandler(source));
232:
233: // set the name of the attachment
234: messageBodyPart2.setFileName(source.getName());
235:
236: // add the message body part to the mulipart (or email)
237: multipart.addBodyPart(messageBodyPart2);
238:
239: // Put the msg content to be the multipart to form the complete email
240: // dont forget that the multipart object by now should contain the text of the email as well as
241: // the attachment file
242: msg.setContent(multipart);
243:
244: // send the email
245: javax.mail.Transport.send(msg);
246: }
247: } catch (Exception e) {
248:
249: return false;
250: }
251:
252: return true;
253: }
254:
255: /**
256: * Debug method which will build a description of steps executed during
257: * the emailing process.
258: *
259: * @return description of process
260: */
261: public String testSend() {
262: StringWriter sw = new StringWriter();
263: PrintWriter err_out = new PrintWriter(sw);
264:
265: try {
266: // create some properties and get the default Session
267: java.util.Properties props = new java.util.Properties();
268: String mail_host = m_sMailhost;
269: err_out.println("Using mail_host:" + mail_host + "<br>");
270:
271: props.put("mail.smtp.host", mail_host);
272:
273: javax.mail.Session session = javax.mail.Session
274: .getDefaultInstance(props, null);
275: err_out.println("created mail session:" + props + "<br>");
276:
277: try {
278: // create a message
279: javax.mail.Message msg = new javax.mail.internet.MimeMessage(
280: session);
281: err_out.println("created mail msg:" + msg + "<br>");
282:
283: msg.setFrom(new javax.mail.internet.InternetAddress(
284: from_address));
285: err_out.println("setFrom:" + from_address + "<br>");
286:
287: msg.setRecipient(javax.mail.Message.RecipientType.TO,
288: new javax.mail.internet.InternetAddress(
289: to_address));
290: err_out.println("setRecipient:" + to_address + "<br>");
291:
292: msg.setSubject(subject_text);
293: err_out.println("setSubject:" + subject_text + "<br>");
294:
295: msg.setSentDate(new java.util.Date());
296: err_out.println("setSentDate." + "<br>");
297:
298: msg.setContent(message_text, message_contenttype);
299:
300: err_out.println("setText:" + message_text + "<br>");
301: err_out.println("setContent:" + message_contenttype
302: + "<br>");
303:
304: javax.mail.Transport.send(msg);
305: err_out.println("sent mail." + "<br>");
306: } catch (javax.mail.MessagingException mex) {
307: err_out.println("\n--Exception handling for mail"
308: + "<br>");
309:
310: m_logger.log(Level.WARNING, mex.getLocalizedMessage(),
311: mex);
312:
313: Exception ex = mex;
314:
315: do {
316: if (ex instanceof javax.mail.SendFailedException) {
317: javax.mail.SendFailedException sfex = (javax.mail.SendFailedException) ex;
318: javax.mail.Address[] invalid = sfex
319: .getInvalidAddresses();
320:
321: if (invalid != null) {
322: err_out.println(" ** Invalid Addresses"
323: + "<br>");
324:
325: if (invalid != null) {
326: for (int i = 0; i < invalid.length; i++)
327: err_out.println(" "
328: + invalid[i] + "<br>");
329: }
330: }
331:
332: javax.mail.Address[] validUnsent = sfex
333: .getValidUnsentAddresses();
334:
335: if (validUnsent != null) {
336: err_out
337: .println(" ** ValidUnsent Addresses"
338: + "<br>");
339:
340: if (validUnsent != null) {
341: for (int i = 0; i < validUnsent.length; i++)
342: err_out.println(" "
343: + validUnsent[i] + "<br>");
344: }
345: }
346:
347: javax.mail.Address[] validSent = sfex
348: .getValidSentAddresses();
349:
350: if (validSent != null) {
351: err_out
352: .println(" ** ValidSent Addresses"
353: + "<br>");
354:
355: if (validSent != null) {
356: for (int i = 0; i < validSent.length; i++)
357: err_out.println(" "
358: + validSent[i] + "<br>");
359: }
360: }
361: }
362:
363: err_out.println("<br>");
364: } while ((ex = ((javax.mail.MessagingException) ex)
365: .getNextException()) != null);
366: }
367: } catch (Exception e) {
368: err_out.println("Exception sending mail:" + e.getMessage()
369: + "<br>");
370: err_out.println();
371: err_out.println("Stacktrace follows:" + "<br>");
372: e.printStackTrace(err_out);
373: } finally {
374: if (err_out != null) {
375: err_out.close();
376: }
377: }
378:
379: return sw.toString();
380: }
381:
382: /**
383: * This method will change the email Address of where the message is GOING.
384: * ie to who the message is being SENT.
385: *
386: * @param new_email_address the address of where the email is going : example mellon2@yahoo.com
387: */
388: public void SetEmailAddress(String new_email_address) {
389: this .to_address = new_email_address;
390:
391: return;
392: }
393:
394: /**
395: * This method will change the content type.
396: */
397: public void SetContentType(String content_type) {
398: content_type = content_type.trim();
399:
400: if (content_type.equals(Email.CTYPE_HTML)
401: || content_type.equals(Email.CTYPE_TXTPLAIN)) {
402: this .message_contenttype = content_type;
403: } else {
404: throw new RuntimeException("Cannot set content type to:"
405: + content_type + ", allowed values are:"
406: + CTYPE_HTML + " " + CTYPE_TXTPLAIN);
407: }
408: }
409:
410: /**
411: * Sets the importance heading of the email.
412: *
413: * @param sImportance
414: */
415: public void setImportance(String sImportance) {
416: m_sImportance = sImportance;
417: }
418: }
|