diff --git a/ccm-core/src/main/java/com/arsdigita/mail/Mail.java b/ccm-core/src/main/java/com/arsdigita/mail/Mail.java index f6f9f90df..b5e85307b 100644 --- a/ccm-core/src/main/java/com/arsdigita/mail/Mail.java +++ b/ccm-core/src/main/java/com/arsdigita/mail/Mail.java @@ -29,10 +29,14 @@ import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; -import java.util.Enumeration; -import java.util.Hashtable; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.Properties; -import java.util.StringTokenizer; +import java.util.Set; +import java.util.stream.IntStream; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.activation.URLDataSource; @@ -45,11 +49,8 @@ import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; -import org.apache.log4j.Logger; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Represents a email message with optional attachments. This class is a wrapper @@ -75,83 +76,84 @@ public class Mail implements MessageType { /** * Used for logging. */ - private static final Logger s_log = Logger.getLogger(Mail.class); + private static final Logger LOGGER = LogManager.getLogger(Mail.class); private static final InternetAddress[] EMPTY_ADDRESS_LIST = new InternetAddress[0]; /** * Table of message headers. */ - private Hashtable m_headers; + //private Hashtable m_headers; + private final Map headers = new HashMap<>(); /** * Email addresses the message is being sent to. */ - private InternetAddress[] m_to; - private InternetAddress[] m_filteredTo = EMPTY_ADDRESS_LIST; - private InternetAddress[] m_invalidTo = EMPTY_ADDRESS_LIST; - private static Set s_invalidDomains = new HashSet(); + private InternetAddress[] toAddress; + private InternetAddress[] filteredTo = EMPTY_ADDRESS_LIST; + private InternetAddress[] invalidTo = EMPTY_ADDRESS_LIST; + private final static Set INVALID_DOMAINS = new HashSet<>(); static { - s_log.debug("Static initalizer starting..."); - s_invalidDomains.add("example.com"); - s_log.debug("Static initalizer finished."); + LOGGER.debug("Static initalizer starting..."); + INVALID_DOMAINS.add("example.com"); + LOGGER.debug("Static initalizer finished."); } /** * Email address the message is being sent from. */ - private InternetAddress m_from; + private InternetAddress fromAddress; /** * Email address used for replies to this message. */ - private InternetAddress[] m_replyTo; + private InternetAddress[] replyTo; /** * Email addresses that the message is being carbon-copied to. */ - private InternetAddress[] m_cc; + private InternetAddress[] carbonCopy; /** * Email addresses that the message is being blind carbon-copied to. */ - private InternetAddress[] m_bcc; + private InternetAddress[] blindCarbonCopy; /** * Message subject. */ - private String m_subject; + private String subject; /** * Message body (can be text or HTML). */ - private String m_body; + private String body; /** * Message body alternate (if the body is HTML) */ - private String m_alternate; + private String alternate; /** * Encoding specification for m_body and m_alternate (optional). Default * value (null) implies "us-ascii" encoding. */ - private String m_encoding; + private String encoding; /** * Message attachments (optional) */ - private MimeMultipart m_attachments; + private MimeMultipart attachments; /** * Unique identifier for each mail send out. */ - private String m_messageID; + private String messageId; /** * Session object used to send mail. */ - private static Session s_session; + private static Session session; /** * SMTP host to connect to. Only used to override the default for testing * purposes. */ - private static String s_host; + private static String host; /** * SMTP port to connect to. Only used to override the default for testing * purposes. */ - private static String s_port; + private static String port; // Constants used by Mail final static String CONTENT_TYPE = "Content-Type"; final static String CONTENT_ID = "Content-ID"; @@ -167,8 +169,8 @@ public class Mail implements MessageType { public final static String ATTACHMENT = javax.mail.Part.ATTACHMENT; /** - * Default constructor. Must use the setTo, setSubject (and so on) methods - * to create a valid mail message. + * Default constructor. Must use the setToAddress, setSubject (and so on) + * methods to create a valid mail message. */ public Mail() { this(null, null, null, null); @@ -177,8 +179,8 @@ public class Mail implements MessageType { /** * Constructor used to specify to, from, and subject. * - * @param to one or more of addresses to send the message to - * @param from the address the message is being sent from + * @param to one or more of addresses to send the message to + * @param from the address the message is being sent from * @param subject the subject for the message */ public Mail(String to, @@ -190,68 +192,84 @@ public class Mail implements MessageType { /** * Constructor used to specify to, from, subject, and body. * - * @param to one or more of addresses to send the message to - * @param from the address the message is being sent from + * @param toAddress one or more of addresses to send the message to + * @param fromAddress the address the message is being sent from * @param subject the subject for the message - * @param body the plain text body of the message + * @param body the plain text body of the message */ - public Mail(String to, - String from, - String subject, - String body) { - m_to = (to == null ? EMPTY_ADDRESS_LIST : parseAddressField(to)); + public Mail(final String toAddress, + final String fromAddress, + final String subject, + final String body) { + if (toAddress == null) { + this.toAddress = EMPTY_ADDRESS_LIST; + } else { + this.toAddress = parseAddressField(toAddress); + } filterRecipients(); - m_from = (from == null ? null : parseAddress(from)); - m_subject = subject; + if (fromAddress == null) { + this.fromAddress = null; + } else { + this.fromAddress = parseAddress(fromAddress); + } + this.subject = subject; setBody(body); } /** * Constructor used to specify to, from, subject, body, and encoding. * - * @param to one or more of addresses to send the message to - * @param from the address the message is being sent from + * @param toAddress one or more of addresses to send the message to + * @param fromAddress the address the message is being sent from * @param subject the subject for the message - * @param body is plain text body of the message - * @param enc the encoding of the body + * @param body is plain text body of the message + * @param enc the encoding of the body */ - public Mail(String to, - String from, - String subject, - String body, - String enc) { - this(to, from, subject, body); + public Mail(final String toAddress, + final String fromAddress, + final String subject, + final String body, + final String enc) { + this(toAddress, fromAddress, subject, body); setEncoding(enc); } /** * A convenience method to send a simple plain-text message. * - * @param to one or more of addresses to send the message to - * @param from the address the message is being sent from + * @param toAddress one or more of addresses to send the message to + * @param fromAddress the address the message is being sent from * @param subject the subject for the message - * @param body the plain text body of the message + * @param body the plain text body of the message + * + * @throws MessagingException If there is a problem creating the mail. + * @throws SendFailedException If sending the mail fails for some reason. */ - public static void send(String to, - String from, - String subject, - String body) - throws MessagingException, - SendFailedException { - Mail msg = new Mail(to, from, subject, body); + public static void send(final String toAddress, + final String fromAddress, + final String subject, + final String body) throws MessagingException, + SendFailedException { + Mail msg = new Mail(toAddress, fromAddress, subject, body); msg.send(); } /** * Sends the message. + * + * @throws MessagingException If there is a problem creating the mail. + * @throws SendFailedException If sending the mail fails for some reason. */ - public void send() - throws MessagingException, - SendFailedException { - final Properties properties = MailConfig.getConfig().getJavaMailProperties(); - Transport transport = getSession().getTransport(); - transport.connect(properties.getProperty("mail.smtp.user"), - properties.getProperty("mail.smtp.password")); + public void send() throws MessagingException, SendFailedException { + final Properties properties = MailConfig.getConfig(). + getJavaMailProperties(); + final Transport transport = getSession().getTransport(); + if ("true".equals(properties.getProperty("mail.smtp.auth"))) { + transport.connect(properties.getProperty("mail.smtp.user"), + properties.getProperty("mail.smtp.password")); + } else { + transport.connect(); + } send(transport); transport.close(); } @@ -262,60 +280,58 @@ public class Mail implements MessageType { * connection to the mail server. * * @throws SendFailedException on any kind of MessagingException, also such - * returned from the server. Applications might - * try to catch this and re-schedule sending the - * mail. + * returned from the server. Applications might try to catch this and + * re-schedule sending the mail. */ - void send(Transport transport) - throws MessagingException, - SendFailedException { - Message msg = null; - if (m_filteredTo.length > 0) { - msg = getMessage(); + void send(final Transport transport) throws MessagingException, + SendFailedException { +// Message message = null; + final Message message; + if (filteredTo.length > 0) { + message = getMessage(); try { - transport.sendMessage(msg, msg.getAllRecipients()); - } catch (MessagingException mex) { + transport.sendMessage(message, message.getAllRecipients()); + } catch (MessagingException ex) { // Close the transport agent and rethrow error for // detailed message. transport.close(); - throw new SendFailedException("send failed: ", mex); + throw new SendFailedException("send failed: ", ex); } + } else { + message = null; } // Write a copy of the message into the log file if (MailConfig.getConfig().isDebug()) { - if (msg != null) { + if (message == null) { + LOGGER.debug("no message sent. No valid recipients:\n"); + } else { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); - msg.writeTo(os); - s_log.debug("message sent:\n" + os.toString() - + "\n-- EOT --"); + message.writeTo(os); + LOGGER.debug("message sent:\n{}\n-- EOT --", os.toString()); } catch (IOException ex) { - s_log.error("unable to log message"); + LOGGER.error("unable to log message", ex); } - } else { - s_log.debug("no message sent. No valid recipients:\n"); } } else { - s_log.info("message sent to <" + Arrays.asList(m_filteredTo) - + "> from <" + m_from + "> subject <" + m_subject - + ">"); - s_log.info("messages filtered for <" + Arrays.asList(m_invalidTo) - + "> from <" + m_from + "> subject <" + m_subject - + ">"); + LOGGER.info("message sent <{}> from <{}> subject <{}>", + Arrays.asList(filteredTo), fromAddress, subject); + LOGGER.info("messages filtered for <{}> from <{}> <{}>", + Arrays.asList(invalidTo), fromAddress, subject); } } /** * Sets the email address that the message is being sent to. * - * @param to one or more addresses to send the message to + * @param toAddress one or more addresses to send the message to */ - public void setTo(String to) { - m_to = parseAddressField(to); + public void setToAddress(final String toAddress) { + this.toAddress = parseAddressField(toAddress); filterRecipients(); } @@ -324,8 +340,8 @@ public class Mail implements MessageType { * * @param from the address the message is sent from */ - public void setFrom(String from) { - m_from = parseAddress(from); + public void setFromAddress(final String from) { + fromAddress = parseAddress(from); } /** @@ -333,8 +349,8 @@ public class Mail implements MessageType { * * @param subject the subject of the message */ - public void setSubject(String subject) { - m_subject = subject; + public void setSubject(final String subject) { + this.subject = subject; } /** @@ -342,8 +358,8 @@ public class Mail implements MessageType { * * @param replyTo the address to use for replies */ - public void setReplyTo(String replyTo) { - m_replyTo = parseAddressField(replyTo); + public void setReplyTo(final String replyTo) { + this.replyTo = parseAddressField(replyTo); } /** @@ -351,49 +367,45 @@ public class Mail implements MessageType { * * @param messageID unique identifier for each email. */ - public void setMessageID(String messageID) { - m_messageID = messageID; + public void setMessageID(final String messageID) { + this.messageId = messageID; } /** * Sets the mail's MIME headers. * - * @param headers a String containing MIME headers + * @param mimeHeader a String containing MIME headers */ - public void setHeaders(String headers) { - m_headers = parseHeaderField(headers); + public void setHeaders(final String mimeHeader) { + parseHeaderField(mimeHeader, headers); } /** * Adds a header (name, value) pair. * - * @param name the header element name + * @param name the header element name * @param value the header element value */ - public void addHeader(String name, String value) { - if (m_headers == null) { - m_headers = new Hashtable(); - } - - m_headers.put(name, value); + public void addHeader(final String name, final String value) { + headers.put(name, value); } /** * Sets the email address that is being carbon-copied. * - * @param cc the email address for a carbon copy + * @param carbonCopy the email address for a carbon copy */ - public void setCc(String cc) { - m_cc = parseAddressField(cc); + public void setCarbonCopy(final String carbonCopy) { + this.carbonCopy = parseAddressField(carbonCopy); } /** * Sets the email address that is being blind carbon-copied. * - * @param bcc the email address for a blind carbon copy + * @param blindCarbonCopy the email address for a blind carbon copy */ - public void setBcc(String bcc) { - m_bcc = parseAddressField(bcc); + public void setBlindCarbonCopy(final String blindCarbonCopy) { + this.blindCarbonCopy = parseAddressField(blindCarbonCopy); } /** @@ -401,8 +413,8 @@ public class Mail implements MessageType { * * @param body the body of the message in plain text */ - public void setBody(String body) { - m_body = body; + public final void setBody(final String body) { + this.body = body; } /** @@ -410,21 +422,21 @@ public class Mail implements MessageType { * alternative. * * @param body the body of the message in HTML - * @param alt the alternate message body in plain text + * @param alternate the alternate message body in plain text */ - public void setBody(String body, String alt) { - m_body = body; - m_alternate = alt; + public final void setBody(final String body, final String alternate) { + this.body = body; + this.alternate = alternate; } /** * Sets the character encoding. Valid encodings include "us-ascii", * "iso-8859-1" for w-Europe, "iso-8859-2" for e-Europe, and so on. * - * @param enc the requested encoding + * @param encoding the requested encoding */ - public void setEncoding(String enc) { - m_encoding = enc; + public final void setEncoding(final String encoding) { + this.encoding = encoding; } /** @@ -434,7 +446,7 @@ public class Mail implements MessageType { * @return the string value of the character encoding being used */ public String getEncoding() { - return m_encoding; + return encoding; } /** @@ -444,26 +456,26 @@ public class Mail implements MessageType { * * @param part the message part to attach */ - private void attach(MimeBodyPart part) - throws MessagingException { - if (m_attachments == null) { - m_attachments = new MimeMultipart(); + private void attach(final MimeBodyPart part) throws MessagingException { + if (attachments == null) { + attachments = new MimeMultipart(); } - m_attachments.addBodyPart(part); + attachments.addBodyPart(part); } /** * Adds an attachment with a specified name and description to a message by * fetching its content from a URL. Sets the disposition to ATTACHMENT. * - * @param url the URL to retreieve the content from - * @param name the name of the attachment + * @param url the URL to retreieve the content from + * @param name the name of the attachment * @param description a description of the attachment + * + * @throws MessagingException If the attachment could not be added. */ - public void attach(URL url, - String name, - String description) - throws MessagingException { + public void attach(final URL url, + final String name, + final String description) throws MessagingException { attach(url, name, description, Mail.ATTACHMENT); } @@ -471,22 +483,22 @@ public class Mail implements MessageType { * Adds an attachment with a specified name, description and disposition to * a message by fetching its content from a URL. * - * @param url the URL to retreieve the content from - * @param name the name of the attachment + * @param url the URL to retreieve the content from + * @param name the name of the attachment * @param description a description of the attachment * @param disposition Mail.ATTACHMENT or Mail.INLINE + * + * @throws MessagingException If teh attachment could not be added. */ - public void attach(URL url, - String name, - String description, - String disposition) - throws MessagingException { - MimeBodyPart part = new MimeBodyPart(); + public void attach(final URL url, + final String name, + final String description, + final String disposition) throws MessagingException { + final MimeBodyPart part = new MimeBodyPart(); attach(part); - DataHandler dh = new DataHandler(new URLDataSource(url)); - - part.setDataHandler(dh); + final DataHandler dataHandler = new DataHandler(new URLDataSource(url)); + part.setDataHandler(dataHandler); part.setFileName(name); part.setDescription(description); part.setDisposition(disposition); @@ -497,14 +509,15 @@ public class Mail implements MessageType { * fetching its content from a local file. Sets the disposition to * ATTACHMENT. * - * @param path the file path to retreieve the content from - * @param name the name of the attachment + * @param path the file path to retreieve the content from + * @param name the name of the attachment * @param description a description of the attachment + * + * @throws MessagingException If teh attachment could not be added. */ - public void attach(File path, - String name, - String description) - throws MessagingException { + public void attach(final File path, + final String name, + final String description) throws MessagingException { attach(path, name, description, ATTACHMENT); } @@ -512,22 +525,22 @@ public class Mail implements MessageType { * Adds an attachment with a specified name, description and disposition to * a message by fetching its content from a local file. * - * @param path the file path to retreieve the content from - * @param name the name of the attachment + * @param path the file path to retreieve the content from + * @param name the name of the attachment * @param description a description of the attachment * @param disposition Mail.ATTACHMENT or Mail.INLINE + * + * @throws MessagingException If teh attachment could not be added. */ - public void attach(File path, - String name, - String description, - String disposition) - throws MessagingException { - MimeBodyPart part = new MimeBodyPart(); + public void attach(final File path, + final String name, + final String description, + final String disposition) throws MessagingException { + final MimeBodyPart part = new MimeBodyPart(); attach(part); - DataHandler dh = new DataHandler(new FileDataSource(path)); - - part.setDataHandler(dh); + final DataHandler dataHandler = new DataHandler(new FileDataSource(path)); + part.setDataHandler(dataHandler); part.setFileName(name); part.setDescription(description); part.setDisposition(disposition); @@ -540,11 +553,12 @@ public class Mail implements MessageType { * @param data the content of the attachment * @param type the MIME type of the attachment * @param name the name of the attachment + * + * @throws MessagingException If teh attachment could not be added. */ - public void attach(byte[] data, - String type, - String name) - throws MessagingException { + public void attach(final byte[] data, + final String type, + final String name) throws MessagingException { attach(data, type, name, null, ATTACHMENT); } @@ -552,22 +566,23 @@ public class Mail implements MessageType { * Attaches a byte array to a message. Sets the MIME type, name, description * and disposition of the attachment. * - * @param data the content of the attachment - * @param type the MIME type of the attachment - * @param name the name of the attachment + * @param data the content of the attachment + * @param type the MIME type of the attachment + * @param name the name of the attachment * @param description a description of the attachment * @param disposition Mail.ATTACHMENT or Mail.INLINE * - * @throws javax.mail.MessagingException + * @throws MessagingException If teh attachment could not be added. */ - public void attach(byte[] data, - String type, - String name, - String description, - String disposition) - throws MessagingException { - ByteArrayDataSource ds = new ByteArrayDataSource(data, type, name); - attach(ds, description, disposition); + public void attach(final byte[] data, + final String type, + final String name, + final String description, + final String disposition) throws MessagingException { + final ByteArrayDataSource dataSource = new ByteArrayDataSource(data, + type, + name); + attach(dataSource, description, disposition); } /** @@ -577,11 +592,12 @@ public class Mail implements MessageType { * @param data the content of the attachment * @param type the MIME type of the attachment * @param name the name of the attachment + * + * @throws MessagingException If teh attachment could not be added. */ - public void attach(String data, - String type, - String name) - throws MessagingException { + public void attach(final String data, + final String type, + final String name) throws MessagingException { attach(data, type, name, null, ATTACHMENT); } @@ -589,20 +605,23 @@ public class Mail implements MessageType { * Attaches a String to a message. Sets the MIME type, name, description and * disposition of the attachment. * - * @param data the content of the attachment - * @param type the MIME type of the attachment - * @param name the name of the attachment + * @param data the content of the attachment + * @param type the MIME type of the attachment + * @param name the name of the attachment * @param description a description of the attachment * @param disposition Mail.ATTACHMENT or Mail.INLINE + * + * @throws MessagingException If teh attachment could not be added. */ - public void attach(String data, - String type, - String name, - String description, - String disposition) - throws MessagingException { - ByteArrayDataSource ds = new ByteArrayDataSource(data, type, name); - attach(ds, description, disposition); + public void attach(final String data, + final String type, + final String name, + final String description, + final String disposition) throws MessagingException { + final ByteArrayDataSource dataSource = new ByteArrayDataSource(data, + type, + name); + attach(dataSource, description, disposition); } /** @@ -610,35 +629,38 @@ public class Mail implements MessageType { * MIME type and name of the attachment, and initializes the disposition to * ATTACHMENT. * - * @param is the input stream to read from. + * @param inputStream the input stream to read from. * @param type the MIME type of the attachment * @param name the name of the attachment + * + * @throws MessagingException If teh attachment could not be added. */ - public void attach(ByteArrayInputStream is, - String type, - String name) - throws MessagingException { - attach(is, type, name, null, ATTACHMENT); + public void attach(final ByteArrayInputStream inputStream, + final String type, + final String name) throws MessagingException { + attach(inputStream, type, name, null, ATTACHMENT); } /** * Attaches the content from a ByteArrayInputStream to a message. Sets the * MIME type, name, description and disposition of the attachment. * - * @param is the input stream to read from. - * @param type the MIME type of the attachment - * @param name the name of the attachment + * @param inputStream the input stream to read from. + * @param type the MIME type of the attachment + * @param name the name of the attachment * @param description a description of the attachment * @param disposition Mail.ATTACHMENT or Mail.INLINE + * + * @throws MessagingException If teh attachment could not be added. */ - public void attach(ByteArrayInputStream is, - String type, - String name, - String description, - String disposition) - throws MessagingException { - ByteArrayDataSource ds = new ByteArrayDataSource(is, type, name); - attach(ds, description, disposition); + public void attach(final ByteArrayInputStream inputStream, + final String type, + final String name, + final String description, + final String disposition) throws MessagingException { + final ByteArrayDataSource dataSource = new ByteArrayDataSource( + inputStream, type, name); + attach(dataSource, description, disposition); } /** @@ -647,20 +669,20 @@ public class Mail implements MessageType { * types as input. The MIME type and name are determined directly from the * dataSource. * - * @param dataSource the data source to read from + * @param dataSource the data source to read from * @param description a description of the attachment * @param disposition Mail.ATTACHMENT or Mail.INLINE + * + * @throws MessagingException If teh attachment could not be added. */ - protected void attach(ByteArrayDataSource dataSource, - String description, - String disposition) - throws MessagingException { - MimeBodyPart part = new MimeBodyPart(); + protected void attach(final ByteArrayDataSource dataSource, + final String description, + final String disposition) throws MessagingException { + final MimeBodyPart part = new MimeBodyPart(); attach(part); - DataHandler dh = new DataHandler(dataSource); - - part.setDataHandler(dh); + DataHandler dataHandler = new DataHandler(dataSource); + part.setDataHandler(dataHandler); part.setFileName(dataSource.getName()); part.setDescription(description); part.setDisposition(disposition); @@ -671,30 +693,32 @@ public class Mail implements MessageType { * parameters (MIME type, name, ...) are determined directly from the * DataHandler. * - * @param dh a DataHandler for some piece of content. + * @param dataHandler a DataHandler for some piece of content. + * + * @throws MessagingException If teh attachment could not be added. */ - public void attach(DataHandler dh) - throws MessagingException { - attach(dh, null, ATTACHMENT); + public void attach(final DataHandler dataHandler) throws MessagingException { + attach(dataHandler, null, ATTACHMENT); } /** * Attaches content to a message by supplying a DataHandler. Sets the * description and disposition of the content. * - * @param dh the data source to read from + * @param dataHandler the data source to read from * @param description a description of the attachment * @param disposition Mail.ATTACHMENT or Mail.INLINE + * + * @throws MessagingException If teh attachment could not be added. */ - public void attach(DataHandler dh, - String description, - String disposition) - throws MessagingException { + public void attach(final DataHandler dataHandler, + final String description, + final String disposition) throws MessagingException { MimeBodyPart part = new MimeBodyPart(); attach(part); - part.setDataHandler(dh); - part.setFileName(dh.getName()); + part.setDataHandler(dataHandler); + part.setFileName(dataHandler.getName()); part.setDescription(description); part.setDisposition(disposition); } @@ -706,27 +730,27 @@ public class Mail implements MessageType { */ static synchronized Session getSession() { - if (s_session == null) { + if (session == null) { // Set up the properties Properties props = new Properties( - MailConfig.getConfig().getJavaMailProperties()); + MailConfig.getConfig().getJavaMailProperties()); // Check for overrides of the server information - if (s_host != null) { - props.put("mail.smtp.host", s_host); + if (host != null) { + props.put("mail.smtp.host", host); } - if (s_port != null) { - props.put("mail.smtp.port", s_port); + if (port != null) { + props.put("mail.smtp.port", port); } // Set up the session - s_session = Session.getInstance(props, null); + session = Session.getInstance(props, null); // s_session.setDebug(MailConfig.getConfig().isDebug()); - s_session.setDebug(true); + session.setDebug(true); } - return s_session; + return session; } /** @@ -736,57 +760,60 @@ public class Mail implements MessageType { * method for each instance.) */ private Message getMessage() - throws MessagingException { + throws MessagingException { // Create the message - MimeMessage msg = new MimeMessage(getSession()); + final MimeMessage msg = new MimeMessage(getSession()); - msg.setFrom(m_from); - msg.setRecipients(Message.RecipientType.TO, m_filteredTo); + msg.setFrom(fromAddress); + msg.setRecipients(Message.RecipientType.TO, filteredTo); msg.setSentDate(new Date()); /** * If no message ID is set then do not generate message-id header. */ - if (m_messageID != null) { - msg.setMessageID("<" + m_messageID + ">"); + if (messageId != null) { + msg.setMessageID("<" + messageId + ">"); } - if (m_cc != null) { - msg.setRecipients(Message.RecipientType.CC, m_cc); + if (carbonCopy != null) { + msg.setRecipients(Message.RecipientType.CC, carbonCopy); } - if (m_bcc != null) { - msg.setRecipients(Message.RecipientType.BCC, m_bcc); + if (blindCarbonCopy != null) { + msg.setRecipients(Message.RecipientType.BCC, blindCarbonCopy); } - if (m_replyTo != null) { - msg.setReplyTo(m_replyTo); + if (replyTo != null) { + msg.setReplyTo(replyTo); } // Encode the subject String enc_subj; try { - enc_subj = MimeUtility.encodeText(m_subject, m_encoding, null); + enc_subj = MimeUtility.encodeText(subject, encoding, null); } catch (UnsupportedEncodingException uee) { - s_log.warn("unable to encode subject: " + uee); - enc_subj = m_subject; + LOGGER.warn("unable to encode subject: " + uee); + enc_subj = subject; } msg.setSubject(enc_subj); // Encode the MIME headers - if (m_headers != null) { - Enumeration e = m_headers.keys(); - while (e.hasMoreElements()) { - String name = (String) e.nextElement(); - String value = (String) m_headers.get(name); - String enc_v; +// if (m_headers != null) { + if (!headers.isEmpty()) { + final Set keys = headers.keySet(); + + for (String key : headers.keySet()) { + final String value = headers.get(key); + String encodedValue; try { - enc_v = MimeUtility.encodeText(value, m_encoding, null); - } catch (UnsupportedEncodingException uee) { - s_log.warn("unable to encode header element: " + uee); - enc_v = value; + encodedValue = MimeUtility.encodeText( + value, encoding, null); + } catch (UnsupportedEncodingException ex) { + LOGGER.warn("unable to encode header element.", ex); + encodedValue = value; } - msg.addHeader(name, enc_v); + + msg.addHeader(key, encodedValue); } } @@ -802,12 +829,13 @@ public class Mail implements MessageType { * @param host the SMTP host to connect to * @param port the port number on that host */ - synchronized static void setSmtpServer(String host, String port) { - s_host = host; - s_port = port; + synchronized static void setSmtpServer(final String host, + final String port) { + Mail.host = host; + Mail.port = port; // invalidate the current session object - s_session = null; + session = null; } /** @@ -816,39 +844,36 @@ public class Mail implements MessageType { * @return the SMTP mail host for debugging and account information. */ public synchronized static String getSmtpServer() { - return s_host; + return host; } /** * Writes the content of the message to the given output stream. Useful for * debugging. * - * @param os the output stream to write the message to + * @param outputStream the output stream to write the message to + * + * @throws MessagingException If something goes wrong when writing the + * message. */ - public void writeTo(OutputStream os) - throws MessagingException { + public void writeTo(final OutputStream outputStream) + throws MessagingException { + try { - getMessage().writeTo(os); + getMessage().writeTo(outputStream); } catch (IOException ex) { - s_log.error("writeTo output error", ex); + LOGGER.error("writeTo output error", ex); } } /** * Parses an address field. */ - private static InternetAddress[] parseAddressField(String str) { - String[] addrList; + private static InternetAddress[] parseAddressField(final String str) { + final String[] addrList; - if (str.indexOf(",") != -1) { - ArrayList a = new ArrayList(); - StringTokenizer st = new StringTokenizer(str, ",", false); - while (st.hasMoreTokens()) { - a.add(st.nextToken()); - } - - addrList = new String[a.size()]; - a.toArray(addrList); + if (str.contains(",")) { + addrList = str.split(","); } else { addrList = new String[1]; addrList[0] = str; @@ -860,124 +885,120 @@ public class Mail implements MessageType { /** * Parses an address list. */ - private static InternetAddress[] parseAddressList(String[] addrList) { - InternetAddress[] addrs = new InternetAddress[addrList.length]; + private static InternetAddress[] parseAddressList( + final String[] addressList) { - for (int i = 0; i < addrList.length; i++) { - addrs[i] = parseAddress(addrList[i]); - } - return addrs; + final InternetAddress[] addresses = new InternetAddress[addressList.length]; + + IntStream.range(0, addressList.length).forEach(i -> { + addresses[i] = parseAddress(addressList[i]); + }); + + return addresses; } /** * Parses an address. */ - private static InternetAddress parseAddress(String str) { - String address = null; - String personal = null; - - InternetAddress addr = null; - - str = str.trim(); - - if (str.indexOf(" ") == -1) { - address = str; + private static InternetAddress parseAddress(final String str) { + final String trimmed = str.trim(); + + final String address; + final String personal; + if (trimmed.contains(" ")) { + final String[] tokens = trimmed.split(" "); + personal = tokens[0]; + address = tokens[1]; } else { - int sp = str.lastIndexOf(" "); - personal = str.substring(0, sp); - address = str.substring(sp + 1); + address = str; + personal = null; } - + try { - addr = new InternetAddress(address, personal); - } catch (UnsupportedEncodingException e) { - s_log.error("unable to parse address: " + str); + return new InternetAddress(address, personal); + } catch(UnsupportedEncodingException ex) { + LOGGER.error("Unable to parse address: {}", trimmed); + LOGGER.error(ex); + + return null; } - - return addr; } /** * Parses a header field. */ - private static Hashtable parseHeaderField(String str) { - String[] headerList; - - if (str.indexOf(",") != -1) { - ArrayList a = new ArrayList(); - StringTokenizer st = new StringTokenizer(str, ",", false); - while (st.hasMoreTokens()) { - a.add(st.nextToken()); - } - headerList = new String[a.size()]; - a.toArray(headerList); - } else { - headerList = new String[1]; - headerList[0] = str; - } - - return parseHeaderList(headerList); + private static Map parseHeaderField( + final String str, final Map headers) { + return parseHeaderList(str.split(","), headers); } /** * Parses a header list. */ - private static Hashtable parseHeaderList(String[] headerList) { - Hashtable headers = new Hashtable(); + private static Map parseHeaderList( + final String[] headerList, + final Map headers) { - for (int i = 0; i < headerList.length; i++) { - parseHeader(headerList[i], headers); + for (String header : headerList) { + parseHeader(header, headers); } + return headers; } /** * Parses a header. */ - private static void parseHeader(String str, Hashtable headers) { - str = str.trim(); + private static void parseHeader(final String str, + final Map headers) { + final String trimmed = str.trim(); - int sp = str.lastIndexOf(":"); - String name = str.substring(0, sp); - String value = (str.substring(sp + 1)).trim(); - - headers.put(name, value); + final String[] tokens = trimmed.split(":"); + if (tokens.length >= 2) { + headers.put(tokens[0].trim(), tokens[1].trim()); + } } /** * Utility function to prepare the content of the message. */ - private Message prepareMessageContent(MimeMessage msg) - throws MessagingException { - if (m_alternate == null && m_attachments == null) { + private Message prepareMessageContent(final MimeMessage msg) + throws MessagingException { + + if (alternate == null && attachments == null) { // We have a plain-text message with no attachments. Use // the Message.setText() method to initialize the content // and leave the default MIME type alone. - msg.setText(m_body, m_encoding); + msg.setText(body, encoding); } else { // For anything else the message will be a MIME multipart, // with a subtype of of either "mixed" or "alternative" // depending on whether we have attachments. - String subtype = (m_attachments == null) ? ALTERNATIVE : MIXED; + final String subtype; + if (attachments == null) { + subtype = ALTERNATIVE; + } else { + subtype = MIXED; + } // Create a MIME multipart for the content. - MimeMultipart mp = new MimeMultipart(subtype); - msg.setContent(mp); + final MimeMultipart mimeMultipart = new MimeMultipart(subtype); + msg.setContent(mimeMultipart); // Next we need to look at whether the message part of the // content is going to be text/plain or text/html. - MimeBodyPart part = new MimeBodyPart(); + final MimeBodyPart mimeBodyPart = new MimeBodyPart(); - if (m_alternate == null) { + if (alternate == null) { // No alternate, so it must be text/plain with // attachments. - part.setText(m_body, m_encoding); - part.setHeader(CONTENT_TYPE, MessageType.TEXT_PLAIN); - mp.addBodyPart(part); + mimeBodyPart.setText(body, encoding); + mimeBodyPart.setHeader(CONTENT_TYPE, MessageType.TEXT_PLAIN); + mimeMultipart.addBodyPart(mimeBodyPart); } else { @@ -985,25 +1006,23 @@ public class Mail implements MessageType { // the first part and the alternate as the second. // The overall MIME subtype is probably ALTERNATE // (depending on whether we have attachments). - part.setText(m_body, m_encoding); - part.setHeader(CONTENT_TYPE, MessageType.TEXT_HTML); - mp.addBodyPart(part); - - part = new MimeBodyPart(); - part.setText(m_alternate, m_encoding); - part.setHeader(CONTENT_TYPE, MessageType.TEXT_PLAIN); - mp.addBodyPart(part); + mimeBodyPart.setText(body, encoding); + mimeBodyPart.setHeader(CONTENT_TYPE, MessageType.TEXT_HTML); + mimeMultipart.addBodyPart(mimeBodyPart); + final MimeBodyPart alternateMimeBodyPart = new MimeBodyPart(); + alternateMimeBodyPart.setText(alternate, encoding); + alternateMimeBodyPart.setHeader(CONTENT_TYPE, MessageType.TEXT_PLAIN); + mimeMultipart.addBodyPart(alternateMimeBodyPart); } // Do we have attachments? If so then the MIME subtype // must be MIXED and and the attachments need to be // transferred to the Message. - if (m_attachments != null) { - + if (attachments != null) { // Add attachments to the Message content. - for (int i = 0; i < m_attachments.getCount(); i++) { - mp.addBodyPart(m_attachments.getBodyPart(i)); + for (int i = 0; i < attachments.getCount(); i++) { + mimeMultipart.addBodyPart(attachments.getBodyPart(i)); } } } @@ -1019,32 +1038,32 @@ public class Mail implements MessageType { * */ private InternetAddress[] filterRecipients() { - ArrayList filtered = new ArrayList(); - ArrayList invalid = new ArrayList(); - for (int i = 0; i < m_to.length; i++) { - Iterator it = s_invalidDomains.iterator(); + final List filtered = new ArrayList<>(); + final List invalid = new ArrayList<>(); + for (InternetAddress toAddres : toAddress) { + Iterator it = INVALID_DOMAINS.iterator(); boolean isValid = true; while (it.hasNext()) { - if (m_to[i].getAddress().endsWith((String) it.next())) { + if (toAddres.getAddress().endsWith((String) it.next())) { isValid = false; break; } } if (isValid) { - filtered.add(m_to[i]); + filtered.add(toAddres); } else { - invalid.add(m_to[i]); - s_log.debug("filtering message to non-existent email address " - + m_to[i]); + invalid.add(toAddres); + LOGGER.debug("filtering message to non-existent email address " + + toAddres); } } - m_filteredTo = (InternetAddress[]) filtered.toArray( - new InternetAddress[filtered. - size()]); - m_invalidTo = (InternetAddress[]) invalid.toArray( - new InternetAddress[invalid. - size()]); - return m_filteredTo; + filteredTo = (InternetAddress[]) filtered.toArray( + new InternetAddress[filtered. + size()]); + invalidTo = (InternetAddress[]) invalid.toArray( + new InternetAddress[invalid. + size()]); + return filteredTo; } }