001: /**
002: * Copyright (C) 2006, 2007 David Bulmore, Software Sensation Inc.
003: * All Rights Reserved.
004: *
005: * This file is part of jWebTk.
006: *
007: * jWebTk is free software; you can redistribute it and/or modify it under
008: * the terms of the GNU General Public License (Version 2) as published by
009: * the Free Software Foundation.
010: *
011: * jWebTk is distributed in the hope that it will be useful, but WITHOUT
012: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014: * for more details.
015: *
016: * You should have received a copy of the GNU General Public License
017: * along with jWebTk; if not, write to the Free Software Foundation,
018: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
019: */package jwebtk.mail;
020:
021: import com.sun.mail.smtp.SMTPMessage;
022: import com.sun.mail.smtp.SMTPTransport;
023: import java.io.File;
024: import java.net.URL;
025: import java.util.Date;
026: import java.util.Properties;
027: import java.util.Vector;
028: import javax.activation.DataHandler;
029: import javax.activation.FileDataSource;
030: import javax.mail.Address;
031: import javax.mail.Authenticator;
032: import javax.mail.BodyPart;
033: import javax.mail.Message;
034: import javax.mail.PasswordAuthentication;
035: import javax.mail.Session;
036: import javax.mail.URLName;
037: import javax.mail.internet.InternetAddress;
038: import javax.mail.internet.MimeBodyPart;
039: import javax.mail.internet.MimeMultipart;
040:
041: /**
042: * Handles sending emails via any SMTP server. EmailSender can handle plain
043: * text and/or HTML messages, any number of: send tos, cc tos, bcc tos, reply tos,
044: * and any number of attachments.
045: */
046:
047: @SuppressWarnings("unchecked")
048: // working to complete a Java 1.5 version
049: public class EmailSender {
050: Session session;
051: SMTPMessage message;
052: int port = -1;
053: String smtp_host, user_id, password;
054: Vector send_to = new Vector(), send_cc = new Vector(),
055: send_bcc = new Vector(), reply_to = new Vector(),
056: body_objects = new Vector();
057:
058: /**
059: * Create instance of EmailSender.
060: *
061: * @param smtpHost the domain or IP address of the SMTP host
062: */
063:
064: public EmailSender(String smtpHost) {
065: this .smtp_host = smtpHost;
066:
067: Properties props = new Properties();
068:
069: session = Session.getDefaultInstance(props, null);
070: message = new SMTPMessage(session);
071: }
072:
073: /**
074: * Create instance of EmailSender.
075: *
076: * @param smtpHost the domain or IP address of the SMTP host
077: * @param userId Authenticate with userId
078: * @param password Authenticate with password
079: */
080:
081: public EmailSender(String smtpHost, String userId, String password) {
082: this .smtp_host = smtpHost;
083: this .user_id = userId;
084: this .password = password;
085:
086: Properties props = new Properties();
087:
088: props.put("mail.smtp.auth", "true");
089:
090: session = Session.getDefaultInstance(props,
091: new MyAuthenticator(userId, password));
092:
093: message = new SMTPMessage(session);
094: }
095:
096: /**
097: * Create instance of EmailSender.
098: *
099: * @param smtpHost the domain or IP address of the SMTP host
100: * @param port the port the SMTP host is running on
101: * @param userId Authenticate with userId
102: * @param password Authenticate with password
103: */
104:
105: public EmailSender(String smtpHost, int port, String userId,
106: String password) {
107: this .smtp_host = smtpHost;
108: this .port = port;
109: this .user_id = userId;
110: this .password = password;
111:
112: Properties props = new Properties();
113:
114: props.put("mail.smtp.auth", "true");
115:
116: session = Session.getDefaultInstance(props,
117: new MyAuthenticator(userId, password));
118:
119: message = new SMTPMessage(session);
120: }
121:
122: class MyAuthenticator extends Authenticator {
123: PasswordAuthentication pa;
124:
125: MyAuthenticator(String userId, String password) {
126: pa = new PasswordAuthentication(userId, password);
127: }
128:
129: public PasswordAuthentication getPasswordAuthentication() {
130: return pa;
131: }
132: }
133:
134: /**
135: * Turns debugging on or off.
136: *
137: * @param debug true if debugging, false if not.
138: */
139: public void setDebug(boolean debug) {
140: session.setDebug(debug);
141: }
142:
143: /**
144: * Return the actual JavaMail Session object.
145: *
146: * @return session object
147: */
148: public Session getJavaMailSession() {
149: return session;
150: }
151:
152: /**
153: * Return the actual JavaMail Message object.
154: */
155: public Message getJavaMailMessage() {
156: return message;
157: }
158:
159: /**
160: * Add a send to address to the email.
161: *
162: * @param address address to send the email to
163: */
164: public void addSendTo(String address) throws EmailSenderException {
165: try {
166: send_to.addElement(new InternetAddress(address));
167: } catch (Exception e) {
168: throw new EmailSenderException(e);
169: }
170: }
171:
172: /**
173: * Add a send to address to the email.
174: *
175: * @param address address to send the email to
176: * @param name associate address with name
177: */
178: public void addSendTo(String address, String name)
179: throws EmailSenderException {
180: try {
181: send_to.addElement(new InternetAddress(address, name));
182: } catch (Exception e) {
183: throw new EmailSenderException(e);
184: }
185: }
186:
187: /**
188: * Add a CC to address to the email.
189: *
190: * @param address address to CC the email to
191: */
192: public void addCCTo(String address) throws EmailSenderException {
193: try {
194: send_cc.addElement(new InternetAddress(address));
195: } catch (Exception e) {
196: throw new EmailSenderException(e);
197: }
198: }
199:
200: /**
201: * Add a CC to address to the email.
202: *
203: * @param address address to CC the email to
204: * @param name associate address with name
205: */
206: public void addCCTo(String address, String name)
207: throws EmailSenderException {
208: try {
209: send_cc.addElement(new InternetAddress(address, name));
210: } catch (Exception e) {
211: throw new EmailSenderException(e);
212: }
213: }
214:
215: /**
216: * Add a BCC to address to the email.
217: *
218: * @param address address to BCC the email to
219: */
220: public void addBCCTo(String address) throws EmailSenderException {
221: try {
222: send_bcc.addElement(new InternetAddress(address));
223: } catch (Exception e) {
224: throw new EmailSenderException(e);
225: }
226: }
227:
228: /**
229: * Add a BCC to address to the email.
230: *
231: * @param address address to BCC the email to
232: * @param name associate address with name
233: */
234: public void addBCCTo(String address, String name)
235: throws EmailSenderException {
236: try {
237: send_bcc.addElement(new InternetAddress(address, name));
238: } catch (Exception e) {
239: throw new EmailSenderException(e);
240: }
241: }
242:
243: /**
244: * Add a replay to address to the email.
245: *
246: * @param address address to reply to
247: */
248: public void addReplyTo(String address) throws EmailSenderException {
249: try {
250: reply_to.addElement(new InternetAddress(address));
251: } catch (Exception e) {
252: throw new EmailSenderException(e);
253: }
254: }
255:
256: /**
257: * Add a replay to address to the email.
258: *
259: * @param address address to reply to
260: * @param name associate address with name
261: */
262: public void addReplyTo(String address, String name)
263: throws EmailSenderException {
264: try {
265: reply_to.addElement(new InternetAddress(address, name));
266: } catch (Exception e) {
267: throw new EmailSenderException(e);
268: }
269: }
270:
271: /**
272: * Set the from address for the email.
273: *
274: * @param address address from
275: */
276: public void setSentFrom(String address) throws EmailSenderException {
277: try {
278: message.setFrom(new InternetAddress(address));
279: } catch (Exception e) {
280: throw new EmailSenderException(e);
281: }
282: }
283:
284: /**
285: * Set the from address for the email.
286: *
287: * @param address address from
288: * @param name associate address with name
289: */
290: public void setSentFrom(String address, String name)
291: throws EmailSenderException {
292: try {
293: message.setFrom(new InternetAddress(address, name));
294: } catch (Exception e) {
295: throw new EmailSenderException(e);
296: }
297: }
298:
299: /**
300: * Add HTML to the email.
301: *
302: * @param htmlMessage the HTML message
303: */
304: public void addHtml(String htmlMessage) {
305: body_objects.addElement(new BodyObject("htmlMessage",
306: htmlMessage, null, BodyObject.HTML, true));
307: }
308:
309: /**
310: * Add a text message to the email.
311: *
312: * @param textMessage the text message
313: */
314: public void addText(String textMessage) {
315: body_objects.addElement(new BodyObject("textMessage",
316: textMessage, null, BodyObject.TEXT, false));
317: }
318:
319: /**
320: * Add an attachment to the email.
321: *
322: * @param name attachments name (simple filename, example: file.txt)
323: * @param filename the attachment file path
324: * @param description a description for the attachment
325: * @param inline is the attachment inline
326: */
327: public void addAttachment(String name, String filename,
328: String description, boolean inline) {
329: body_objects.addElement(new BodyObject(name,
330: new File(filename), description, BodyObject.ATTACHMENT,
331: inline));
332: }
333:
334: /**
335: * Add an attachment to the email.
336: *
337: * @param name attachments name (simple filename, example: file.txt)
338: * @param file the attachment file path
339: * @param description a description for the attachment
340: * @param inline is the attachment inline
341: */
342: public void addAttachment(String name, File file,
343: String description, boolean inline) {
344: body_objects.addElement(new BodyObject(name, file, description,
345: BodyObject.ATTACHMENT, inline));
346: }
347:
348: /**
349: * Add an attachment to the email.
350: *
351: * @param name attachments name (simple filename, example: file.txt)
352: * @param url URL to the attachment
353: * @param description a description for the attachment
354: * @param inline is the attachment inline
355: */
356: public void addAttachment(String name, URL url, String description,
357: boolean inline) {
358: body_objects.addElement(new BodyObject(name, url, description,
359: BodyObject.ATTACHMENT, inline));
360: }
361:
362: /**
363: * Set the subject of the email message.
364: *
365: * @param subject the subject of the email
366: */
367: public void setSubject(String subject) throws EmailSenderException {
368: try {
369: message.setSubject(subject);
370: } catch (Exception e) {
371: throw new EmailSenderException(e);
372: }
373: }
374:
375: /**
376: * Send the email.
377: */
378: public void sendEmail() throws EmailSenderException {
379: try {
380: if (send_to.size() > 0)
381: message.setRecipients(Message.RecipientType.TO,
382: (Address[]) send_to.toArray(new Address[send_to
383: .size()]));
384:
385: if (send_cc.size() > 0)
386: message.setRecipients(Message.RecipientType.CC,
387: (Address[]) send_cc.toArray(new Address[send_cc
388: .size()]));
389:
390: if (send_bcc.size() > 0)
391: message.setRecipients(Message.RecipientType.BCC,
392: (Address[]) send_bcc
393: .toArray(new Address[send_bcc.size()]));
394:
395: if (reply_to.size() > 0)
396: message.setReplyTo((Address[]) reply_to
397: .toArray(new Address[reply_to.size()]));
398:
399: message.setContent(buildMultiPartContent());
400:
401: message.setSendPartial(true);
402: message.setSentDate(new Date());
403: message.saveChanges();
404:
405: SMTPTransport t = new SMTPTransport(session, new URLName(
406: "smtp", smtp_host, port, null, user_id, password));
407:
408: t.connect();
409: t.sendMessage(message, message.getAllRecipients());
410: t.close();
411: } catch (Exception e) {
412: throw new EmailSenderException(e);
413: }
414: }
415:
416: MimeMultipart buildMultiPartContent() throws EmailSenderException {
417: MimeMultipart mp = new MimeMultipart();
418:
419: try {
420: for (int i = 0; i < body_objects.size(); i++) {
421: BodyObject body_obj = (BodyObject) body_objects
422: .elementAt(i);
423: MimeBodyPart body_part = new MimeBodyPart();
424:
425: if (body_obj.object_type == BodyObject.TEXT)
426: body_part.setContent((String) body_obj.object,
427: "text/plain");
428: else if (body_obj.object_type == BodyObject.HTML)
429: body_part.setContent(body_obj.object, "text/html");
430: else {
431: if (body_obj.object instanceof File)
432: body_part.setDataHandler(new DataHandler(
433: new FileDataSource(
434: (File) body_obj.object)));
435: else if (body_obj.object instanceof URL)
436: body_part.setDataHandler(new DataHandler(
437: (URL) body_obj.object));
438:
439: body_part.setFileName(body_obj.name);
440: body_part.setDescription(body_obj.description);
441: body_part.setContentID("<" + body_obj.name + ">");
442: body_part
443: .setDisposition(body_obj.in_line ? BodyPart.INLINE
444: : BodyPart.ATTACHMENT);
445: }
446:
447: mp.addBodyPart(body_part);
448: }
449: } catch (Exception e) {
450: throw new EmailSenderException(e);
451: }
452:
453: return mp;
454: }
455:
456: class BodyObject {
457: static final int TEXT = 1;
458: static final int HTML = 2;
459: static final int ATTACHMENT = 3;
460: static final int EMBEDDED = 4;
461:
462: Object object;
463: String description, name;
464: int object_type;
465: boolean in_line;
466:
467: public BodyObject(String name, Object object,
468: String description, int objectType, boolean inLine) {
469: this .name = name;
470: this .object = object;
471: this .description = description;
472: this .object_type = objectType;
473: this .in_line = inLine;
474: }
475: }
476:
477: /**
478: * Convenience method for sending simple emails.
479: *
480: * @param host the email server host address
481: * @param addressFrom the email address the email is being sent from
482: * @param addressTo the email address the email is being sent to
483: * @param subject the subject of the email
484: * @param message the email message
485: */
486: public static void sendEmail(String host,
487: InternetAddress addressFrom, InternetAddress addressTo,
488: String subject, String message) throws EmailSenderException {
489: EmailSender email = new EmailSender(host);
490:
491: email.setSentFrom(addressFrom.getAddress(), addressFrom
492: .getPersonal());
493: email
494: .addSendTo(addressTo.getAddress(), addressTo
495: .getPersonal());
496: email.setSubject(subject);
497: email.addText(message);
498:
499: email.sendEmail();
500: }
501:
502: /**
503: * Convenience method for sending simple emails.
504: *
505: * @param host the email server host address
506: * @param userId the userid for the email host
507: * @param password the password for the email host
508: * @param addressFrom the email address the email is being sent from
509: * @param addressTo the email address the email is being sent to
510: * @param subject the subject of the email
511: * @param message the email message
512: */
513: public static void sendEmail(String host, String userId,
514: String password, InternetAddress addressFrom,
515: InternetAddress addressTo, String subject, String message)
516: throws EmailSenderException {
517: EmailSender email = new EmailSender(host, userId, password);
518:
519: email.setSentFrom(addressFrom.getAddress(), addressFrom
520: .getPersonal());
521: email
522: .addSendTo(addressTo.getAddress(), addressTo
523: .getPersonal());
524: email.setSubject(subject);
525: email.addText(message);
526:
527: email.sendEmail();
528: }
529:
530: /**
531: * Convenience method for sending simple emails.
532: *
533: * @param addressFrom the email address the email is being sent from
534: * @param addressTo the email address the email is being sent to
535: * @param subject the subject of the email
536: * @param message the email message
537: */
538: public static void sendEmail(InternetAddress addressFrom,
539: InternetAddress addressTo, String subject, String message)
540: throws EmailSenderException {
541: sendEmail("localhost", addressFrom, addressTo, subject, message);
542: }
543:
544: /**
545: * Convenience method for sending simple emails.
546: *
547: * @param host the email server host address
548: * @param addressFrom the email address the email is being sent from
549: * @param fromName the name of the email sender
550: * @param addressTo the email address the email is being sent to
551: * @param toName the name the email is being sent to
552: * @param subject the subject of the email
553: * @param message the email message
554: */
555: public static void sendEmail(String host, String addressFrom,
556: String fromName, String addressTo, String toName,
557: String subject, String message) throws EmailSenderException {
558: try {
559: sendEmail(host, new InternetAddress(addressFrom, fromName),
560: new InternetAddress(addressTo, toName), subject,
561: message);
562: } catch (Exception e) {
563: throw new EmailSenderException(e);
564: }
565: }
566:
567: /**
568: * Convenience method for sending simple emails.
569: *
570: * @param host the email server host address
571: * @param userId the userid for the email host
572: * @param password the password for the email host
573: * @param addressFrom the email address the email is being sent from
574: * @param fromName the name of the email sender
575: * @param addressTo the email address the email is being sent to
576: * @param toName the name the email is being sent to
577: * @param subject the subject of the email
578: * @param message the email message
579: */
580: public static void sendEmail(String host, String userId,
581: String password, String addressFrom, String fromName,
582: String addressTo, String toName, String subject,
583: String message) throws EmailSenderException {
584: try {
585: sendEmail(host, userId, password, new InternetAddress(
586: addressFrom, fromName), new InternetAddress(
587: addressTo, toName), subject, message);
588: } catch (Exception e) {
589: throw new EmailSenderException(e);
590: }
591: }
592:
593: /**
594: * Convenience method for sending simple emails.
595: *
596: * @param addressFrom the email address the email is being sent from
597: * @param fromName the name of the email sender
598: * @param addressTo the email address the email is being sent to
599: * @param toName the name the email is being sent to
600: * @param subject the subject of the email
601: * @param message the email message
602: */
603: public static void sendEmail(String addressFrom, String fromName,
604: String addressTo, String toName, String subject,
605: String message) throws EmailSenderException {
606: try {
607: sendEmail("localhost", new InternetAddress(addressFrom,
608: fromName), new InternetAddress(addressTo, toName),
609: subject, message);
610: } catch (Exception e) {
611: throw new EmailSenderException(e);
612: }
613: }
614:
615: public static void main(String[] args) {
616: EmailSender es = new EmailSender("mail.basicisp.net");
617:
618: es.setDebug(true);
619:
620: try {
621: es.addSendTo("david@bulmore.net", "David Bulmore");
622: es.addSendTo("sfeds@bulmore.net", "asdf sdvfs");
623: es.addReplyTo("daveb@softwaresensation.com",
624: "David Bulmore");
625: es.setSentFrom("dlb@softwaresensation.com", "DBulmore");
626: es.setSubject("Still testing");
627:
628: String html = "<html><body><h1>This is a test message</h1>"
629: + "<b>This is a test <img src='cid:image'> message</b></html></body>";
630:
631: es.addHtml(html);
632:
633: es.addAttachment("image",
634: "/work/SoftwareSensation/images/logo_2_200x70.jpg",
635: "This is a test", false);
636: es
637: .addHtml("<html><body><h1>This is a test message</h1></body></html>");
638:
639: for (int i = 0; i < 20; i++)
640: es.sendEmail();
641: } catch (Exception e) {
642: e.printStackTrace();
643: }
644: }
645: }
|