Example usage for javax.mail.internet InternetAddress InternetAddress

List of usage examples for javax.mail.internet InternetAddress InternetAddress

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress InternetAddress.

Prototype

public InternetAddress(String address) throws AddressException 

Source Link

Document

Constructor.

Usage

From source file:com.alkacon.opencms.newsletter.A_CmsNewsletterMailData.java

/**
 * @see com.alkacon.opencms.newsletter.I_CmsNewsletterMailData#getRecipients()
 *///from  ww  w .  j  av  a 2  s .  co m
public List<InternetAddress> getRecipients() throws CmsException {

    if (m_recipients != null) {
        // we have explicitly set recipients, use these
        return m_recipients;
    }
    // we have a group or an OU to check for recipients
    List<InternetAddress> recipients = new ArrayList<InternetAddress>();
    Iterator<CmsUser> i = new ArrayList<CmsUser>().iterator();
    String groupName = "";
    if (getGroup() != null) {
        // iterate over mailing list members (i.e. an OpenCms group)
        groupName = getGroup().getName();
        i = getCms().getUsersOfGroup(groupName).iterator();
    } else if (getOu() != null) {
        i = getOuUsers().iterator();
    }
    while (i.hasNext()) {
        CmsUser user = i.next();
        if (CmsNewsletterManager.isActiveUser(user, groupName)) {
            // add active users to the recipients
            try {
                recipients.add(new InternetAddress(user.getEmail()));
            } catch (MessagingException e) {
                // log invalid email address
                if (LOG.isErrorEnabled()) {
                    LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_NEWSLETTER_EMAIL_3,
                            user.getEmail(), user.getName(), getContent().getFile().getRootPath()));
                }
            }
        }
    }

    if (getContent().hasValue(NODE_BCC, getLocale())) {
        // add the configured email address to the list of BCC recipients
        try {
            recipients.add(new InternetAddress(getContent().getStringValue(getCms(), NODE_BCC, getLocale())));
        } catch (MessagingException e) {
            // log invalid email address
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_NEWSLETTER_EMAIL_BCC_2,
                        getContent().getStringValue(getCms(), NODE_BCC, getLocale()),
                        getContent().getFile().getRootPath()));
            }
        }
    }
    return recipients;
}

From source file:com.datatorrent.lib.io.SmtpOutputOperator.java

