Example usage for javax.mail.internet AddressException AddressException

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

Introduction

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

Prototype

public AddressException(String s) 

Source Link

Document

Constructs an AddressException with the specified detail message.

Usage

From source file:com.hs.mail.mailet.AliasingForwarding.java

public void service(Set<Recipient> recipients, SmtpMessage message) throws MessagingException {
    List<Recipient> newRecipients = new ArrayList<Recipient>();
    List<Recipient> errors = new ArrayList<Recipient>();
    for (Iterator<Recipient> it = recipients.iterator(); it.hasNext();) {
        Recipient rcpt = it.next();//from  w  w w .  j ava  2 s .  c  om
        User user = getUserManager().getUserByAddress(rcpt.getMailbox());
        if (user != null) {
            if (StringUtils.isNotEmpty(user.getForwardTo())) {
                // Forwarding takes precedence over local aliases
                try {
                    // TODO optionally remove the original recipient
                    it.remove();
                    Recipient forwardTo = new Recipient(user.getForwardTo(), false);
                    if (Config.isLocal(forwardTo.getHost())) {
                        long id = getUserManager().getUserID(forwardTo.getMailbox());
                        if (id != 0) {
                            forwardTo.setID(id);
                            newRecipients.add(forwardTo);
                        } else {
                            throw new AddressException("Forwarding address not found.");
                        }
                    } else {
                        message.setNode(SmtpMessage.ALL);
                        message.addRecipient(forwardTo);
                    }
                } catch (Exception e) {
                    // Forwarding address is invalid or not found.
                    StringBuffer errorBuffer = new StringBuffer(128).append("Failed to forwarding ")
                            .append(rcpt.getMailbox()).append(" to ").append(user.getForwardTo());
                    logger.error(errorBuffer.toString());
                    errors.add(rcpt);
                }
            } else {
                rcpt.setID(user.getID());
            }
        } else {
            // Try to find aliases
            List<Alias> expanded = getUserManager().expandAlias(rcpt.getMailbox());
            it.remove();
            if (CollectionUtils.isNotEmpty(expanded)) {
                for (Alias alias : expanded) {
                    newRecipients
                            .add(new Recipient((Long) alias.getDeliverTo(), (String) alias.getUserID(), false));
                }
            } else {
                String errorMessage = new StringBuffer(64).append(rcpt.getMailbox()).append("\r\n")
                        .append("The mailbox specified in the address does not exist.").toString();
                logger.error(new StringBuffer(128).append("Permanent exception delivering mail (")
                        .append(message.getName()).append("): ").append(errorMessage).append("\r\n")
                        .toString());
                errors.add(rcpt);
                message.appendErrorMessage(errorMessage);
            }
        }
    }

    if (newRecipients.size() > 0) {
        recipients.addAll(newRecipients);
    }
}

From source file:com.liferay.petra.mail.InternetAddressUtil.java

public static void validateAddress(Address address) throws AddressException {

    if (address == null) {
        throw new AddressException("Email address is null");
    }/*from  w  w  w .  ja  v a2s .  c  om*/

    String addressString = address.toString();

    for (char c : addressString.toCharArray()) {
        if ((c == CharPool.NEW_LINE) || (c == CharPool.RETURN)) {
            StringBundler sb = new StringBundler(3);

            sb.append("Email address ");
            sb.append(addressString);
            sb.append(" is invalid because it contains line breaks");

            throw new AddressException(sb.toString());
        }
    }
}

From source file:org.openmeetings.cli.Admin.java

