Source Code Cross Referenced for Email.java in  » Net » apache-common-Email » org » apache » commons » mail » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Net » apache common Email » org.apache.commons.mail 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Copyright 2001-2005 The Apache Software Foundation
003:         *
004:         * Licensed under the Apache License, Version 2.0 (the "License");
005:         * you may not use this file except in compliance with the License.
006:         * You may obtain a copy of the License at
007:         *
008:         *     http://www.apache.org/licenses/LICENSE-2.0
009:         *
010:         * Unless required by applicable law or agreed to in writing, software
011:         * distributed under the License is distributed on an "AS IS" BASIS,
012:         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013:         * See the License for the specific language governing permissions and
014:         * limitations under the License.
015:         */
016:        package org.apache.commons.mail;
017:
018:        import java.util.ArrayList;
019:        import java.util.Collection;
020:        import java.util.Date;
021:        import java.util.HashMap;
022:        import java.util.Iterator;
023:        import java.util.List;
024:        import java.util.Map;
025:        import java.util.Properties;
026:
027:        import javax.mail.Authenticator;
028:        import javax.mail.Message;
029:        import javax.mail.MessagingException;
030:        import javax.mail.Session;
031:        import javax.mail.Store;
032:        import javax.mail.Transport;
033:        import javax.mail.internet.InternetAddress;
034:        import javax.mail.internet.MimeMessage;
035:        import javax.mail.internet.MimeMultipart;
036:
037:        /**
038:         * The base class for all email messages.  This class sets the
039:         * sender's email & name, receiver's email & name, subject, and the
040:         * sent date.  Subclasses are responsible for setting the message
041:         * body.
042:         *
043:         * @since 1.0
044:         * @author <a href="mailto:quintonm@bellsouth.net">Quinton McCombs</a>
045:         * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
046:         * @author <a href="mailto:frank.kim@clearink.com">Frank Y. Kim</a>
047:         * @author <a href="mailto:bmclaugh@algx.net">Brett McLaughlin</a>
048:         * @author <a href="mailto:greg@shwoop.com">Greg Ritter</a>
049:         * @author <a href="mailto:unknown">Regis Koenig</a>
050:         * @author <a href="mailto:colin.chalmers@maxware.nl">Colin Chalmers</a>
051:         * @author <a href="mailto:matthias@wessendorf.net">Matthias Wessendorf</a>
052:         * @author <a href="mailto:corey.scott@gmail.com">Corey Scott</a>
053:         * @version $Revision: 279295 $ $Date: 2005-09-07 12:56:41 +0200 (Wed, 07 Sep 2005) $
054:         * @version $Id: Email.java 279295 2005-09-07 10:56:41Z henning $
055:         */
056:        public abstract class Email {
057:            /** Constants used by Email classes. */
058:
059:            /** */
060:            public static final String SENDER_EMAIL = "sender.email";
061:            /** */
062:            public static final String SENDER_NAME = "sender.name";
063:            /** */
064:            public static final String RECEIVER_EMAIL = "receiver.email";
065:            /** */
066:            public static final String RECEIVER_NAME = "receiver.name";
067:            /** */
068:            public static final String EMAIL_SUBJECT = "email.subject";
069:            /** */
070:            public static final String EMAIL_BODY = "email.body";
071:            /** */
072:            public static final String CONTENT_TYPE = "content.type";
073:
074:            /** */
075:            public static final String MAIL_HOST = "mail.host";
076:            /** */
077:            public static final String MAIL_PORT = "mail.smtp.port";
078:            /** */
079:            public static final String MAIL_SMTP_FROM = "mail.smtp.from";
080:            /** */
081:            public static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
082:            /** */
083:            public static final String MAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol";
084:            /** */
085:            public static final String SMTP = "smtp";
086:            /** */
087:            public static final String TEXT_HTML = "text/html";
088:            /** */
089:            public static final String TEXT_PLAIN = "text/plain";
090:            /** */
091:            public static final String ATTACHMENTS = "attachments";
092:            /** */
093:            public static final String FILE_SERVER = "file.server";
094:            /** */
095:            public static final String MAIL_DEBUG = "mail.debug";
096:
097:            /** */
098:            public static final String KOI8_R = "koi8-r";
099:            /** */
100:            public static final String ISO_8859_1 = "iso-8859-1";
101:            /** */
102:            public static final String US_ASCII = "us-ascii";
103:
104:            /** The email message to send. */
105:            protected MimeMessage message;
106:
107:            /** The charset to use for this message */
108:            protected String charset;
109:
110:            /** The Address of the sending party, mandatory */
111:            protected InternetAddress fromAddress;
112:
113:            /** The Subject  */
114:            protected String subject;
115:
116:            /** An attachment  */
117:            protected MimeMultipart emailBody;
118:
119:            /** The content  */
120:            protected Object content;
121:
122:            /** The content type  */
123:            protected String contentType;
124:
125:            /** Set session debugging on or off */
126:            protected boolean debug;
127:
128:            /** Sent date */
129:            protected Date sentDate;
130:
131:            /**
132:             * Instance of an <code>Authenticator</code> object that will be used
133:             * when authentication is requested from the mail server.
134:             */
135:            protected Authenticator authenticator;
136:
137:            /**
138:             * The hostname of the mail server with which to connect. If null will try
139:             * to get property from system.properties. If still null, quit
140:             */
141:            protected String hostName;
142:
143:            /**
144:             * The port number of the mail server to connect to.
145:             * Defaults to the standard port ( 25 ).
146:             */
147:            protected String smtpPort = "25";
148:
149:            /** List of "to" email adresses */
150:            protected List toList = new ArrayList();
151:
152:            /** List of "cc" email adresses */
153:            protected List ccList = new ArrayList();
154:
155:            /** List of "bcc" email adresses */
156:            protected List bccList = new ArrayList();
157:
158:            /** List of "replyTo" email adresses */
159:            protected List replyList = new ArrayList();
160:
161:            /**
162:             * Address to which undeliverable mail should be sent.
163:             * Because this is handled by JavaMail as a String property
164:             * in the mail session, this property is of type <code>String</code>
165:             * rather than <code>InternetAddress</code>.
166:             */
167:            protected String bounceAddress;
168:
169:            /**
170:             * Used to specify the mail headers.  Example:
171:             *
172:             * X-Mailer: Sendmail, X-Priority: 1( highest )
173:             * or  2( high ) 3( normal ) 4( low ) and 5( lowest )
174:             * Disposition-Notification-To: user@domain.net
175:             */
176:            protected Map headers = new HashMap();
177:
178:            /**
179:             * Used to determine whether to use pop3 before smtp, and if so the settings.
180:             */
181:            protected boolean popBeforeSmtp;
182:            /** the host name of the pop3 server */
183:            protected String popHost;
184:            /** the user name to log into the pop3 server */
185:            protected String popUsername;
186:            /** the password to log into the pop3 server */
187:            protected String popPassword;
188:
189:            /** The Session to mail with */
190:            private Session session;
191:
192:            /**
193:             * Setting to true will enable the display of debug information.
194:             *
195:             * @param d A boolean.
196:             * @since 1.0
197:             */
198:            public void setDebug(boolean d) {
199:                this .debug = d;
200:            }
201:
202:            /**
203:             * Sets the userName and password if authentication is needed.  If this
204:             * method is not used, no authentication will be performed.
205:             * <p>
206:             * This method will create a new instance of
207:             * <code>DefaultAuthenticator</code> using the supplied parameters.
208:             *
209:             * @param userName User name for the SMTP server
210:             * @param password password for the SMTP server
211:             * @see DefaultAuthenticator
212:             * @see #setAuthenticator
213:             * @since 1.0
214:             */
215:            public void setAuthentication(String userName, String password) {
216:                this .authenticator = new DefaultAuthenticator(userName,
217:                        password);
218:                this .setAuthenticator(this .authenticator);
219:            }
220:
221:            /**
222:             * Sets the <code>Authenticator</code> to be used when authentication
223:             * is requested from the mail server.
224:             * <p>
225:             * This method should be used when your outgoing mail server requires
226:             * authentication.  Your mail server must also support RFC2554.
227:             *
228:             * @param newAuthenticator the <code>Authenticator</code> object.
229:             * @see Authenticator
230:             * @since 1.0
231:             */
232:            public void setAuthenticator(Authenticator newAuthenticator) {
233:                this .authenticator = newAuthenticator;
234:            }
235:
236:            /**
237:             * Set the charset of the message.
238:             *
239:             * @param newCharset A String.
240:             * @since 1.0
241:             */
242:            public void setCharset(String newCharset) {
243:                this .charset = newCharset;
244:            }
245:
246:            /**
247:             * Set the emailBody to a MimeMultiPart
248:             *
249:             * @param aMimeMultipart aMimeMultipart
250:             * @since 1.0
251:             */
252:            public void setContent(MimeMultipart aMimeMultipart) {
253:                this .emailBody = aMimeMultipart;
254:            }
255:
256:            /**
257:             * Set the content & contentType
258:             *
259:             * @param   aObject aObject
260:             * @param   aContentType aContentType
261:             * @since 1.0
262:             */
263:            public void setContent(Object aObject, String aContentType) {
264:                this .content = aObject;
265:                if (EmailUtils.isEmpty(aContentType)) {
266:                    this .contentType = null;
267:                } else {
268:                    // set the content type
269:                    this .contentType = aContentType;
270:
271:                    // set the charset if the input was properly formed
272:                    String strMarker = "; charset=";
273:                    int charsetPos = aContentType.toLowerCase().indexOf(
274:                            strMarker);
275:
276:                    if (charsetPos != -1) {
277:                        // find the next space (after the marker)
278:                        charsetPos += strMarker.length();
279:                        int intCharsetEnd = aContentType.toLowerCase().indexOf(
280:                                " ", charsetPos);
281:
282:                        if (intCharsetEnd != -1) {
283:                            this .charset = aContentType.substring(charsetPos,
284:                                    intCharsetEnd);
285:                        } else {
286:                            this .charset = aContentType.substring(charsetPos);
287:                        }
288:                    }
289:                }
290:            }
291:
292:            /**
293:             * Set the hostname of the outgoing mail server
294:             *
295:             * @param   aHostName aHostName
296:             * @since 1.0
297:             */
298:            public void setHostName(String aHostName) {
299:                this .hostName = aHostName;
300:            }
301:
302:            /**
303:             * Set the port number of the outgoing mail server.
304:             * @param   aPortNumber aPortNumber
305:             * @since 1.0
306:             */
307:            public void setSmtpPort(int aPortNumber) {
308:                if (aPortNumber < 1) {
309:                    throw new IllegalArgumentException(
310:                            "Cannot connect to a port number that is less than 1 ( "
311:                                    + aPortNumber + " )");
312:                }
313:
314:                this .smtpPort = Integer.toString(aPortNumber);
315:            }
316:
317:            /**
318:             * Supply a mail Session object to use
319:             * @param aSession mail session to be used
320:             * @since 1.0
321:             */
322:            public void setMailSession(Session aSession) {
323:                this .session = aSession;
324:            }
325:
326:            /**
327:             * Initialise a mailsession object
328:             *
329:             * @return A Session.
330:             * @throws EmailException thrown when host name was not set.
331:             * @since 1.0
332:             */
333:            public Session getMailSession() throws EmailException {
334:                if (this .session == null) {
335:                    Properties properties = new Properties(System
336:                            .getProperties());
337:                    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, SMTP);
338:
339:                    if (EmailUtils.isEmpty(this .hostName)) {
340:                        this .hostName = properties.getProperty(MAIL_HOST);
341:                    }
342:
343:                    if (EmailUtils.isEmpty(this .hostName)) {
344:                        throw new EmailException(
345:                                "Cannot find valid hostname for mail session");
346:                    }
347:
348:                    properties.setProperty(MAIL_PORT, smtpPort);
349:                    properties.setProperty(MAIL_HOST, hostName);
350:                    properties.setProperty(MAIL_DEBUG, String
351:                            .valueOf(this .debug));
352:
353:                    if (this .authenticator != null) {
354:                        properties.setProperty(MAIL_SMTP_AUTH, "true");
355:                    }
356:
357:                    if (this .bounceAddress != null) {
358:                        properties.setProperty(MAIL_SMTP_FROM,
359:                                this .bounceAddress);
360:                    }
361:
362:                    // changed this (back) to getInstance due to security exceptions
363:                    // caused when testing using maven
364:                    this .session = Session.getInstance(properties,
365:                            this .authenticator);
366:                }
367:                return this .session;
368:            }
369:
370:            /**
371:             * Creates a InternetAddress.
372:             *
373:             * @param email An email address.
374:             * @param name A name.
375:             * @return An internet address.
376:             * @throws EmailException Thrown when the address supplied or name were invalid.
377:             */
378:            private InternetAddress createInternetAddress(String email,
379:                    String name) throws EmailException {
380:                InternetAddress address = null;
381:
382:                try {
383:                    // check name input
384:                    if (EmailUtils.isEmpty(name)) {
385:                        name = email;
386:                    }
387:
388:                    // Using this instead of new InternetAddress(email, name, [charset]) makes
389:                    // commons-email usable with javamail 1.2 / J2EE 1.3
390:                    address = new InternetAddress(email);
391:
392:                    if (EmailUtils.isNotEmpty(this .charset)) {
393:                        address.setPersonal(name, this .charset);
394:                    } else {
395:                        address.setPersonal(name);
396:                    }
397:                } catch (Exception e) {
398:                    throw new EmailException(e);
399:                }
400:                return address;
401:            }
402:
403:            /**
404:             * Set the FROM field of the email.
405:             *
406:             * @param email A String.
407:             * @return An Email.
408:             * @throws EmailException Indicates an invalid email address.
409:             * @since 1.0
410:             */
411:            public Email setFrom(String email) throws EmailException {
412:                return setFrom(email, null);
413:            }
414:
415:            /**
416:             * Set the FROM field of the email.
417:             *
418:             * @param email A String.
419:             * @param name A String.
420:             * @throws EmailException Indicates an invalid email address.
421:             * @return An Email.
422:             * @since 1.0
423:             */
424:            public Email setFrom(String email, String name)
425:                    throws EmailException {
426:                this .fromAddress = createInternetAddress(email, name);
427:
428:                return this ;
429:            }
430:
431:            /**
432:             * Add a recipient TO to the email.
433:             *
434:             * @param email A String.
435:             * @throws EmailException Indicates an invalid email address.
436:             * @return An Email.
437:             * @since 1.0
438:             */
439:            public Email addTo(String email) throws EmailException {
440:                return addTo(email, null);
441:            }
442:
443:            /**
444:             * Add a recipient TO to the email.
445:             *
446:             * @param email A String.
447:             * @param name A String.
448:             * @throws EmailException Indicates an invalid email address.
449:             * @return An Email.
450:             * @since 1.0
451:             */
452:            public Email addTo(String email, String name) throws EmailException {
453:                this .toList.add(createInternetAddress(email, name));
454:                return this ;
455:            }
456:
457:            /**
458:             * Set a list of "TO" addresses.
459:             *
460:             * @param  aCollection collection of InternetAddress objects.
461:             * @throws EmailException Indicates an invalid email address.
462:             * @return An Email.
463:             * @since 1.0
464:             */
465:            public Email setTo(Collection aCollection) throws EmailException {
466:                if (aCollection == null || aCollection.isEmpty()) {
467:                    throw new EmailException(
468:                            "Address List provided was invalid");
469:                }
470:
471:                this .toList = new ArrayList(aCollection);
472:                return this ;
473:            }
474:
475:            /**
476:             * Add a recipient CC to the email.
477:             *
478:             * @param email A String.
479:             * @return An Email.
480:             * @throws EmailException Indicates an invalid email address.
481:             * @since 1.0
482:             */
483:            public Email addCc(String email) throws EmailException {
484:                return this .addCc(email, null);
485:            }
486:
487:            /**
488:             * Add a recipient CC to the email.
489:             *
490:             * @param email A String.
491:             * @param name A String.
492:             * @throws EmailException Indicates an invalid email address.
493:             * @return An Email.
494:             * @since 1.0
495:             */
496:            public Email addCc(String email, String name) throws EmailException {
497:                this .ccList.add(createInternetAddress(email, name));
498:                return this ;
499:            }
500:
501:            /**
502:             * Set a list of "CC" addresses.
503:             *
504:             * @param aCollection collection of InternetAddress objects.
505:             * @return An Email.
506:             * @throws EmailException Indicates an invalid email address
507:             * @since 1.0.
508:             */
509:            public Email setCc(Collection aCollection) throws EmailException {
510:                if (aCollection == null || aCollection.isEmpty()) {
511:                    throw new EmailException(
512:                            "Address List provided was invalid");
513:                }
514:
515:                this .ccList = new ArrayList(aCollection);
516:                return this ;
517:            }
518:
519:            /**
520:             * Add a blind BCC recipient to the email.
521:             *
522:             * @param email A String.
523:             * @return An Email.
524:             * @throws EmailException Indicates an invalid email address
525:             * @since 1.0
526:             */
527:            public Email addBcc(String email) throws EmailException {
528:                return this .addBcc(email, null);
529:            }
530:
531:            /**
532:             * Add a blind BCC recipient to the email.
533:             *
534:             * @param email A String.
535:             * @param name A String.
536:             * @return An Email.
537:             * @throws EmailException Indicates an invalid email address
538:             * @since 1.0
539:             */
540:            public Email addBcc(String email, String name)
541:                    throws EmailException {
542:                this .bccList.add(createInternetAddress(email, name));
543:                return this ;
544:            }
545:
546:            /**
547:             * Set a list of "BCC" addresses
548:             *
549:             * @param   aCollection collection of InternetAddress objects
550:             * @return  An Email.
551:             * @throws EmailException Indicates an invalid email address
552:             * @since 1.0
553:             */
554:            public Email setBcc(Collection aCollection) throws EmailException {
555:                if (aCollection == null || aCollection.isEmpty()) {
556:                    throw new EmailException(
557:                            "Address List provided was invalid");
558:                }
559:
560:                this .bccList = new ArrayList(aCollection);
561:                return this ;
562:            }
563:
564:            /**
565:             * Add a reply to address to the email.
566:             *
567:             * @param email A String.
568:             * @return An Email.
569:             * @throws EmailException Indicates an invalid email address
570:             * @since 1.0
571:             */
572:            public Email addReplyTo(String email) throws EmailException {
573:                return this .addReplyTo(email, null);
574:            }
575:
576:            /**
577:             * Add a reply to address to the email.
578:             *
579:             * @param email A String.
580:             * @param name A String.
581:             * @return An Email.
582:             * @throws EmailException Indicates an invalid email address
583:             * @since 1.0
584:             */
585:            public Email addReplyTo(String email, String name)
586:                    throws EmailException {
587:                this .replyList.add(createInternetAddress(email, name));
588:                return this ;
589:            }
590:
591:            /**
592:             * Used to specify the mail headers.  Example:
593:             *
594:             * X-Mailer: Sendmail, X-Priority: 1( highest )
595:             * or  2( high ) 3( normal ) 4( low ) and 5( lowest )
596:             * Disposition-Notification-To: user@domain.net
597:             *
598:             * @param map A Map.
599:             * @since 1.0
600:             */
601:            public void setHeaders(Map map) {
602:                Iterator iterKeyBad = map.entrySet().iterator();
603:
604:                while (iterKeyBad.hasNext()) {
605:                    Map.Entry entry = (Map.Entry) iterKeyBad.next();
606:                    String strName = (String) entry.getKey();
607:                    String strValue = (String) entry.getValue();
608:
609:                    if (EmailUtils.isEmpty(strName)) {
610:                        throw new IllegalArgumentException(
611:                                "name can not be null");
612:                    }
613:                    if (EmailUtils.isEmpty(strValue)) {
614:                        throw new IllegalArgumentException(
615:                                "value can not be null");
616:                    }
617:                }
618:
619:                // all is ok, update headers
620:                this .headers = map;
621:            }
622:
623:            /**
624:             * Adds a header ( name, value ) to the headers Map.
625:             *
626:             * @param name A String with the name.
627:             * @param value A String with the value.
628:             * @since 1.0
629:             */
630:            public void addHeader(String name, String value) {
631:                if (EmailUtils.isEmpty(name)) {
632:                    throw new IllegalArgumentException("name can not be null");
633:                }
634:                if (EmailUtils.isEmpty(value)) {
635:                    throw new IllegalArgumentException("value can not be null");
636:                }
637:
638:                this .headers.put(name, value);
639:            }
640:
641:            /**
642:             * Set the email subject.
643:             *
644:             * @param aSubject A String.
645:             * @return An Email.
646:             * @since 1.0
647:             */
648:            public Email setSubject(String aSubject) {
649:                this .subject = aSubject;
650:                return this ;
651:            }
652:
653:            /**
654:             * Set the "bounce address" - the address to which undeliverable messages
655:             * will be returned.  If this value is never set, then the message will be
656:             * sent to the address specified with the System property "mail.smtp.from",
657:             * or if that value is not set, then to the "from" address.
658:             *
659:             * @param email A String.
660:             * @return An Email.
661:             * @since 1.0
662:             */
663:            public Email setBounceAddress(String email) {
664:                this .bounceAddress = email;
665:                return this ;
666:            }
667:
668:            /**
669:             * Define the content of the mail.  It should be overidden by the
670:             * subclasses.
671:             *
672:             * @param msg A String.
673:             * @return An Email.
674:             * @throws EmailException generic exception.
675:             * @since 1.0
676:             */
677:            public abstract Email setMsg(String msg) throws EmailException;
678:
679:            /**
680:             * Build the internal MimeMessage to be sent.
681:             *
682:             * @throws EmailException if there was an error.
683:             * @since 1.0
684:             */
685:            public void buildMimeMessage() throws EmailException {
686:                try {
687:                    this .getMailSession();
688:                    this .message = new MimeMessage(this .session);
689:
690:                    if (EmailUtils.isNotEmpty(this .subject)) {
691:                        if (EmailUtils.isNotEmpty(this .charset)) {
692:                            this .message.setSubject(this .subject, this .charset);
693:                        } else {
694:                            this .message.setSubject(this .subject);
695:                        }
696:                    }
697:
698:                    // ========================================================
699:                    // Start of replacement code
700:                    if (this .content != null) {
701:                        this .message.setContent(this .content, this .contentType);
702:                    }
703:                    // end of replacement code
704:                    // ========================================================
705:                    else if (this .emailBody != null) {
706:                        this .message.setContent(this .emailBody);
707:                    } else {
708:                        this .message.setContent("", Email.TEXT_PLAIN);
709:                    }
710:
711:                    if (this .fromAddress != null) {
712:                        this .message.setFrom(this .fromAddress);
713:                    } else {
714:                        throw new EmailException("Sender address required");
715:                    }
716:
717:                    if (this .toList.size() + this .ccList.size()
718:                            + this .bccList.size() == 0) {
719:                        throw new EmailException(
720:                                "At least one receiver address required");
721:                    }
722:
723:                    if (this .toList.size() > 0) {
724:                        this .message.setRecipients(Message.RecipientType.TO,
725:                                this .toInternetAddressArray(this .toList));
726:                    }
727:
728:                    if (this .ccList.size() > 0) {
729:                        this .message.setRecipients(Message.RecipientType.CC,
730:                                this .toInternetAddressArray(this .ccList));
731:                    }
732:
733:                    if (this .bccList.size() > 0) {
734:                        this .message.setRecipients(Message.RecipientType.BCC,
735:                                this .toInternetAddressArray(this .bccList));
736:                    }
737:
738:                    if (this .replyList.size() > 0) {
739:                        this .message.setReplyTo(this 
740:                                .toInternetAddressArray(this .replyList));
741:                    }
742:
743:                    if (this .headers.size() > 0) {
744:                        Iterator iterHeaderKeys = this .headers.keySet()
745:                                .iterator();
746:                        while (iterHeaderKeys.hasNext()) {
747:                            String name = (String) iterHeaderKeys.next();
748:                            String value = (String) headers.get(name);
749:                            this .message.addHeader(name, value);
750:                        }
751:                    }
752:
753:                    if (this .message.getSentDate() == null) {
754:                        this .message.setSentDate(getSentDate());
755:                    }
756:
757:                    if (this .popBeforeSmtp) {
758:                        Store store = session.getStore("pop3");
759:                        store.connect(this .popHost, this .popUsername,
760:                                this .popPassword);
761:                    }
762:                } catch (MessagingException me) {
763:                    throw new EmailException(me);
764:                }
765:            }
766:
767:            /**
768:             * Sends the previously created MimeMessage to the SMTP server.
769:             *
770:             * @return the message id of the underlying MimeMessage
771:             * @throws EmailException the sending failed
772:             */
773:            public String sendMimeMessage() throws EmailException {
774:                EmailUtils.notNull(this .message, "message");
775:
776:                try {
777:                    Transport.send(this .message);
778:                    return this .message.getMessageID();
779:                } catch (Throwable t) {
780:                    String msg = "Sending the email to the following server failed : "
781:                            + this .getHostName() + ":" + this .getSmtpPort();
782:
783:                    throw new EmailException(msg, t);
784:                }
785:            }
786:
787:            /**
788:             * Returns the internal MimeMessage. Please not that the
789:             * MimeMessage is build by the buildMimeMessage() method.
790:             *
791:             * @return the MimeMessage
792:             */
793:            public MimeMessage getMimeMessage() {
794:                return this .message;
795:            }
796:
797:            /**
798:             * Sends the email. Internally we build a MimeMessage
799:             * which is afterwards sent to the SMTP server.
800:             *
801:             * @return the message id of the underlying MimeMessage
802:             * @throws EmailException the sending failed
803:             */
804:            public String send() throws EmailException {
805:                this .buildMimeMessage();
806:                return this .sendMimeMessage();
807:            }
808:
809:            /**
810:             * Sets the sent date for the email.  The sent date will default to the
811:             * current date if not explictly set.
812:             *
813:             * @param date Date to use as the sent date on the email
814:             * @since 1.0
815:             */
816:            public void setSentDate(Date date) {
817:                this .sentDate = date;
818:            }
819:
820:            /**
821:             * Gets the sent date for the email.
822:             *
823:             * @return date to be used as the sent date for the email
824:             * @since 1.0
825:             */
826:            public Date getSentDate() {
827:                if (this .sentDate == null) {
828:                    return new Date();
829:                }
830:                return this .sentDate;
831:            }
832:
833:            /**
834:             * Gets the subject of the email.
835:             *
836:             * @return email subject
837:             */
838:            public String getSubject() {
839:                return this .subject;
840:            }
841:
842:            /**
843:             * Gets the sender of the email.
844:             *
845:             * @return from address
846:             */
847:            public InternetAddress getFromAddress() {
848:                return this .fromAddress;
849:            }
850:
851:            /**
852:             * Gets the host name of the SMTP server,
853:             *
854:             * @return host name
855:             */
856:            public String getHostName() {
857:                return this .hostName;
858:            }
859:
860:            /**
861:             * Gets the listening port of the SMTP server.
862:             *
863:             * @return smtp port
864:             */
865:            public String getSmtpPort() {
866:                return this .smtpPort;
867:            }
868:
869:            /**
870:             * Utility to copy List of known InternetAddress objects into an
871:             * array.
872:             *
873:             * @param list A List.
874:             * @return An InternetAddress[].
875:             * @since 1.0
876:             */
877:            protected InternetAddress[] toInternetAddressArray(List list) {
878:                InternetAddress[] ia = (InternetAddress[]) list
879:                        .toArray(new InternetAddress[list.size()]);
880:
881:                return ia;
882:            }
883:
884:            /**
885:             * Set details regarding "pop3 before smtp" authentication.
886:             *
887:             * @param newPopBeforeSmtp Wether or not to log into pop3
888:             *      server before sending mail.
889:             * @param newPopHost The pop3 host to use.
890:             * @param newPopUsername The pop3 username.
891:             * @param newPopPassword The pop3 password.
892:             * @since 1.0
893:             */
894:            public void setPopBeforeSmtp(boolean newPopBeforeSmtp,
895:                    String newPopHost, String newPopUsername,
896:                    String newPopPassword) {
897:                this.popBeforeSmtp = newPopBeforeSmtp;
898:                this.popHost = newPopHost;
899:                this.popUsername = newPopUsername;
900:                this.popPassword = newPopPassword;
901:            }
902:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.