private void resetMessage() {
    if (!setupCalled) {
        return;/*from w w w . j a  v  a2  s. co  m*/
    }
    try {
        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        for (Map.Entry<String, String> entry : recipients.entrySet()) {
            RecipientType type = RecipientType.valueOf(entry.getKey().toUpperCase());
            Message.RecipientType recipientType;
            switch (type) {
            case TO:
                recipientType = Message.RecipientType.TO;
                break;
            case CC:
                recipientType = Message.RecipientType.CC;
                break;
            case BCC:
            default:
                recipientType = Message.RecipientType.BCC;
                break;
            }
            String[] addresses = entry.getValue().split(",");
            for (String address : addresses) {
                message.addRecipient(recipientType, new InternetAddress(address));
            }
        }
        message.setSubject(subject);
        LOG.debug("all recipients {}", Arrays.toString(message.getAllRecipients()));
    } catch (MessagingException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.fiveamsolutions.nci.commons.util.MailUtils.java

/**
 * Send an email./*from ww  w  .j a  v a  2  s  .com*/
 * @param u the recipient of the message
 * @param title the subject of the message
 * @param html the html content of the message
 * @param plainText the plain text content of the message
 * @throws MessagingException on error.
 */
public static void sendEmail(AbstractUser u, String title, String html, String plainText)
        throws MessagingException {
    if (!isMailEnabled()) {
        LOG.info("sending email to " + u.getEmail() + " with title " + title);
        LOG.info("plain text: " + plainText);
        LOG.info("html: " + html);
        return;
    }
    MimeMessage msg = new MimeMessage(getMailSession());
    msg.setFrom(new InternetAddress(getFromAddress()));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(u.getEmail()));
    msg.setSubject(title);
    Multipart mp = new MimeMultipart("alternative");
    BodyPart bp = new MimeBodyPart();
    bp.setContent(html, "text/html");
    mp.addBodyPart(bp);

    bp = new MimeBodyPart();
    bp.setContent(plainText, "text/plain");
    mp.addBodyPart(bp);

    msg.setContent(mp);

    Transport.send(msg);
}

From source file:hudson.maven.reporters.MavenMailerTest.java

/**
* Test using the list of recipients of TAG ciManagement defined in
* ModuleRoot for de root module, and the recipients defined in moduleA for
* moduleA./*from ww  w. j  ava  2s  .c o  m*/
* 
* @throws Exception
*/
@Test
@Bug(6421)
public void testCiManagementNotificationModule() throws Exception {

    JenkinsLocationConfiguration.get().setAdminAddress(EMAIL_ADMIN);
    Mailbox otherInbox = Mailbox.get(new InternetAddress(EMAIL_OTHER));
    Mailbox someInbox = Mailbox.get(new InternetAddress(EMAIL_SOME));
    Mailbox jenkinsConfiguredInbox = Mailbox.get(new InternetAddress(EMAIL_JENKINS_CONFIGURED));
    otherInbox.clear();
    someInbox.clear();
    jenkinsConfiguredInbox.clear();

    j.configureDefaultMaven();
    MavenModuleSet mms = j.createMavenProject();
    mms.setGoals("test");
    mms.setScm(new ExtractResourceSCM(getClass().getResource("/hudson/maven/JENKINS-1201-module-defined.zip")));
    MavenMailer m = new MavenMailer();
    m.recipients = EMAIL_JENKINS_CONFIGURED;
    m.perModuleEmail = true;
    mms.getReporters().add(m);

    j.assertBuildStatus(Result.FAILURE, mms.scheduleBuild2(0).get());

    assertEquals(1, otherInbox.size());
    assertEquals(1, someInbox.size());
    assertEquals(2, jenkinsConfiguredInbox.size());

    Message message = otherInbox.get(0);
    assertEquals(2, message.getAllRecipients().length);
    assertContainsRecipient(EMAIL_OTHER, message);
    assertContainsRecipient(EMAIL_JENKINS_CONFIGURED, message);

    message = someInbox.get(0);
    assertEquals(2, message.getAllRecipients().length);
    assertContainsRecipient(EMAIL_SOME, message);
    assertContainsRecipient(EMAIL_JENKINS_CONFIGURED, message);

    message = jenkinsConfiguredInbox.get(0);
    assertEquals(2, message.getAllRecipients().length);
    assertContainsRecipient(EMAIL_JENKINS_CONFIGURED, message);

    message = jenkinsConfiguredInbox.get(1);
    assertEquals(2, message.getAllRecipients().length);
    assertContainsRecipient(EMAIL_JENKINS_CONFIGURED, message);

}

From source file:com.waveerp.sendMail.java

public void sendMsgTLS(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc) throws Exception {

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.port", strPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }/* ww w .ja  v  a2  s . co m*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(strSource));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination));
        message.setSubject(strSubject);
        message.setText(strMsg);

        Transport.send(message);

        //System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

    log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass);

    //Email email = new SimpleEmail();
    //email.setHostName(strHost);
    //email.setSmtpPort( Integer.parseInt(strPort) );
    //email.setAuthenticator(new DefaultAuthenticator(strUser, strPass01));
    //email.setTLS(true);
    //email.setFrom(strSource, strSourceDesc);
    //email.setSubject(strSubject);
    //email.setMsg(strMsg);

    //email.addTo(strDestination, strDestDesc);
    //email.send();

}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Filters a list of emails : removes illegal addresses
 * //w  w w.  ja v a  2  s.co  m
 * @param email List of emails
 * @return An Array containing the correct adresses
 */
private static InternetAddress[] toInternetAddresses(String email) throws AddressException {
    String[] mails = parseAddresses(email);
    if (mails == null) {
        return null;
    }

    InternetAddress[] address = new InternetAddress[mails.length];
    for (int i = 0; i < mails.length; i++) {
        address[i] = new InternetAddress(mails[i]);
    }
    return address;
}

From source file:mitm.application.djigzo.james.mailets.MailAddressHandlerTest.java

