org.sape.carbon.services.email
Class SynchronousMailService

java.lang.Object
  |
  +--org.sape.carbon.services.email.SynchronousMailService
All Implemented Interfaces:
Configurable, FunctionalInterface, MailService, Startable

public class SynchronousMailService
extends Object
implements MailService, Configurable, Startable

This is a synchronous implementation for sending emails over JavaMail API.

Since:
carbon 1.0
Version:
$Revision: 1.15 $($Author: dvoet $ / $Date: 2003/05/05 21:21:29 $)
Copyright 2002 Sapient
Author:
Nitin Gulati, June 2002

Field Summary
protected static String BLANK_STRING
          An empty string.
protected static String CONTENT_TYPE
          Content type key for headers.
private static String FILE
          Constant for the file:// protocol.
private  boolean holdConnection
          A boolean property indicating whether or not the email service will create and keep open a connection to the SMTP host for its lifetime.
private static String LOCALHOST
          Constant for the localhost address.
private  org.apache.commons.logging.Log log
          Provides a handle to Apache-commons logger
private static String MAIL_HOST
          Key for mail session property of mail host.
private static String MAIL_PROTOCOL_KEY
          Key for mail session property of protocol.
private  int retryAttempts
          This indicates the number of retry attempts to be made with SMTP server to send an email.When trying to send an email the service may receive an exception back from JavaMail.
private  javax.mail.Session session
          Holds the session object required to create the MimeMessage .
private  long sleepRetryTime
          Time in milliseconds waited between send attempts when failure occurs.
private static String SMTP
          SMPT Value for mail session property of protocol.
private  String smtpHost
          Holds the SMTP host name or IP address.
private  javax.mail.Transport transport
          Holds the reference to the Transport obejct which does the actual job of sending the message.
 
Constructor Summary
SynchronousMailService()
           
 
Method Summary
protected  javax.mail.BodyPart attach(MailAttachment attachment, String charset)
          Attaches the MailAttachment.
protected  Collection checkRequiredFields(Map to, Map cc, Map bcc, String fromEmail, MailContentTypeEnum bodyType)
           This method is used internally to check the required parameters before sending an email.
 void configure(ComponentConfiguration config)
          Configure the component.
protected  String encodeText(String text, String charset, String encodingType)
          Encode a RFC 822 "text" token into mail-safe form as per RFC 2047.
protected  void processAttachments(javax.mail.internet.MimeMessage message, String body, MailContentTypeEnum bodyType, String charset, MailAttachment[] attachments)
          Used internally to attach the attachments in the the MimeMessage
protected  String processRequiredFieldErrors(Collection errors)
           Used internally to process the validation errors.
protected  void send(javax.mail.internet.MimeMessage message)
          Sends a single email message.
protected  void sendInternal(javax.mail.internet.MimeMessage message)
          Does the actual job of sending a message.
 void sendMail(MailDataObject mailDataObject)
          Sends an email with the parameters specified in mail data object.
protected  void setAddresses(javax.mail.internet.MimeMessage message, Map addresses, javax.mail.Message.RecipientType recipientType, String charset)
           Used internally to set the addresses in MimeMessage from a Map structure.
protected  void setContentTypeHeader(javax.mail.Part part, MailContentTypeEnum bodyType, String charset)
           This method sets the Content type header.
 void start()
          Start the component.
 void stop()
          Stop the component.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

log

private org.apache.commons.logging.Log log
Provides a handle to Apache-commons logger


smtpHost

private String smtpHost

Holds the SMTP host name or IP address.


holdConnection

private boolean holdConnection

A boolean property indicating whether or not the email service will create and keep open a connection to the SMTP host for its lifetime. If set to true, the connection will not be closed until the email service is shutdown. If set to false a new connection will be opened for each email sent.


retryAttempts

private int retryAttempts

This indicates the number of retry attempts to be made with SMTP server to send an email.When trying to send an email the service may receive an exception back from JavaMail. This is usually the result of failure to connect to the email server. In this case the service will execute the following steps n (retry attempts) times.