private AdminUserDetails checkAdminDetails(String ctxName, String langPath) throws Exception {
    AdminUserDetails admin = new AdminUserDetails();
    admin.login = cmdl.getOptionValue("user");
    admin.email = cmdl.getOptionValue("email");
    admin.group = cmdl.getOptionValue("group");
    if (admin.login == null || admin.login.length() < InstallationConfig.USER_LOGIN_MINIMUM_LENGTH) {
        System.out.println("User login was not provided, or too short, should be at least "
                + InstallationConfig.USER_LOGIN_MINIMUM_LENGTH + " character long.");
        System.exit(1);/* www .j  a v  a 2  s  .  com*/
    }

    try {
        if (!MailUtil.matches(admin.email)) {
            throw new AddressException("Invalid address");
        }
        new InternetAddress(admin.email, true);
    } catch (AddressException ae) {
        System.out.println("Please provide non-empty valid email: '" + admin.email + "' is not valid.");
        System.exit(1);
    }
    if (admin.group == null || admin.group.length() < 1) {
        System.out.println("User group was not provided, or too short, should be at least 1 character long: "
                + admin.group);
        System.exit(1);
    }
    admin.pass = cmdl.getOptionValue("password");
    if (checkPassword(admin.pass)) {
        System.out.print("Please enter password for the user '" + admin.login + "':");
        admin.pass = new BufferedReader(new InputStreamReader(System.in)).readLine();
        if (checkPassword(admin.pass)) {
            System.out.println("Password was not provided, or too short, should be at least "
                    + InstallationConfig.USER_PASSWORD_MINIMUM_LENGTH + " character long.");
            System.exit(1);
        }
    }
    ImportInitvalues importInit = getApplicationContext(ctxName).getBean(ImportInitvalues.class);
    Map<String, String> tzMap = ImportHelper.getAllTimeZones(importInit.getTimeZones(langPath));
    admin.tz = null;
    if (cmdl.hasOption("tz")) {
        admin.tz = cmdl.getOptionValue("tz");
        admin.tz = tzMap.containsKey(admin.tz) ? admin.tz : null;
    }
    if (admin.tz == null) {
        System.out.println("Please enter timezone, Possible timezones are:");

        for (String tzIcal : tzMap.keySet()) {
            System.out.println(String.format("%1$-25s%2$s", "\"" + tzIcal + "\"", tzMap.get(tzIcal)));
        }
        System.exit(1);
    }
    return admin;
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send the message/*  www.  j  a  va2  s  . c  om*/
 *
 * @param msg
 *            the message to send
 * @param transport
 *            the transport used to send the message
 * @throws MessagingException
 *             If a messaging error occured
 * @throws AddressException
 *             If invalid address
 */
private static void sendMessage(Message msg, Transport transport) throws MessagingException, AddressException {
    if (msg.getAllRecipients() != null) {
        // Send the message
        transport.sendMessage(msg, msg.getAllRecipients());
    } else {
        throw new AddressException("Mail adress is null");
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave)
        throws Exception {
    MimeMessage msg = null;//from w w w.  j a v a 2  s .c om
    boolean success = true;

    String[] to = SimpleMessage.breakAddr(smsg.getTo());
    String[] cc = SimpleMessage.breakAddr(smsg.getCc());
    String[] bcc = SimpleMessage.breakAddr(smsg.getBcc());
    String replyTo = smsg.getReplyTo();

    msg = new MimeMessage(mainAccount.getMailSession());
    msg.setFrom(getInternetAddress(from));
    InternetAddress ia = null;

    //set the TO recipient
    for (int q = 0; q < to.length; q++) {
        //        Service.logger.debug("to["+q+"]="+to[q]);
        to[q] = to[q].replace(',', ' ');
        try {
            ia = getInternetAddress(to[q]);
        } catch (AddressException exc) {
            throw new AddressException(to[q]);
        }
        msg.addRecipient(Message.RecipientType.TO, ia);
    }

    //set the CC recipient
    for (int q = 0; q < cc.length; q++) {
        cc[q] = cc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(cc[q]);
        } catch (AddressException exc) {
            throw new AddressException(cc[q]);
        }
        msg.addRecipient(Message.RecipientType.CC, ia);
    }

    //set BCC recipients
    for (int q = 0; q < bcc.length; q++) {
        bcc[q] = bcc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(bcc[q]);
        } catch (AddressException exc) {
            throw new AddressException(bcc[q]);
        }
        msg.addRecipient(Message.RecipientType.BCC, ia);
    }

    //set reply to addr
    if (replyTo != null && replyTo.length() > 0) {
        Address[] replyaddr = new Address[1];
        replyaddr[0] = getInternetAddress(replyTo);
        msg.setReplyTo(replyaddr);
    }

    //add any header
    String headerLines[] = smsg.getHeaderLines();
    for (int i = 0; i < headerLines.length; ++i) {
        if (!headerLines[i].startsWith("Sonicle-reply-folder")) {
            msg.addHeaderLine(headerLines[i]);
        }
    }

    //add reply/references
    String inreplyto = smsg.getInReplyTo();
    String references[] = smsg.getReferences();
    String replyfolder = smsg.getReplyFolder();
    if (inreplyto != null) {
        msg.setHeader("In-Reply-To", inreplyto);
    }
    if (references != null && references[0] != null) {
        msg.setHeader("References", references[0]);
    }
    if (tosave) {
        if (replyfolder != null) {
            msg.setHeader("Sonicle-reply-folder", replyfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }

    //add forward data
    String forwardedfrom = smsg.getForwardedFrom();
    String forwardedfolder = smsg.getForwardedFolder();
    if (forwardedfrom != null) {
        msg.setHeader("Forwarded-From", forwardedfrom);
    }
    if (tosave) {
        if (forwardedfolder != null) {
            msg.setHeader("Sonicle-forwarded-folder", forwardedfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }
    //set the subject
    String subject = smsg.getSubject();
    try {
        //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null);
        subject = MimeUtility.encodeText(smsg.getSubject());
    } catch (Exception exc) {
    }
    msg.setSubject(subject);

    //set priority
    int priority = smsg.getPriority();
    if (priority != 3) {
        msg.setHeader("X-Priority", "" + priority);

        //set receipt
    }
    String receiptTo = from;
    try {
        receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null);
    } catch (Exception exc) {
    }
    if (smsg.getReceipt()) {
        msg.setHeader("Disposition-Notification-To", from);

        //see if there are any new attachments for the message
    }
    int noAttach;
    int newAttach;

    if (attachments == null) {
        newAttach = 0;
    } else {
        newAttach = attachments.size();
    }

    //get the array of the old attachments
    Part[] oldParts = smsg.getAttachments();

    //check if there are old attachments
    if (oldParts == null) {
        noAttach = 0;
    } else { //old attachments exist
        noAttach = oldParts.length;
    }

    if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) {
        // create the main Multipart
        MimeMultipart mp = new MimeMultipart("mixed");
        MimeMultipart unrelated = null;

        String textcontent = smsg.getTextContent();
        //if is text, or no alternative text is available, add the content as one single body part
        //else create a multipart/alternative with both rich and text mime content
        if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) {
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            mp.addBodyPart(mbp1);
        } else {
            MimeMultipart alternative = new MimeMultipart("alternative");
            //the rich part
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            //the text part
            MimeBodyPart mbp1 = new MimeBodyPart();

            /*          ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length());
             com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos);
             for(int i=0;i<textcontent.length();++i) {
             try {
             qpe.write(textcontent.charAt(i));
             } catch(IOException exc) {
             Service.logger.error("Exception",exc);
             }
             }
             textcontent=new String(bos.toByteArray());*/
            mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8"));
            //          mbp1.setHeader("Content-transfer-encoding","quoted-printable");

            alternative.addBodyPart(mbp1);
            alternative.addBodyPart(mbp2);

            MimeBodyPart altbody = new MimeBodyPart();
            altbody.setContent(alternative);

            mp.addBodyPart(altbody);
        }

        if (noAttach > 0) { //if there are old attachments
            // create the parts with the attachments
            //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach];
            //Part[] mbps2 = new Part[noAttach];

            //for(int e = 0;e < noAttach;e++) {
            //  mbps2[e] = (Part)oldParts[e];
            //}//end for e
            //add the old attachment parts
            for (int r = 0; r < noAttach; r++) {
                Object content = null;
                String contentType = null;
                String contentFileName = null;
                if (oldParts[r] instanceof Message) {
                    //                Service.logger.debug("Attachment is a message");
                    Message msgpart = (Message) oldParts[r];
                    MimeMessage mm = new MimeMessage(mainAccount.getMailSession());
                    mm.addFrom(msgpart.getFrom());
                    mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO));
                    mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC));
                    mm.setRecipients(Message.RecipientType.BCC,
                            msgpart.getRecipients(Message.RecipientType.BCC));
                    mm.setReplyTo(msgpart.getReplyTo());
                    mm.setSentDate(msgpart.getSentDate());
                    mm.setSubject(msgpart.getSubject());
                    mm.setContent(msgpart.getContent(), msgpart.getContentType());
                    content = mm;
                    contentType = "message/rfc822";
                } else {
                    //                Service.logger.debug("Attachment is not a message");
                    content = oldParts[r].getContent();
                    if (!(content instanceof MimeMultipart)) {
                        contentType = oldParts[r].getContentType();
                        contentFileName = oldParts[r].getFileName();
                    }
                }
                MimeBodyPart mbp = new MimeBodyPart();
                if (contentFileName != null) {
                    mbp.setFileName(contentFileName);
                    //              Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName);
                    contentType += "; name=\"" + contentFileName + "\"";
                }
                if (content instanceof MimeMultipart)
                    mbp.setContent((MimeMultipart) content);
                else
                    mbp.setDataHandler(new DataHandler(content, contentType));
                mp.addBodyPart(mbp);
            }

        } //end if, adding old attachments

        if (newAttach > 0) { //if there are new attachments
            // create the parts with the attachments
            MimeBodyPart[] mbps = new MimeBodyPart[newAttach];

            for (int e = 0; e < newAttach; e++) {
                mbps[e] = new MimeBodyPart();

                // attach the file to the message
                JsAttachment attach = (JsAttachment) attachments.get(e);
                UploadedFile upfile = getUploadedFile(attach.uploadId);
                FileDataSource fds = new FileDataSource(upfile.getFile());
                mbps[e].setDataHandler(new DataHandler(fds));
                // filename starts has format:
                // "_" + userid + sessionId + "_" + filename
                //
                if (attach.inline) {
                    mbps[e].setDisposition(Part.INLINE);
                }
                String contentFileName = attach.fileName.trim();
                mbps[e].setFileName(contentFileName);
                String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\"";
                mbps[e].setHeader("Content-type", contentType);
                if (attach.cid != null && attach.cid.trim().length() > 0) {
                    mbps[e].setHeader("Content-ID", "<" + attach.cid + ">");
                    mbps[e].setHeader("X-Attachment-Id", attach.cid);
                    mbps[e].setDisposition(Part.INLINE);
                    if (unrelated == null)
                        unrelated = new MimeMultipart("mixed");
                }
            } //end for e

            //add the new attachment parts
            if (unrelated == null) {
                for (int r = 0; r < newAttach; r++)
                    mp.addBodyPart(mbps[r]);
            } else {
                //mp becomes the related part with text parts and cids
                MimeMultipart related = mp;
                related.setSubType("related");
                //nest the related part into the mixed part
                mp = unrelated;
                MimeBodyPart mbd = new MimeBodyPart();
                mbd.setContent(related);
                mp.addBodyPart(mbd);
                for (int r = 0; r < newAttach; r++) {
                    if (mbps[r].getHeader("Content-ID") != null) {
                        related.addBodyPart(mbps[r]);
                    } else {
                        mp.addBodyPart(mbps[r]);
                    }
                }
            }

        } //end if, adding new attachments

        //
        //          msg.addHeaderLine("This is a multi-part message in MIME format.");
        // add the Multipart to the message
        msg.setContent(mp);

    } else { //end if newattach
        msg.setText(smsg.getContent());
    } //singlepart message

    msg.setSentDate(new java.util.Date());

    return msg;

}