@Test
public void mailAddressHandlerRetryEvent() throws Exception {
    final int retries = 2;

    final MutableInt count = new MutableInt();

    final MutableInt eventCount = new MutableInt();

    MailAddressHandler.HandleUserEventHandler eventHandler = new MailAddressHandler.HandleUserEventHandler() {
        @Override//from www  .j a  v a  2  s .  c  o  m
        public void handleUser(User user) throws MessagingException {
            count.increment();

            throw new ConstraintViolationException("Dummy ConstraintViolationException", null, "");
        }
    };

    DatabaseActionRetryEvent retryEvent = new DatabaseActionRetryEvent() {
        @Override
        public void onRetry() {
            eventCount.increment();
        }
    };

    MailAddressHandler handler = new MailAddressHandler(sessionManager, userWorkflow, actionExecutor,
            eventHandler, retries, retryEvent);

    Collection<MailAddress> recipients = MailAddressUtils
            .fromAddressArrayToMailAddressList(new InternetAddress("test@example.com"));

    try {
        handler.handleMailAddresses(recipients);

        fail();
    } catch (MessagingException e) {
        assertTrue(ExceptionUtils.getRootCause(e) instanceof ConstraintViolationException);
    }

    assertEquals(retries + 1, count.intValue());
    assertEquals(retries, eventCount.intValue());
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.MailUsersServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    VitroRequest vreq = new VitroRequest(request);

    String confirmpage = "/confirmUserMail.jsp";
    String errpage = "/contact_err.jsp";
    String status = null; // holds the error status

    if (!FreemarkerEmailFactory.isConfigured(vreq)) {
        status = "This application has not yet been configured to send mail. "
                + "Email properties must be specified in the configuration properties file.";
        response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status);
        return;//from w w w.j  a v a2 s .c  o m
    }

    String SPAM_MESSAGE = "Your message was flagged as spam.";

    boolean probablySpam = false;
    String spamReason = "";

    String originalReferer = (String) request.getSession().getAttribute("commentsFormReferer");
    request.getSession().removeAttribute("commentsFormReferer");
    if (originalReferer == null) {
        originalReferer = "none";
        // (the following does not support cookie-less browsing:)
        // probablySpam = true;
        // status = SPAM_MESSAGE;
    } else {
        String referer = request.getHeader("Referer");
        //Review how spam works?
        /*if (referer.indexOf("comments")<0 && referer.indexOf("correction")<0) {
        probablySpam=true;
        status = SPAM_MESSAGE ;
        spamReason = "The form was not submitted from the Contact Us or Corrections page.";
        }*/
    }

    String formType = vreq.getParameter("DeliveryType");
    List<String> deliverToArray = null;
    int recipientCount = 0;
    String deliveryfrom = null;

    // get Individuals that the User mayEditAs
    deliverToArray = getEmailsForAllUserAccounts(vreq);

    //Removed all form type stuff b/c recipients pre-configured
    recipientCount = (deliverToArray == null) ? 0 : deliverToArray.size();

    if (recipientCount == 0) {
        //log.error("recipientCount is 0 when DeliveryType specified as \""+formType+"\"");
        throw new Error("To establish the Contact Us mail capability the system administrators must  "
                + "specify at least one email address in the current portal.");
    }

    // obtain passed in form data with a simple trim on the values
    String webusername = vreq.getParameter("webusername");// Null.trim(); will give you an exception
    String webuseremail = vreq.getParameter("webuseremail");//.trim();
    String comments = vreq.getParameter("s34gfd88p9x1"); //what does this string signify?
    //webusername = "hjk54";
    //webuseremail = "hjk54@cornell.edu";
    //comments = "following are comments";

    webusername = webusername.trim();
    deliveryfrom = webuseremail;
    comments = comments.trim();
    //Removed spam filtering code

    StringBuffer msgBuf = new StringBuffer(); // contains the intro copy for the body of the email message
    String lineSeparator = System.getProperty("line.separator"); // \r\n on windows, \n on unix
    // from MyLibrary
    msgBuf.setLength(0);
    //msgBuf.append("Content-Type: text/html; charset='us-ascii'" + lineSeparator);
    msgBuf.append("<html>" + lineSeparator);
    msgBuf.append("<head>" + lineSeparator);
    msgBuf.append("<style>a {text-decoration: none}</style>" + lineSeparator);
    msgBuf.append("<title>" + deliveryfrom + "</title>" + lineSeparator);
    msgBuf.append("</head>" + lineSeparator);
    msgBuf.append("<body>" + lineSeparator);
    msgBuf.append("<h4>" + deliveryfrom + "</h4>" + lineSeparator);
    msgBuf.append("<h4>From: " + webusername + " (" + webuseremail + ")" + " at IP address "
            + request.getRemoteAddr() + "</h4>" + lineSeparator);

    //Don't need any 'likely viewing page' portion to be emailed out to the others

    msgBuf.append(lineSeparator + "</i></p><h3>Comments:</h3>" + lineSeparator);
    if (comments == null || comments.equals("")) {
        msgBuf.append("<p>BLANK MESSAGE</p>");
    } else {
        msgBuf.append("<p>" + comments + "</p>");
    }
    msgBuf.append("</body>" + lineSeparator);
    msgBuf.append("</html>" + lineSeparator);

    String msgText = msgBuf.toString();

    Calendar cal = Calendar.getInstance();

    /* outFile.println("<hr/>");
     outFile.println();
     outFile.println("<p>"+cal.getTime()+"</p>");
     outFile.println();
     if (probablySpam) {
    outFile.println("<p>REJECTED - SPAM</p>");
    outFile.println("<p>"+spamReason+"</p>");
    outFile.println();
     }
     outFile.print( msgText );
     outFile.println();
     outFile.println();
     outFile.flush();
     // outFile.close();
    */

    Session s = FreemarkerEmailFactory.getEmailSession(vreq);
    //s.setDebug(true);
    try {
        // Construct the message
        MimeMessage msg = new MimeMessage(s);
        log.debug("trying to send message from servlet");

        // Set the from address
        msg.setFrom(new InternetAddress(webuseremail));

        // Set the recipient address

        if (recipientCount > 0) {
            InternetAddress[] address = new InternetAddress[recipientCount];
            for (int i = 0; i < recipientCount; i++) {
                address[i] = new InternetAddress(deliverToArray.get(i));
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        }

        // Set the subject and text
        msg.setSubject(deliveryfrom);

        // add the multipart to the message
        msg.setContent(msgText, "text/html");

        // set the Date: header
        msg.setSentDate(new Date());

        log.debug("sending from servlet");

        //if (!probablySpam)
        Transport.send(msg); // try to send the message via smtp - catch error exceptions

    } catch (AddressException e) {
        status = "Please supply a valid email address.";
        log.debug("Error - status is " + status);
    } catch (SendFailedException e) {
        status = "The system was unable to deliver your mail.  Please try again later.  [SEND FAILED]";
        log.error("Error - status is " + status);
    } catch (MessagingException e) {
        status = "The system was unable to deliver your mail.  Please try again later.  [MESSAGING]";
        log.error("Error - status is " + status, e);
    }

    //outFile.flush();
    //outFile.close();

    // Redirect to the appropriate confirmation page
    if (status == null && !probablySpam) {
        // message was sent successfully
        response.sendRedirect("test?bodyJsp=" + confirmpage);
    } else {
        // exception occurred
        response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status);
    }

}