session

private javax.mail.Session session

Holds the session object required to create the MimeMessage .


transport

private javax.mail.Transport transport

Holds the reference to the Transport obejct which does the actual job of sending the message.


sleepRetryTime

private long sleepRetryTime

Time in milliseconds waited between send attempts when failure occurs.


CONTENT_TYPE

protected static final String CONTENT_TYPE
Content type key for headers.

See Also:
Constant Field Values

BLANK_STRING

protected static final String BLANK_STRING
An empty string.

See Also:
Constant Field Values

FILE

private static final String FILE
Constant for the file:// protocol.

See Also:
Constant Field Values

LOCALHOST

private static final String LOCALHOST
Constant for the localhost address.

See Also:
Constant Field Values

MAIL_PROTOCOL_KEY

private static final String MAIL_PROTOCOL_KEY
Key for mail session property of protocol.

See Also:
Constant Field Values

MAIL_HOST

private static final String MAIL_HOST
Key for mail session property of mail host.

See Also:
Constant Field Values

SMTP

private static final String SMTP
SMPT Value for mail session property of protocol.

See Also:
Constant Field Values
Constructor Detail

SynchronousMailService

public SynchronousMailService()
Method Detail

sendMail

public void sendMail(MailDataObject mailDataObject)
              throws MailFailureException
Description copied from interface: MailService

Sends an email with the parameters specified in mail data object. E.x MailDataObject mailDataObject = new MailDataObject(); mailDataObject.addTo("someone@somewhere.com", "someone"); mailDataObject.setFrom("ejfw4@sapient.com", "ejfw4"); mailDataObject.setSubject("Hello"); mailDataObject.setBody("A simple plain text email", MailContentTypeEnum.PLAIN_TEXT); // Fetch the mail component MailService mailService = (MailService) Lookup.getInstance(). fetchComponent("/email/test/testEmail"); mailService.sendMail(mailDataObject);

Specified by:
sendMail in interface MailService
Parameters:
mailDataObject - the mail data object to send
Throws:
MailFailureException - Throws when the mail was not sent because of various reasons listed below :
  • Invalid configuration E.g wrong ip of smtp server.
  • The path or URL of any of the attachment does not exist.
  • The charset passed for encoding the message is not supported.
  • Unable to connect to the smtp server due to network issues.
See Also:
MailService.sendMail(MailDataObject mailDataObject)

processAttachments

protected void processAttachments(javax.mail.internet.MimeMessage message,
                                  String body,
                                  MailContentTypeEnum bodyType,
                                  String charset,
                                  MailAttachment[] attachments)
                           throws javax.mail.MessagingException,
                                  UnsupportedEncodingException,
                                  MalformedURLException

Used internally to attach the attachments in the the MimeMessage

Parameters:
message - message to add the attachments to
body - The body content of the message
bodyType - type of body (plain/html/etc)
charset - character set of the message
attachments - array of attachments to add to the message
Throws:
MalformedURLException - indicates the path or URL of attachment does not exist.
UnsupportedEncodingException - indicates the encoding given was not valid
javax.mail.MessagingException - indicates a generic exception attempting to add the attachment

checkRequiredFields

protected Collection checkRequiredFields(Map to,
                                         Map cc,
                                         Map bcc,
                                         String fromEmail,
                                         MailContentTypeEnum bodyType)

This method is used internally to check the required parameters before sending an email.

Parameters:
to - A Map containing the mapping of toEmail to toPersonal.
cc - A Map containing the mapping of ccEmail to ccPersonal.
bcc - A Map containing the mapping of bccEmail to bccPersonal.
fromEmail - sender's email id.
bodyType - the type of body content (plain/html/etc)
Returns:
Collection A collection containing all the errors.

processRequiredFieldErrors

protected String processRequiredFieldErrors(Collection errors)

Used internally to process the validation errors.

Parameters:
errors - collection of validation error to process
Returns:
The String representation of all the errors.

setContentTypeHeader