From source file:com.sonicle.webtop.mail.Service.java

private SimpleMessage prepareMessage(JsMessage jsmsg, long msgId, boolean save, boolean isFax)
        throws Exception {
    PrivateEnvironment env = environment;
    UserProfile profile = env.getProfile();
    //expand multiple addresses
    ArrayList<String> aemails = new ArrayList<>();
    ArrayList<String> artypes = new ArrayList<>();
    for (JsRecipient jsrcpt : jsmsg.recipients) {
        String emails[] = StringUtils.split(jsrcpt.email, ';');
        for (String email : emails) {
            aemails.add(email);/*from  w  w  w  .  j  av a  2  s.c  o m*/
            artypes.add(jsrcpt.rtype);
        }
    }
    String emails[] = new String[aemails.size()];
    emails = (String[]) aemails.toArray(emails);
    String rtypes[] = new String[artypes.size()];
    rtypes = (String[]) artypes.toArray(rtypes);

    //String replyfolder = request.getParameter("replyfolder");
    //String inreplyto = request.getParameter("inreplyto");
    //String references = request.getParameter("references");

    //String forwardedfolder = request.getParameter("forwardedfolder");
    //String forwardedfrom = request.getParameter("forwardedfrom");

    //String subject = request.getParameter("subject");
    //String mime = request.getParameter("mime");
    //String sident = request.getParameter("identity");
    //String content = request.getParameter("content");
    //String msgid = request.getParameter("newmsgid");
    //String ssave = request.getParameter("save");
    //boolean save = (ssave != null && ssave.equals("true"));
    //String sreceipt = request.getParameter("receipt");
    //boolean receipt = (sreceipt != null && sreceipt.equals("true"));
    //String spriority = request.getParameter("priority");
    //boolean priority = (spriority != null && spriority.equals("true"));

    //boolean isFax = request.getParameter("fax") != null;

    String to = null;
    String cc = null;
    String bcc = null;
    for (int i = 0; i < emails.length; ++i) {
        //String email=decoder.decode(ByteBuffer.wrap(emails[i].getBytes())).toString();
        String email = emails[i];
        if (email == null || email.trim().length() == 0) {
            continue;
        }
        //Check for list
        boolean checkemail = true;
        boolean listdone = false;
        if (email.indexOf('@') < 0) {
            if (isFax && StringUtils.isNumeric(email)) {
                String faxpattern = getEnv().getCoreServiceSettings().getFaxPattern();
                String faxemail = faxpattern.replace("{number}", email).replace("{username}",
                        profile.getUserId());
                email = faxemail;
            }
        } else {
            //check for list if one email with domain equals one allowed service id
            InternetAddress ia = null;
            try {
                ia = new InternetAddress(email);
            } catch (AddressException exc) {

            }
            if (ia != null) {
                String iamail = ia.getAddress();
                String dom = iamail.substring(iamail.indexOf("@") + 1);
                CoreManager core = WT.getCoreManager();
                if (environment.getSession().isServiceAllowed(dom)) {
                    List<Recipient> rcpts = core.expandVirtualProviderRecipient(iamail);
                    for (Recipient rcpt : rcpts) {
                        String xemail = rcpt.getAddress();
                        String xpersonal = rcpt.getPersonal();
                        String xrtype = EnumUtils.toSerializedName(rcpt.getType());

                        if (xpersonal != null)
                            xemail = xpersonal + " <" + xemail + ">";

                        try {
                            checkEmail(xemail);
                            InternetAddress.parse(xemail.replace(',', ' '), true);
                        } catch (AddressException exc) {
                            throw new AddressException(
                                    lookupResource(MailLocaleKey.ADDRESS_ERROR) + " : " + xemail);
                        }
                        if (rtypes[i].equals("to")) {
                            if (xrtype.equals("to")) {
                                if (to == null)
                                    to = xemail;
                                else
                                    to += "; " + xemail;
                            } else if (xrtype.equals("cc")) {
                                if (cc == null)
                                    cc = xemail;
                                else
                                    cc += "; " + xemail;
                            } else if (xrtype.equals("bcc")) {
                                if (bcc == null)
                                    bcc = xemail;
                                else
                                    bcc += "; " + xemail;
                            }
                        } else if (rtypes[i].equals("cc")) {
                            if (cc == null)
                                cc = xemail;
                            else
                                cc += "; " + xemail;
                        } else if (rtypes[i].equals("bcc")) {
                            if (bcc == null)
                                bcc = xemail;
                            else
                                bcc += "; " + xemail;
                        }

                        listdone = true;
                        checkemail = false;
                    }
                }
            }
        }
        if (listdone) {
            continue;
        }

        if (checkemail) {
            try {
                checkEmail(email);
                //InternetAddress.parse(email.replace(',', ' '), false);
                getInternetAddress(email);
            } catch (AddressException exc) {
                Service.logger.error("Exception", exc);
                throw new AddressException(lookupResource(MailLocaleKey.ADDRESS_ERROR) + " : " + email);
            }
        }

        if (rtypes[i].equals("to")) {
            if (to == null) {
                to = email;
            } else {
                to += "; " + email;
            }
        } else if (rtypes[i].equals("cc")) {
            if (cc == null) {
                cc = email;
            } else {
                cc += "; " + email;
            }
        } else if (rtypes[i].equals("bcc")) {
            if (bcc == null) {
                bcc = email;
            } else {
                bcc += "; " + email;
            }
        }
    }

    //long id = Long.parseLong(msgid);
    SimpleMessage msg = new SimpleMessage(msgId);
    /*int idx = jsmsg.identity - 1;
    Identity from = null;
    if (idx >= 0) {
       from = mprofile.getIdentity(idx);
    }*/
    Identity from = mprofile.getIdentity(jsmsg.identityId);
    msg.setFrom(from);
    msg.setTo(to);
    msg.setCc(cc);
    msg.setBcc(bcc);
    msg.setSubject(jsmsg.subject);

    //TODO: fax coverpage - dismissed
    /*if (isFax) {
       String coverpage = request.getParameter("faxcover");
       if (coverpage != null) {
    if (coverpage.equals("none")) {
       msg.addHeaderLine("X-FAX-AutoCoverPage: No");
    } else {
       msg.addHeaderLine("X-FAX-AutoCoverPage: Yes");
       msg.addHeaderLine("X-FAX-Cover-Template: " + coverpage);
    }
       }
    }*/

    //TODO: custom headers keys
    /*String[] headersKeys = request.getParameterValues("headersKeys");
    String[] headersValues = request.getParameterValues("headersValues");
    if (headersKeys != null && headersValues != null && headersKeys.length == headersValues.length) {
       for (int i = 0; i < headersKeys.length; i++) {
    if (!headersKeys[i].equals("")) {
       msg.addHeaderLine(headersKeys[i] + ": " + headersValues[i]);
    }
       }
    }*/

    if (jsmsg.inreplyto != null) {
        msg.setInReplyTo(jsmsg.inreplyto);
    }
    if (jsmsg.references != null) {
        msg.setReferences(new String[] { jsmsg.references });
    }
    if (jsmsg.replyfolder != null) {
        msg.setReplyFolder(jsmsg.replyfolder);
    }

    if (jsmsg.forwardedfolder != null) {
        msg.setForwardedFolder(jsmsg.forwardedfolder);
    }
    if (jsmsg.forwardedfrom != null) {
        msg.setForwardedFrom(jsmsg.forwardedfrom);
    }

    msg.setReceipt(jsmsg.receipt);
    msg.setPriority(jsmsg.priority ? 1 : 3);
    if (jsmsg.format == null || jsmsg.format.equals("plain")) {
        msg.setContent(jsmsg.content);
    } else {
        if (jsmsg.format.equalsIgnoreCase("html")) {
            //TODO: change this weird matching of cids2urls!

            //CIDs
            String content = jsmsg.content;
            String pattern1 = RegexUtils
                    .escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&amp;service="
                            + SERVICE_ID + "&amp;action=PreviewAttachment&amp;nowriter=true&amp;uploadId=");
            String pattern2 = RegexUtils.escapeRegexSpecialChars("&amp;cid=");
            content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "cid:");
            pattern1 = RegexUtils.escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken()
                    + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId=");
            pattern2 = RegexUtils.escapeRegexSpecialChars("&cid=");
            content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "cid:");

            //URLs
            pattern1 = RegexUtils
                    .escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&amp;service="
                            + SERVICE_ID + "&amp;action=PreviewAttachment&amp;nowriter=true&amp;uploadId=");
            pattern2 = RegexUtils.escapeRegexSpecialChars("&amp;url=");
            content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "");
            pattern1 = RegexUtils.escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken()
                    + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId=");
            pattern2 = RegexUtils.escapeRegexSpecialChars("&url=");
            content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "");

            //My resources as cids?
            if (ss.isPublicResourceLinksAsInlineAttachments()) {
                ArrayList<JsAttachment> rescids = new ArrayList<>();
                String match = "\"" + URIUtils.concat(getEnv().getCoreServiceSettings().getPublicBaseUrl(),
                        ResourceRequest.URL);
                while (StringUtils.contains(content, match)) {
                    pattern1 = RegexUtils.escapeRegexSpecialChars(match);
                    Pattern pattern = Pattern.compile(pattern1 + "\\S*");
                    Matcher matcher = pattern.matcher(content);
                    matcher.find();
                    String matched = matcher.group();
                    String url = matched.substring(1, matched.length() - 1);
                    URI uri = new URI(url);

                    // Retrieve macthed URL 
                    // and save it locally
                    logger.debug("Downloading resource file as uploaded file from URL [{}]", url);
                    HttpClient httpCli = null;
                    try {
                        httpCli = HttpClientUtils.createBasicHttpClient(HttpClientUtils.configureSSLAcceptAll(),
                                uri);
                        InputStream is = HttpClientUtils.getContent(httpCli, uri);
                        String tag = "" + msgId;
                        String filename = PathUtils.getFileName(uri.getPath());
                        UploadedFile ufile = addAsUploadedFile(tag, filename,
                                ServletHelper.guessMediaType(filename), is);
                        rescids.add(new JsAttachment(ufile.getUploadId(), filename, ufile.getUploadId(), true,
                                ufile.getSize()));
                        content = matcher.replaceFirst("\"cid:" + ufile.getUploadId() + "\"");
                    } catch (IOException ex) {
                        throw new WTException(ex, "Unable to retrieve webcal [{0}]", uri);
                    } finally {
                        HttpClientUtils.closeQuietly(httpCli);
                    }
                }

                //add new resource cids as attachments
                if (rescids.size() > 0) {
                    if (jsmsg.attachments == null)
                        jsmsg.attachments = new ArrayList<>();
                    jsmsg.attachments.addAll(rescids);
                }
            }

            String textcontent = MailUtils.HtmlToText_convert(MailUtils.htmlunescapesource(content));
            String htmlcontent = MailUtils.htmlescapefixsource(content).trim();
            if (htmlcontent.length() < 6 || !htmlcontent.substring(0, 6).toLowerCase().equals("<html>")) {
                htmlcontent = "<html><header></header><body>" + htmlcontent + "</body></html>";
            }
            msg.setContent(htmlcontent, textcontent, "text/html");
        } else {
            msg.setContent(jsmsg.content, null, "text/" + jsmsg.format);
        }

    }
    return msg;
}

