Example usage for javax.mail.internet AddressException getRef

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

Introduction

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

Prototype

public String getRef() 

Source Link

Document

Get the string that was being parsed when the error was detected (null if not relevant).

Usage

From source file:com.flexive.shared.FxMailUtils.java

/**
 * Sends an email/*from   w  w w.j a v a2s .c o  m*/
 *
 * @param SMTPServer      IP Address of the SMTP server
 * @param subject         subject of the email
 * @param textBody        plain text
 * @param htmlBody        html text
 * @param to              recipient
 * @param cc              cc recepient
 * @param bcc             bcc recipient
 * @param from            sender
 * @param replyTo         reply-to address
 * @param mimeAttachments strings containing mime encoded attachments
 * @throws FxApplicationException on errors
 */
public static void sendMail(String SMTPServer, String subject, String textBody, String htmlBody, String to,
        String cc, String bcc, String from, String replyTo, String... mimeAttachments)
        throws FxApplicationException {

    try {
        // Set the mail server
        java.util.Properties properties = System.getProperties();
        if (SMTPServer != null)
            properties.put("mail.smtp.host", SMTPServer);

        // Get a session and create a new message
        javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
        MimeMessage msg = new MimeMessage(session);

        // Set the sender
        if (StringUtils.isBlank(from))
            msg.setFrom(); // Uses local IP Adress and the user under which the server is running
        else {
            msg.setFrom(createAddress(from));
        }

        if (!StringUtils.isBlank(replyTo))
            msg.setReplyTo(encodePersonal(InternetAddress.parse(replyTo, false)));

        // Set the To, Cc and Bcc fields
        if (!StringUtils.isBlank(to))
            msg.setRecipients(MimeMessage.RecipientType.TO, encodePersonal(InternetAddress.parse(to, false)));
        if (!StringUtils.isBlank(cc))
            msg.setRecipients(MimeMessage.RecipientType.CC, encodePersonal(InternetAddress.parse(cc, false)));
        if (!StringUtils.isBlank(bcc))
            msg.setRecipients(MimeMessage.RecipientType.BCC, encodePersonal(InternetAddress.parse(bcc, false)));

        // Set the subject
        msg.setSubject(subject, "UTF-8");

        String sMainType = "Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"";

        StringBuilder body = new StringBuilder(5000);

        if (mimeAttachments.length > 0) {
            sMainType = "Multipart/Mixed;\n\tboundary=\"" + BOUNDARY2 + "\"";
            body.append("This is a multi-part message in MIME format.\n\n");
            body.append("--" + BOUNDARY2 + "\n");
            body.append("Content-Type: Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"\n\n\n");
        }

        if (textBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/plain; charset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            body.append(encodeQuotedPrintable(textBody)).append("\n");
        }
        if (htmlBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/html;\n\tcharset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            if (htmlBody.toLowerCase().indexOf("<html>") < 0) {
                body.append("<HTML><HEAD>\n<TITLE></TITLE>\n");
                body.append(
                        "<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Dutf-8\"></HEAD>\n<BODY>\n");
                body.append(encodeQuotedPrintable(htmlBody)).append("</BODY></HTML>\n");
            } else
                body.append(encodeQuotedPrintable(htmlBody)).append("\n");
        }

        body.append("\n--" + BOUNDARY1 + "--\n");

        if (mimeAttachments.length > 0) {
            for (String mimeAttachment : mimeAttachments) {
                body.append("\n--" + BOUNDARY2 + "\n");
                body.append(mimeAttachment).append("\n");
            }
            body.append("\n--" + BOUNDARY2 + "--\n");
        }

        msg.setDataHandler(
                new javax.activation.DataHandler(new ByteArrayDataSource(body.toString(), sMainType)));

        // Set the header
        msg.setHeader("X-Mailer", "JavaMailer");

        // Set the sent date
        msg.setSentDate(new java.util.Date());

        // Send the message
        javax.mail.Transport.send(msg);
    } catch (AddressException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.address", e.getRef());
    } catch (javax.mail.MessagingException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (IOException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (EncoderException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    }
}

From source file:net.sourceforge.vulcan.mailer.EmailPlugin.java

private void sendMessages(BuildCompletedEvent event, final ProjectConfigDto projectConfig,
        final Map<Locale, List<String>> subscribers) {
    for (Map.Entry<Locale, List<String>> ent : subscribers.entrySet()) {
        try {/*  w w w  . j  a va2 s. c om*/
            final URL sandboxURL = generateSandboxURL(projectConfig);
            final URL statusURL = generateStatusURL();
            URL trackerURL = null;

            if (StringUtils.isNotBlank(projectConfig.getBugtraqUrl())) {
                trackerURL = new URL(projectConfig.getBugtraqUrl());
            }

            final Document document = projectDomBuilder.createProjectDocument(event.getStatus(), ent.getKey());

            final String content = generateXhtml(document, sandboxURL, statusURL, trackerURL, ent.getKey());

            final MimeMessage message = messageAssembler.constructMessage(
                    StringUtils.join(ent.getValue().iterator(), ","), config, event.getStatus(), content);

            sendMessage(message);
        } catch (AddressException e) {
            eventHandler.reportEvent(new ErrorEvent(this, "errors.address.exception",
                    new Object[] { e.getRef(), e.getMessage() }, e));
        } catch (MessagingException e) {
            eventHandler.reportEvent(
                    new ErrorEvent(this, "errors.messaging.exception", new Object[] { e.getMessage() }, e));
        } catch (Exception e) {
            eventHandler
                    .reportEvent(new ErrorEvent(this, "errors.exception", new Object[] { e.getMessage() }, e));
        }
    }
}

From source file:com.cubusmail.gwtui.server.services.MailboxService.java

public void saveMessageAsDraft(GWTMessage message) throws Exception {

    try {//ww w  . java2s.  co  m
        log.debug("saving message to draft...");
        MessageHandler messageHandler = SessionManager.get().getCurrentComposeMessage();
        IMailbox mailbox = SessionManager.get().getMailbox();
        IMailFolder draftFolder = mailbox.getDraftFolder();
        messageHandler.setGWTMessage(message);
        messageHandler.saveToFolder(draftFolder, true);

        // if there is the original message to delete
        if (message.getId() > 0) {
            long[] deleteId = new long[] { message.getId() };
            deleteMessages(deleteId);
        }
        log.debug("...successful");
    } catch (AddressException e) {
        log.error(e.getMessage(), e);
        throw new GWTInvalidAddressException(e.getMessage(), e.getRef());
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        throw new GWTMessageException(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new GWTMessageException(e.getMessage());
    }
}

From source file:nl.nn.adapterframework.core.IbisException.java

public String getExceptionSpecificDetails(Throwable t) {
    String result = null;/*from   www.j a va2s.c  om*/
    if (t instanceof AddressException) {
        AddressException ae = (AddressException) t;
        String parsedString = ae.getRef();
        if (StringUtils.isNotEmpty(parsedString)) {
            result = addPart(result, " ", "[" + parsedString + "]");
        }
        int column = ae.getPos() + 1;
        if (column > 0) {
            result = addPart(result, " ", "at column [" + column + "]");
        }
    }
    if (t instanceof SAXParseException) {
        SAXParseException spe = (SAXParseException) t;
        int line = spe.getLineNumber();
        int col = spe.getColumnNumber();
        String sysid = spe.getSystemId();

        String locationInfo = null;
        if (StringUtils.isNotEmpty(sysid)) {
            locationInfo = "SystemId [" + sysid + "]";
        }
        if (line >= 0) {
            locationInfo = addPart(locationInfo, " ", "line [" + line + "]");
        }
        if (col >= 0) {
            locationInfo = addPart(locationInfo, " ", "column [" + col + "]");
        }
        result = addPart(locationInfo, ": ", result);
    }
    if (t instanceof TransformerException) {
        TransformerException te = (TransformerException) t;
        SourceLocator locator = te.getLocator();
        if (locator != null) {
            int line = locator.getLineNumber();
            int col = locator.getColumnNumber();
            String sysid = locator.getSystemId();

            String locationInfo = null;
            if (StringUtils.isNotEmpty(sysid)) {
                locationInfo = "SystemId [" + sysid + "]";
            }
            if (line >= 0) {
                locationInfo = addPart(locationInfo, " ", "line [" + line + "]");
            }
            if (col >= 0) {
                locationInfo = addPart(locationInfo, " ", "column [" + col + "]");
            }
            result = addPart(locationInfo, ": ", result);
        }
    }
    if (t instanceof SQLException) {
        SQLException sqle = (SQLException) t;
        int errorCode = sqle.getErrorCode();
        String sqlState = sqle.getSQLState();
        if (errorCode != 0) {
            result = addPart("errorCode [" + errorCode + "]", ", ", result);
        }
        if (StringUtils.isNotEmpty(sqlState)) {
            result = addPart("SQLState [" + sqlState + "]", ", ", result);
        }
    }
    return result;
}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Extracts properties and text from an EML Document input stream.
 *
 * @param stream/*from  w ww.  j  av a  2  s.c o m*/
 *            the stream
 * @param handler
 *            the handler
 * @param metadata
 *            the metadata
 * @param context
 *            the context
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();

    Properties props = System.getProperties();
    Session mailSession = Session.getDefaultInstance(props, null);

    try {
        MimeMessage message = new MimeMessage(mailSession, stream);

        String subject = message.getSubject();
        String from = this.convertAddressesToString(message.getFrom());
        // Recipients :
        String messageException = "";
        String to = "";
        String cc = "";
        String bcc = "";
        try {
            // QVIDMS-2004 Added because of bug in Mail Api
            to = this.convertAddressesToString(message.getRecipients(Message.RecipientType.TO));
            cc = this.convertAddressesToString(message.getRecipients(Message.RecipientType.CC));
            bcc = this.convertAddressesToString(message.getRecipients(Message.RecipientType.BCC));
        } catch (AddressException e) {
            e.printStackTrace();
            messageException = e.getRef();
            if (messageException.indexOf("recipients:") != -1) {
                to = messageException.substring(0, messageException.indexOf(":"));
            }
        }
        metadata.set(Office.AUTHOR, from);
        metadata.set(DublinCore.TITLE, subject);
        metadata.set(DublinCore.SUBJECT, subject);

        xhtml.element("h1", subject);

        xhtml.startElement("dl");
        header(xhtml, "From", MimeUtility.decodeText(from));
        header(xhtml, "To", MimeUtility.decodeText(to.toString()));
        header(xhtml, "Cc", MimeUtility.decodeText(cc.toString()));
        header(xhtml, "Bcc", MimeUtility.decodeText(bcc.toString()));

        // // Parse message
        // if (message.getContent() instanceof MimeMultipart) {
        // // Multipart message, call matching method
        // MimeMultipart multipart = (MimeMultipart) message.getContent();
        // this.extractMultipart(xhtml, multipart, context);

        List<String> attachmentList = new ArrayList<String>();
        // prepare attachments
        prepareExtractMultipart(xhtml, message, null, context, attachmentList);
        if (attachmentList.size() > 0) {
            // TODO internationalization
            header(xhtml, "Attachments", attachmentList.toString());
        }
        xhtml.endElement("dl");

        // a supprimer si pb et a remplacer par ce qui est commenT
        adaptedExtractMultipart(xhtml, message, null, context);

        xhtml.endDocument();
    } catch (Exception e) {
        throw new TikaException("Error while processing message", e);
    }
}

From source file:org.hyperic.hq.ui.action.resource.common.monitor.alerts.config.AddOthersForm.java

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    if (!shouldValidate(mapping, request))
        return null;

    log.debug("validating email addresses: " + emailAddresses);
    ActionErrors errs = super.validate(mapping, request);
    if (null == errs && (emailAddresses == null || emailAddresses.length() == 0)) {
        // A special case, BaseValidatorForm will return null if Ok is
        // clicked and input is null, indicating a PrepareForm
        // action is occurring. This is tricky. However, it also
        // returns null if no validations failed. This is really
        // lame, in my opinion.
        return null;
    } else {//w  w w  . j  a  v  a  2s  .  co m
        errs = new ActionErrors();
    }

    try {
        InternetAddress[] addresses = InternetAddress.parse(emailAddresses);
    } catch (AddressException e) {
        if (e.getRef() == null) {
            ActionMessage err = new ActionMessage("alert.config.error.InvalidEmailAddresses", e.getMessage());
            errs.add("emailAddresses", err);
        } else {
            ActionMessage err = new ActionMessage("alert.config.error.InvalidEmailAddress", e.getRef(),
                    e.getMessage());
            errs.add("emailAddresses", err);
        }
    }

    return errs;
}