From source file:mitm.application.djigzo.james.matchers.MailAddressMatcherTest.java

@Test
public void mailAddressMatcherRetryEvent() throws Exception {
    final int retries = 4;

    final MutableInt count = new MutableInt();

    final MutableInt eventCount = new MutableInt();

    DatabaseActionRetryEvent retryEvent = new DatabaseActionRetryEvent() {
        @Override//w  w  w.java 2s .c o  m
        public void onRetry() {
            eventCount.increment();
        }
    };

    MailAddressMatcher.HasMatchEventHandler handler = new MailAddressMatcher.HasMatchEventHandler() {
        @Override
        public boolean hasMatch(User user) throws MessagingException {
            count.increment();

            throw new ConstraintViolationException("Dummy ConstraintViolationException", null, "");
        }
    };

    MailAddressMatcher matcher = new MailAddressMatcher(sessionManager, userWorkflow, actionExecutor, handler,
            retries, retryEvent);

    Collection<MailAddress> recipients = MailAddressUtils
            .fromAddressArrayToMailAddressList(new InternetAddress("test@example.com"));

    try {
        matcher.getMatchingMailAddresses(recipients);
    } catch (MessagingException e) {
        /*
         * Must be caused by ConstraintViolationException
         */
        assertTrue(ExceptionUtils.getRootCause(e) instanceof ConstraintViolationException);
    }

    assertEquals(retries + 1, count.intValue());
    assertEquals(retries, eventCount.intValue());
}

From source file:com.email.SendEmail.java

/**
 * Sends a single email and uses account based off of the section that the
 * email comes from after email is sent the attachments are gathered
 * together and collated into a single PDF file and a history entry is
 * created based off of that entry// www  .jav a  2s  .c  o  m
 *
 * @param eml EmailOutModel
 */