From source file:com.sonicle.webtop.mail.Service.java

private void checkEmail(String email) throws AddressException {
    int ix = email.indexOf('@');
    if (ix < 1) {
        throw new AddressException(email);
    }//  ww w .  j av  a 2  s . c  o m
    int ix2 = email.indexOf('@', ix + 1);
    if (ix2 >= 0) {
        int ixx = email.indexOf('<');
        if (ixx >= 0) {
            if (!(ix < ixx && ix2 > ixx)) {
                throw new AddressException(email);
            }
        } else {
            throw new AddressException(email);
        }
    }
}

From source file:org.apache.nifi.processors.standard.PutEmail.java

/**
 * @param context the current context/* www .ja va 2s.c  o  m*/
 * @param flowFile the current flow file
 * @param propertyDescriptor the property to evaluate
 * @return an InternetAddress[] parsed from the supplied property
 * @throws AddressException if the property cannot be parsed to a valid InternetAddress[]
 */
private InternetAddress[] toInetAddresses(final ProcessContext context, final FlowFile flowFile,
        PropertyDescriptor propertyDescriptor) throws AddressException {
    InternetAddress[] parse;
    String value = context.getProperty(propertyDescriptor).evaluateAttributeExpressions(flowFile).getValue();
    if (value == null || value.isEmpty()) {
        if (propertyDescriptor.isRequired()) {
            final String exceptionMsg = "Required property '" + propertyDescriptor.getDisplayName()
                    + "' evaluates to an empty string.";
            throw new AddressException(exceptionMsg);
        } else {
            parse = new InternetAddress[0];
        }
    } else {
        try {
            parse = InternetAddress.parse(value);
        } catch (AddressException e) {
            final String exceptionMsg = "Unable to parse a valid address for property '"
                    + propertyDescriptor.getDisplayName() + "' with value '" + value + "'";
            throw new AddressException(exceptionMsg);
        }
    }
    return parse;
}

