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) throws AddressException 

Source Link

Document

Parse the given comma separated sequence of addresses into InternetAddress objects.

Usage

From source file:org.apache.synapse.transport.mail.MailTransportSender.java

/**
 * Initialize the Mail sender and be ready to send messages
 * @param cfgCtx the axis2 configuration context
 * @param transportOut the transport-out description
 * @throws org.apache.axis2.AxisFault on error
 *///from   w ww  . j  a v  a2 s .  c  o  m
public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut) throws AxisFault {
    setTransportName(MailConstants.TRANSPORT_NAME);
    super.init(cfgCtx, transportOut);

    // initialize SMTP session
    Properties props = new Properties();
    List<Parameter> params = transportOut.getParameters();
    for (Parameter p : params) {
        props.put(p.getName(), p.getValue());
    }

    if (props.containsKey(MailConstants.MAIL_SMTP_FROM)) {
        try {
            smtpFromAddress = new InternetAddress((String) props.get(MailConstants.MAIL_SMTP_FROM));
        } catch (AddressException e) {
            handleException("Invalid default 'From' address : " + props.get(MailConstants.MAIL_SMTP_FROM), e);
        }
    }

    if (props.containsKey(MailConstants.MAIL_SMTP_BCC)) {
        try {
            smtpBccAddresses = InternetAddress.parse((String) props.get(MailConstants.MAIL_SMTP_BCC));
        } catch (AddressException e) {
            handleException("Invalid default 'Bcc' address : " + props.get(MailConstants.MAIL_SMTP_BCC), e);
        }
    }

    if (props.containsKey(MailConstants.TRANSPORT_MAIL_FORMAT)) {
        defaultMailFormat = (String) props.get(MailConstants.TRANSPORT_MAIL_FORMAT);
    }

    smtpUsername = (String) props.get(MailConstants.MAIL_SMTP_USERNAME);
    smtpPassword = (String) props.get(MailConstants.MAIL_SMTP_PASSWORD);

    if (smtpUsername != null && smtpPassword != null) {
        session = Session.getInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
            }
        });
    } else {
        session = Session.getInstance(props, null);
    }

    // add handlers for main MIME types
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("application/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("application/soap+xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    CommandMap.setDefaultCommandMap(mc);

    session.setDebug(log.isTraceEnabled());
}

From source file:org.entermedia.email.PostMail.java

public List<InternetAddress> parseEmails(String[] inEmails) {
    List emails = new ArrayList<InternetAddress>();
    for (int i = 0; i < inEmails.length; i++) {
        try {//ww  w . ja  va 2s . c  o m
            InternetAddress[] inet = InternetAddress.parse(inEmails[i]);
            for (int j = 0; j < inet.length; j++) {
                emails.add(inet[i]);
            }
        } catch (AddressException ex) {
            //ignore
            log.error("Could not process email " + inEmails[i], ex);
        }
    }
    return emails;
}

From source file:com.adaptris.mail.MailSenderImp.java

@Override
public void addCarbonCopy(String address) throws MailException {
    try {//  w ww.  ja v a2 s .  co  m
        addCarbonCopy(InternetAddress.parse(address));
    } catch (AddressException e) {
        throw new MailException(e);
    }
}

From source file:eagle.common.email.EagleMailClient.java

private boolean _send(String from, String to, String cc, String title, String content) {
    Message msg = new MimeMessage(session);
    try {/*from  ww  w  . j a v  a2 s. com*/
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(title);
        if (to != null) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        }
        if (cc != null) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
        }
        //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS));
        msg.setContent(content, "text/html;charset=utf-8");
        LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title));
        Transport.send(msg);
        return true;
    } catch (AddressException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    } catch (MessagingException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    }
}

From source file:com.spartasystems.holdmail.util.TestMailClient.java

public void sendResourceEmail(String resourceName, String sender, String recipient, String subject) {

    try {// w  w w.j  av  a  2s . c  om

        InputStream resource = TestMailClient.class.getClassLoader().getResourceAsStream(resourceName);
        if (resource == null) {
            throw new MessagingException("Couldn't find resource at: " + resourceName);
        }

        Message message = new MimeMessage(session, resource);

        // wipe out ALL exisitng recipients
        message.setRecipients(Message.RecipientType.TO, new Address[] {});
        message.setRecipients(Message.RecipientType.CC, new Address[] {});
        message.setRecipients(Message.RecipientType.BCC, new Address[] {});

        // then set the new data
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
        message.setFrom(InternetAddress.parse(sender)[0]);
        message.setSubject(subject);

        Transport.send(message);

        logger.info("Outgoing mail forwarded to " + recipient);

    } catch (MessagingException e) {
        throw new HoldMailException("couldn't send mail: " + e.getMessage(), e);
    }

}

