Example usage for javax.mail.internet InternetAddress parse

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

Introduction

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

Prototype

public static InternetAddress[] parse(String addresslist, boolean strict) throws AddressException 

Source Link

Document

Parse the given sequence of addresses into InternetAddress objects.

Usage

From source file:org.j2free.email.EmailService.java

private void send(InternetAddress from, String recipients, String subject, String body, ContentType contentType,
        Priority priority, boolean ccSender)
        throws AddressException, MessagingException, RejectedExecutionException {
    send(from, InternetAddress.parse(recipients, false), subject, body, contentType, priority, ccSender);
}

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

private InternetAddress getInternetAddress(String email) throws UnsupportedEncodingException, AddressException {
    email = email.trim();/*from  w  w w  .  jav  a 2  s.com*/
    if (!email.startsWith("\"")) {
        int ix = email.indexOf("<");
        if (ix >= 0) {
            String personal = email.substring(0, ix).trim();
            String address = email.substring(ix).trim();
            email = "\"" + personal + "\" " + address;
        }
    }
    InternetAddress ia[] = InternetAddress.parse(email, false);
    //build an InternetAddress with UTF8 personal, if present
    InternetAddress retia = InternetAddressUtils.toInternetAddress(ia[0].getAddress(), ia[0].getPersonal());
    return retia;
}

From source file:eu.optimis.sm.gui.server.ServiceManagerWebServiceImpl.java

public static void Send(final String username, final String password, String recipientEmail, String ccEmail,
        String title, String message) throws AddressException, MessagingException {
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    Properties props = System.getProperties();
    props.setProperty("mail.smtps.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.setProperty("mail.smtps.auth", "true");

    props.put("mail.smtps.quitwait", "false");

    Session session = Session.getInstance(props, null);
    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(username + "@gmail.com"));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

    if (ccEmail.length() > 0) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
    }/*w w  w  . j ava 2 s  .  c  o  m*/

    msg.setSubject(title);
    msg.setText(message, "utf-8");
    msg.setSentDate(new Date());

    SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
    t.connect("smtp.gmail.com", username, password);
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}

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

public Message reply(MailAccount account, MimeMessage orig, boolean replyToAll, boolean fromSent)
        throws MessagingException {
    MimeMessage reply = new MimeMessage(account.getMailSession());
    /*//from   ww w.  j a  va 2  s  . c  om
     * Have to manipulate the raw Subject header so that we don't lose
     * any encoding information.  This is safe because "Re:" isn't
     * internationalized and (generally) isn't encoded.  If the entire
     * Subject header is encoded, prefixing it with "Re: " still leaves
     * a valid and correct encoded header.
     */
    String subject = orig.getHeader("Subject", null);
    if (subject != null) {
        if (!subject.regionMatches(true, 0, "Re: ", 0, 4)) {
            subject = "Re: " + subject;
        }
        reply.setHeader("Subject", subject);
    }
    Address a[] = null;
    if (!fromSent)
        a = orig.getReplyTo();
    else {
        Address ax[] = orig.getRecipients(RecipientType.TO);
        if (ax != null) {
            a = new Address[1];
            a[0] = ax[0];
        }
    }
    reply.setRecipients(Message.RecipientType.TO, a);
    if (replyToAll) {
        Vector v = new Vector();
        Session session = account.getMailSession();
        // add my own address to list
        InternetAddress me = InternetAddress.getLocalAddress(session);
        if (me != null) {
            v.addElement(me);
        }
        // add any alternate names I'm known by
        String alternates = null;
        if (session != null) {
            alternates = session.getProperty("mail.alternates");
        }
        if (alternates != null) {
            eliminateDuplicates(v, InternetAddress.parse(alternates, false));
        }
        // should we Cc all other original recipients?
        String replyallccStr = null;
        boolean replyallcc = false;
        if (session != null) {
            replyallcc = PropUtil.getBooleanSessionProperty(session, "mail.replyallcc", false);
        }
        // add the recipients from the To field so far
        eliminateDuplicates(v, a);
        a = orig.getRecipients(Message.RecipientType.TO);
        a = eliminateDuplicates(v, a);
        if (a != null && a.length > 0) {
            if (replyallcc) {
                reply.addRecipients(Message.RecipientType.CC, a);
            } else {
                reply.addRecipients(Message.RecipientType.TO, a);
            }
        }
        a = orig.getRecipients(Message.RecipientType.CC);
        a = eliminateDuplicates(v, a);
        if (a != null && a.length > 0) {
            reply.addRecipients(Message.RecipientType.CC, a);
        }
        // don't eliminate duplicate newsgroups
        a = orig.getRecipients(MimeMessage.RecipientType.NEWSGROUPS);
        if (a != null && a.length > 0) {
            reply.setRecipients(MimeMessage.RecipientType.NEWSGROUPS, a);
        }
    }

    String msgId = orig.getHeader("Message-Id", null);
    if (msgId != null) {
        reply.setHeader("In-Reply-To", msgId);
    }

    /*
     * Set the References header as described in RFC 2822:
     *
     * The "References:" field will contain the contents of the parent's
     * "References:" field (if any) followed by the contents of the parent's
     * "Message-ID:" field (if any).  If the parent message does not contain
     * a "References:" field but does have an "In-Reply-To:" field
     * containing a single message identifier, then the "References:" field
     * will contain the contents of the parent's "In-Reply-To:" field
     * followed by the contents of the parent's "Message-ID:" field (if
     * any).  If the parent has none of the "References:", "In-Reply-To:",
     * or "Message-ID:" fields, then the new message will have no
     * "References:" field.
     */
    String refs = orig.getHeader("References", " ");
    if (refs == null) {
        // XXX - should only use if it contains a single message identifier
        refs = orig.getHeader("In-Reply-To", " ");
    }
    if (msgId != null) {
        if (refs != null) {
            refs = MimeUtility.unfold(refs) + " " + msgId;
        } else {
            refs = msgId;
        }
    }
    if (refs != null) {
        reply.setHeader("References", MimeUtility.fold(12, refs));
    }

    //try {
    //    setFlags(answeredFlag, true);
    //} catch (MessagingException mex) {
    //    // ignore it
    //}
    return reply;
}

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);//w w  w .jav a2 s .c om
            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;
}