From source file:org.apache.openmeetings.cli.Admin.java

private void checkAdminDetails() throws Exception {
    cfg.username = cmdl.getOptionValue("user");
    cfg.email = cmdl.getOptionValue("email");
    cfg.group = cmdl.getOptionValue("group");
    if (cfg.username == null || cfg.username.length() < USER_LOGIN_MINIMUM_LENGTH) {
        System.out.println("User login was not provided, or too short, should be at least "
                + USER_LOGIN_MINIMUM_LENGTH + " character long.");
        System.exit(1);/* w ww  . j a  v  a  2  s .  c  o m*/
    }

    try {
        if (cfg.email == null || !MailUtil.matches(cfg.email)) {
            throw new AddressException("Invalid address");
        }
        new InternetAddress(cfg.email, true);
    } catch (AddressException ae) {
        System.out.println("Please provide non-empty valid email: '" + cfg.email + "' is not valid.");
        System.exit(1);
    }
    if (cfg.group == null || cfg.group.length() < 1) {
        System.out.println(
                "User group was not provided, or too short, should be at least 1 character long: " + cfg.group);
        System.exit(1);
    }
    cfg.password = cmdl.getOptionValue("password");
    ConfigurationDao cfgDao = getApplicationContext().getBean(ConfigurationDao.class);
    if (invalidPassword(cfg.password, cfgDao)) {
        System.out.print("Please enter password for the user '" + cfg.username + "':");
        cfg.password = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)).readLine();
        if (invalidPassword(cfg.password, cfgDao)) {
            System.out.println("Password was not provided, or too short, should be at least "
                    + getMinPasswdLength(cfgDao) + " character long.");
            System.exit(1);
        }
    }
    Map<String, String> tzMap = ImportHelper.getAllTimeZones(TimeZone.getAvailableIDs());
    cfg.ical_timeZone = null;
    if (cmdl.hasOption("tz")) {
        cfg.ical_timeZone = cmdl.getOptionValue("tz");
        cfg.ical_timeZone = tzMap.containsKey(cfg.ical_timeZone) ? cfg.ical_timeZone : null;
    }
    if (cfg.ical_timeZone == null) {
        System.out.println("Please enter timezone, Possible timezones are:");

        for (Map.Entry<String, String> me : tzMap.entrySet()) {
            System.out.println(String.format("%1$-25s%2$s", "\"" + me.getKey() + "\"", me.getValue()));
        }
        System.exit(1);
    }
}