protected void setContentTypeHeader(javax.mail.Part part,
                                    MailContentTypeEnum bodyType,
                                    String charset)
                             throws javax.mail.MessagingException

This method sets the Content type header.

Parameters:
part - The message or body part.
bodyType - The body type of the message or body part.
charset - The charset to be used for encoding.
Throws:
javax.mail.MessagingException - If this part is read-only.

encodeText

protected String encodeText(String text,
                            String charset,
                            String encodingType)
                     throws UnsupportedEncodingException

Encode a RFC 822 "text" token into mail-safe form as per RFC 2047.

Parameters:
text - The text to be encoded.
charset - The charset. If this parameter is null, the JVM's default charset is used.
encodingType - The encoding to be used. Currently supported values by Java Mail are "B" and "Q". If this parameter is null, then the "Q" encoding is used if most of characters to be encoded are in the ASCII charset, otherwise "B" encoding is used.
Returns:
Unicode string containing only US-ASCII characters
Throws:
UnsupportedEncodingException - Thrown when the text passed is non-ascii and the charset or encodingType is not supported.

attach

protected javax.mail.BodyPart attach(MailAttachment attachment,
                                     String charset)
                              throws MalformedURLException,
                                     UnsupportedEncodingException,
                                     javax.mail.MessagingException
Attaches the MailAttachment.

Parameters:
attachment - A MailAttachment.
charset - the character of the attachment
Returns:
A Multipart.
Throws:
MalformedURLException - indicates the path or URL of attachment does not exist.
UnsupportedEncodingException - indicates the encoding given was not valid
javax.mail.MessagingException - indicates a generic exception attempting to add the attachment

setAddresses

protected void setAddresses(javax.mail.internet.MimeMessage message,
                            Map addresses,
                            javax.mail.Message.RecipientType recipientType,
                            String charset)
                     throws javax.mail.MessagingException,
                            UnsupportedEncodingException

Used internally to set the addresses in MimeMessage from a Map structure.

Parameters:
message - message to add the addresses to
addresses - map of addresses to add to the message
recipientType - type of message recipient
charset - character set of the address
Throws:
javax.mail.MessagingException - indicates a generic error trying to set the address
UnsupportedEncodingException - indicates an unsupported encoding was given to the system.

configure

public void configure(ComponentConfiguration config)
               throws Exception
Description copied from interface: Configurable
Configure the component. This is preceded and followed by the suspend and resume operations if they are available on the component.

Specified by:
configure in interface Configurable
Parameters:
config - the configuration for this component
Throws:
Exception - indicates a unknown error
See Also:
Configurable.configure(ComponentConfiguration)

send

protected void send(javax.mail.internet.MimeMessage message)
             throws javax.mail.MessagingException

Sends a single email message.

Parameters:
message - The message to be sent.
Throws:
javax.mail.MessagingException - indicates an error sending the message

sendInternal

protected void sendInternal(javax.mail.internet.MimeMessage message)
                     throws javax.mail.MessagingException

Does the actual job of sending a message. The call to this method is synchronized on this.transport because different threads can access the same component to send emails. If the call is not synchronized then there might be the case when one thread opens a connection, the second thread sends an email and closes the connection. Now first threads wakes up and try to send an email but would get an exception as the connection is closed.

Parameters:
message - The message to be sent.
Throws:
javax.mail.MessagingException - indicates an error sending the message

stop

public void stop()
          throws Exception
Description copied from interface: Startable
Stop the component. Prior to entry, the container will cease forwarding requests for service to the component. This is an opportunity to cleanly complete or abort any outstanding work. For example, a set of worker threads could be killed off, or a queue set to drain.

Specified by:
stop in interface Startable
Throws:
Exception - when there is a failure to stop the exception
See Also:
Startable.stop()

start

public void start()
Description copied from interface: Startable
Start the component. On return, the container will begin fowarding requests to the component. This may be an opportunity to dispatch worker threads.

Specified by:
start in interface Startable
See Also:
Startable.start()


Copyright 1999-2003 Sapient Corporation. All Rights Reserved.