From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java

public void testRoundTripPOX() throws Exception {

    String msgId = UUIDGenerator.getUUID();

    Session session = Session.getInstance(props, new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("synapse.test.1", "mailpassword");
        }//from   ww  w . j a v a  2  s .c  om
    });
    session.setDebug(log.isTraceEnabled());

    WSMimeMessage msg = new WSMimeMessage(session);
    msg.setFrom(new InternetAddress("synapse.test.0@gmail.com"));
    msg.setReplyTo(InternetAddress.parse("synapse.test.0@gmail.com"));
    InternetAddress[] address = { new InternetAddress("synapse.test.6@gmail.com") };
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject("POX Roundtrip");
    msg.setHeader(BaseConstants.SOAPACTION, Constants.AXIS2_NAMESPACE_URI + "/echoOMElement");
    msg.setSentDate(new Date());
    msg.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgId);
    msg.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgId);
    msg.setText(POX_MESSAGE);
    Transport.send(msg);

    Thread.yield();
    Thread.sleep(1000 * 10);

    Object reply = null;
    boolean replyNotFound = true;
    int retryCount = 3;
    while (replyNotFound) {
        log.debug("Checking for response ... with MessageID : " + msgId);
        reply = getMessage(msgId);
        if (reply != null) {
            replyNotFound = false;
        } else {
            if (retryCount-- > 0) {
                Thread.sleep(10000);
            } else {
                break;
            }
        }
    }

    if (reply != null && reply instanceof String) {
        log.debug("Result Body : " + reply);
        XMLStreamReader reader = StAXUtils.createXMLStreamReader(new StringReader((String) reply));
        OMElement res = new StAXOMBuilder(reader).getDocumentElement();
        if (res != null) {
            AXIOMXPath xpath = new AXIOMXPath("//my:myValue");
            xpath.addNamespace("my", "http://localhost/axis2/services/EchoXMLService");
            Object result = xpath.evaluate(res);
            if (result != null && result instanceof OMElement) {
                assertEquals("omTextValue", ((OMElement) result).getText());
            }
        }
    } else {
        fail("Did not receive the reply mail");
    }
}

From source file:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {/*from ww  w.jav  a2s.  c  o m*/

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected void assignFromAddress(SendingMessage sendingMessage, MimeMessage msg) throws MessagingException {
    InternetAddress[] internetAddresses = InternetAddress.parse(sendingMessage.getFrom());
    for (InternetAddress internetAddress : internetAddresses) {
        if (StringUtils.isNotEmpty(internetAddress.getPersonal())) {
            try {
                internetAddress.setPersonal(internetAddress.getPersonal(), StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                throw new MessagingException("Unsupported encoding type", e);
            }//from w w  w. j  av  a 2s. c o  m
        }
    }

    if (internetAddresses.length == 1) {
        msg.setFrom(internetAddresses[0]);
    } else {
        msg.addFrom(internetAddresses);
    }
}

From source file:ua.aits.crc.controller.MainController.java

@RequestMapping(value = { "/sendmail/", "/sendmail" }, method = RequestMethod.GET)
public @ResponseBody String sendMail(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    request.setCharacterEncoding("UTF-8");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String text = request.getParameter("text");
    final String username = "office@crc.org.ua";
    final String password = "crossroad2000";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
            return new javax.mail.PasswordAuthentication(username, password);
        }//from www .jav a2 s  . com
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(email));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("office@crc.org.ua"));
        message.setSubject("Mail from site");
        message.setText("Name: " + name + "\nEmail: " + email + "\n\n" + text);
        Transport.send(message);
        return "done";
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.adaptris.mail.MailSenderImp.java

@Override
public void addBlindCarbonCopy(String address) throws MailException {
    try {/*  www.  j a va2 s .c  o  m*/
        addBlindCarbonCopy(InternetAddress.parse(address));
    } catch (AddressException e) {
        throw new MailException(e);
    }
}