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:com.googlecode.psiprobe.tools.Mailer.java

private static InternetAddress[] createAddresses(String[] addresses) throws AddressException {
    List/*InternetAddress*/ result = new ArrayList(addresses.length);
    for (int i = 0; i < addresses.length; i++) {
        String address = addresses[i];
        InternetAddress[] parsedAddresses = InternetAddress.parse(address);
        for (int j = 0; j < parsedAddresses.length; j++) {
            InternetAddress parsedAddress = parsedAddresses[j];
            result.add(parsedAddress);//from  ww  w.j  a va2s .  c  o  m
        }
    }
    return (InternetAddress[]) result.toArray(new InternetAddress[result.size()]);
}

From source file:org.craftercms.commons.mail.impl.EmailFactoryImplTest.java

@Test
public void testGetEmailWithBodyTemplate() throws Exception {
    Map<String, Object> model = Collections.<String, Object>singletonMap("name", "John Doe");
    String body = processTemplate(TEMPLATE_NAME, model);

    EmailImpl email = (EmailImpl) emailFactory.getEmail(FROM, TO, CC, BCC, REPLY_TO, SUBJECT, TEMPLATE_NAME,
            model, false);//w w  w . ja  va  2s  .  c o  m

    assertNotNull(email);

    MimeMessage msg = email.message;

    assertArrayEquals(InternetAddress.parse(FROM), msg.getFrom());
    assertArrayEquals(InternetAddress.parse(StringUtils.join(TO)), msg.getRecipients(Message.RecipientType.TO));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(CC)), msg.getRecipients(Message.RecipientType.CC));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(BCC)),
            msg.getRecipients(Message.RecipientType.BCC));
    assertArrayEquals(InternetAddress.parse(REPLY_TO), msg.getReplyTo());
    assertEquals(SUBJECT, msg.getSubject());
    assertEquals(body, msg.getContent());
}

From source file:org.apache.axis2.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  w w .j  av  a2 s .  co  m
public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut) throws AxisFault {
    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);
    }

    MailUtils.setupLogging(session, log, transportOut);

    // set the synchronise callback table
    if (cfgCtx.getProperty(BaseConstants.CALLBACK_TABLE) == null) {
        cfgCtx.setProperty(BaseConstants.CALLBACK_TABLE, new ConcurrentHashMap());
    }
}

From source file:org.quartz.jobs.ee.mail.SendMailJob.java

protected MimeMessage prepareMimeMessage(MailInfo mailInfo) throws MessagingException {
    Session session = getMailSession(mailInfo);

    MimeMessage mimeMessage = new MimeMessage(session);

    Address[] toAddresses = InternetAddress.parse(mailInfo.getTo());
    mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses);

    if (mailInfo.getCc() != null) {
        Address[] ccAddresses = InternetAddress.parse(mailInfo.getCc());
        mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses);
    }/*w  w  w  .j a  v a 2 s  .  com*/

    mimeMessage.setFrom(new InternetAddress(mailInfo.getFrom()));

    if (mailInfo.getReplyTo() != null) {
        mimeMessage.setReplyTo(new InternetAddress[] { new InternetAddress(mailInfo.getReplyTo()) });
    }

    mimeMessage.setSubject(mailInfo.getSubject());

    mimeMessage.setSentDate(new Date());

    setMimeMessageContent(mimeMessage, mailInfo);

    return mimeMessage;
}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param runner/* w ww .  j  ava2  s  .com*/
 * @param resultDir
 * @throws MessagingException
 * @throws IOException
 */
public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException {

    MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");

    // To
    mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo()));

    // From
    mimeMessage.setFrom(new InternetAddress(config.getFrom()));

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("result", runner.getResult() ? "passed" : "failed");
    context.put("passedCount", new Integer(runner.getPassedCount()));
    context.put("failedCount", new Integer(runner.getFailedCount()));
    context.put("totalCount", new Integer(runner.getHtmlSuiteList().size()));
    context.put("startTime", new Date(runner.getStartTime()));
    context.put("endTime", new Date(runner.getEndTime()));
    context.put("htmlSuites", runner.getHtmlSuiteList());

    // subject
    mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset());

    // multipart message
    MimeMultipart content = new MimeMultipart();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset());
    content.addBodyPart(body);

    File resultArchive = createResultArchive(resultDir);

    MimeBodyPart attachmentFile = new MimeBodyPart();
    attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive)));
    attachmentFile.setFileName(RESULT_ARCHIVE_FILE);
    content.addBodyPart(attachmentFile);

    mimeMessage.setContent(content);

    // send mail
    _send(mimeMessage);
}