public static void sendEmails(EmailOutModel eml) {
    SystemEmailModel account = null;

    String section = eml.getSection();
    if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED")
            || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) {
        section = eml.getCaseType();
    }

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(section)) {
            account = acc;
            break;
        }
    }

    //Account Exists?
    if (account != null) {
        //Case Location
        String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG"))
                ? FileService.getCaseFolderORGCSCLocation(eml)
                : FileService.getCaseFolderLocation(eml);

        //Attachment List
        boolean allFilesExists = true;
        List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId());

        for (EmailOutAttachmentModel attach : attachmentList) {
            File attachment = new File(casePath + attach.getFileName());
            boolean exists = attachment.exists();
            if (exists == false) {
                allFilesExists = false;
                SECExceptionsModel item = new SECExceptionsModel();
                item.setClassName("SendEmail");
                item.setMethodName("sendEmails");
                item.setExceptionType("FileMissing");
                item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId()
                        + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator()
                        + "File: " + attachment);

                ExceptionHandler.HandleNoException(item);

                break;
            } else {
                if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))
                        || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) {
                    if (!attachment.renameTo(attachment)) {
                        allFilesExists = false;
                        SECExceptionsModel item = new SECExceptionsModel();
                        item.setClassName("SendEmail");
                        item.setMethodName("sendEmails");
                        item.setExceptionType("File In Use");
                        item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId()
                                + System.lineSeparator() + "EmailSubject: " + eml.getSubject()
                                + System.lineSeparator() + "File: " + attachment);

                        ExceptionHandler.HandleNoException(item);
                        break;
                    }
                }
            }
        }

        if (allFilesExists) {
            //Set up Initial Merge Utility
            PDFMergerUtility ut = new PDFMergerUtility();

            //List ConversionPDFs To Delete Later
            List<String> tempPDFList = new ArrayList<>();

            //create email message body
            Date emailSentTime = new Date();
            String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime);

            //Add Email Body To PDF Merge
            try {
                ut.addSource(casePath + emailPDFname);
                tempPDFList.add(casePath + emailPDFname);
            } catch (FileNotFoundException ex) {
                ExceptionHandler.Handle(ex);
            }

            //Get parts
            String FromAddress = account.getEmailAddress();
            String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";"));
            String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";"));
            String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";"));
            String emailSubject = eml.getSubject();
            String emailBody = eml.getBody();

            //Set Email Parts
            Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
            Properties properties = EmailProperties.setEmailOutProperties(account);
            Session session = Session.getInstance(properties, auth);
            MimeMessage smessage = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            //Add Parts to Email Message
            try {
                smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
                for (String To : TOAddressess) {
                    if (EmailValidator.getInstance().isValid(To)) {
                        smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                    }
                }
                for (String CC : CCAddressess) {
                    if (EmailValidator.getInstance().isValid(CC)) {
                        smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC));
                    }
                }
                for (String BCC : BCCAddressess) {
                    if (EmailValidator.getInstance().isValid(BCC)) {
                        smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC));
                    }
                }
                smessage.setSubject(emailSubject);

                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(emailBody, "text/plain");
                multipart.addBodyPart(messageBodyPart);

                //get attachments
                for (EmailOutAttachmentModel attachment : attachmentList) {
                    String fileName = attachment.getFileName();
                    String extension = FilenameUtils.getExtension(fileName);

                    //Convert attachments to PDF
                    //If Image
                    if (FileService.isImageFormat(fileName)) {
                        fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Word Doc
                    } else if (extension.equals("docx") || extension.equals("doc")) {
                        fileName = WordToPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Text File
                    } else if ("txt".equals(extension)) {
                        fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If PDF
                    } else if (FilenameUtils.getExtension(fileName).equals("pdf")) {

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }
                    }

                    DataSource source = new FileDataSource(casePath + fileName);
                    messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(fileName);
                    multipart.addBodyPart(messageBodyPart);
                }
                smessage.setContent(multipart);

                //Send Message
                if (Global.isOkToSendEmail()) {
                    Transport.send(smessage);
                } else {
                    Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject);
                }

                //DocumentFileName
                String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject())
                        .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf";

                //Set Merge File Destination
                ut.setDestinationFileName(casePath + savedDoc);

                //Try to Merge
                try {
                    ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
                } catch (IOException ex) {
                    ExceptionHandler.Handle(ex);
                }

                //Add emailBody Activity
                addEmailActivity(eml, savedDoc, emailSentTime);

                //Copy to related case folders
                if (section.equals("MED")) {
                    List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml);
                    if (relatedMedList.size() > 0) {
                        for (RelatedCaseModel related : relatedMedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                } else {
                    //This is blanket and should grab all related cases. (UNTESTED outside of CMDS)
                    List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml);
                    if (relatedList.size() > 0) {
                        for (EmailOutRelatedCaseModel related : relatedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationEmailOutRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                }

                //Clean SQL entries
                EmailOut.deleteEmailEntry(eml.getId());
                EmailOutAttachment.deleteAttachmentsForEmail(eml.getId());
                EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId());

                //Clean up temp PDFs
                for (String tempPDF : tempPDFList) {
                    new File(tempPDF).delete();
                }

            } catch (AddressException ex) {
                ExceptionHandler.Handle(ex);
            } catch (MessagingException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}