From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java

@Override
@Transactional(readOnly = false)/*www  . ja v a 2 s. c o  m*/
public boolean sendMessage(@NotNull final Message message)
        throws ObjectNotFoundException, SendFailedException, UnsupportedEncodingException {

    LOGGER.info("BEGIN : sendMessage()");
    LOGGER.info(addMessageIdToError(message) + "Sending message: {}", message.toString());

    try {
        final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        final MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);

        // process FROM addresses
        InternetAddress from;
        String appName = configService.getByName("app_title").getValue();

        //We used the configured outbound email address for every outgoing message
        //If a message was initiated by an end user, their name will be attached to the 'from' while
        //the configured outbound address will be the actual address used for example "Amy Aministrator (SSP) <myconfiguredaddress@foobar.com>"
        String name = appName + " Administrator";
        if (message.getSender() != null && !message.getSender().getEmailAddresses().isEmpty()
                && !message.getSender().getId().equals(Person.SYSTEM_ADMINISTRATOR_ID)) {
            InternetAddress[] froms = getEmailAddresses(message.getSender(), "from:", message.getId());
            if (froms.length > 0) {
                name = message.getSender().getFullName() + " (" + appName + ")";
            }
        }

        from = new InternetAddress(configService.getByName("outbound_email_address").getValue(), name);
        if (!this.validateEmail(from.getAddress())) {
            throw new AddressException("Invalid from: email address [" + from.getAddress() + "]");
        }

        mimeMessageHelper.setFrom(from);
        message.setSentFromAddress(from.toString());
        mimeMessageHelper.setReplyTo(from);
        message.setSentReplyToAddress(from.toString());

        // process TO addresses
        InternetAddress[] tos = null;
        if (message.getRecipient() != null && message.getRecipient().hasEmailAddresses()) { // NOPMD by jon.adams         
            tos = getEmailAddresses(message.getRecipient(), "to:", message.getId());
        } else {
            tos = getEmailAddresses(message.getRecipientEmailAddress(), "to:", message.getId());
        }
        if (tos.length > 0) {
            mimeMessageHelper.setTo(tos);
            message.setSentToAddresses(StringUtils.join(tos, ",").trim());
        } else {
            StringBuilder errorMsg = new StringBuilder();

            errorMsg.append(addMessageIdToError(message) + " Message " + message.toString()
                    + " could not be sent. No valid recipient email address found: '");

            if (message.getRecipient() != null) {
                errorMsg.append(message.getRecipient().getPrimaryEmailAddress());
            } else {
                errorMsg.append(message.getRecipientEmailAddress());
            }
            LOGGER.error(errorMsg.toString());
            throw new MessagingException(errorMsg.toString());
        }

        // process BCC addresses
        try {
            InternetAddress[] bccs = getEmailAddresses(getBcc(), "bcc:", message.getId());
            if (bccs.length > 0) {
                mimeMessageHelper.setBcc(bccs);
                message.setSentBccAddresses(StringUtils.join(bccs, ",").trim());
            }
        } catch (Exception exp) {
            LOGGER.warn("Unrecoverable errors were generated adding carbon copy to message: " + message.getId()
                    + "Attempt to send message still initiated.", exp);
        }

        // process CC addresses
        try {
            InternetAddress[] carbonCopies = getEmailAddresses(message.getCarbonCopy(), "cc:", message.getId());
            if (carbonCopies.length > 0) {
                mimeMessageHelper.setCc(carbonCopies);
                message.setSentCcAddresses(StringUtils.join(carbonCopies, ",").trim());
            }
        } catch (Exception exp) {
            LOGGER.warn("Unrecoverable errors were generated adding bcc to message: " + message.getId()
                    + "Attempt to send message still initiated.", exp);
        }

        mimeMessageHelper.setSubject(message.getSubject());
        mimeMessageHelper.setText(message.getBody());
        mimeMessage.setContent(message.getBody(), "text/html");

        send(mimeMessage);

        message.setSentDate(new Date());
        messageDao.save(message);
    } catch (final MessagingException e) {
        LOGGER.error("ERROR : sendMessage() : {}", e);
        handleSendMessageError(message);
        throw new SendFailedException(addMessageIdToError(message) + "The message parameters were invalid.", e);
    }

    LOGGER.info("END : sendMessage()");
    return true;
}