From source file:org.eclipse.che.mail.MailSender.java

public void sendMail(EmailBean emailBean) throws SendMailException {
    File tempDir = null;//from   w  w w  .  j  a  va2 s  .c  om
    try {
        MimeMessage message = new MimeMessage(mailSessionProvider.get());
        Multipart contentPart = new MimeMultipart();

        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType()));
        contentPart.addBodyPart(bodyPart);

        if (emailBean.getAttachments() != null) {
            tempDir = Files.createTempDir();
            for (Attachment attachment : emailBean.getAttachments()) {
                // Create attachment file in temporary directory
                byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent());
                File attachmentFile = new File(tempDir, attachment.getFileName());
                Files.write(attachmentContent, attachmentFile);

                // Attach the attachment file to email
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(attachmentFile);
                attachmentPart.setContentID("<" + attachment.getContentId() + ">");
                contentPart.addBodyPart(attachmentPart);
            }
        }

        message.setContent(contentPart);
        message.setSubject(emailBean.getSubject(), "UTF-8");
        message.setFrom(new InternetAddress(emailBean.getFrom(), true));
        message.setSentDate(new Date());
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo()));

        if (emailBean.getReplyTo() != null) {
            message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo()));
        }
        LOG.info("Sending from {} to {} with subject {}", emailBean.getFrom(), emailBean.getTo(),
                emailBean.getSubject());

        Transport.send(message);
        LOG.debug("Mail sent");
    } catch (Exception e) {
        LOG.error(e.getLocalizedMessage());
        throw new SendMailException(e.getLocalizedMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                FileUtils.deleteDirectory(tempDir);
            } catch (IOException exception) {
                LOG.error(exception.getMessage());
            }
        }
    }
}

From source file:org.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java

public void prepare(MimeMessage message) throws Exception {

    message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");

    // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369
    if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) {
        message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");
    }//from w w  w  . j av  a2s  . c  o  m

    if (getFrom() != null) {
        List<InternetAddress> toAddress = new ArrayList<InternetAddress>();
        toAddress.add(new InternetAddress(getFrom(), getFromName()));
        message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()]));
    }
    if (getTo() != null) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
    }
    if (getCc() != null) {
        message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc()));
    }
    if (getBcc() != null) {
        message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(getBcc()));
    }
    if (getSubject() != null) {
        message.setSubject(getSubject());
    }

    MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
    message.setContent(mimeMultipart);

    if (getPlainTextContent() != null) {
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");
        textBodyPart.setHeader("Content-Transfer-Encoding", "base64");
        textBodyPart.setContent(getPlainTextContent(), "text/plain; charset=\"UTF-8\"");
        mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
        htmlBodyPart.setHeader("Content-Transfer-Encoding", "base64");
        htmlBodyPart.setContent(getHtmlContent(), "text/html; charset=\"UTF-8\"");
        mimeMultipart.addBodyPart(htmlBodyPart);
    }

}

From source file:org.xwiki.mail.internal.factory.usersandgroups.UsersAndGroupsSource.java

private static List<Address> extractAddresses(String key, Map<String, Object> sourceMap)
        throws MessagingException {
    List<Address> addresses;
    List<String> emails = (List<String>) sourceMap.get(key);
    if (emails != null) {
        addresses = new ArrayList<>();
        for (String email : emails) {
            addresses.add(InternetAddress.parse(email)[0]);
        }//from   w ww.ja v a  2  s  .c o m
    } else {
        addresses = Collections.emptyList();
    }
    return addresses;
}

From source file:com.ayu.filter.RegularService.java

@Async
public void sendSSLMail(String text, String toMail) {

    final String username = "clouddefenceids";
    final String password = "";

    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 PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from w ww .j  a v  a  2  s . c  o  m
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
        message.setSubject("Forgot Password");
        message.setText(text);

        Transport.send(message);

        System.out.println("Done");

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

From source file:com.reizes.shiva.net.mail.Mail.java

private InternetAddress[] parseAddresses(String input) throws AddressException {
    return InternetAddress.parse(StringUtils.replace(input, ";", ","));
}