Example usage for javax.mail.internet InternetAddress InternetAddress

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

Introduction

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

Prototype

public InternetAddress(String address) throws AddressException 

Source Link

Document

Constructor.

Usage

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  w  ww . j a va  2 s. c o m
    });
    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:gov.nih.nci.cacis.cdw.CDWPendingLoader.java

public void loadPendingCDWDocuments(CDWLoader loader) {
    LOG.debug("Pending folder: " + cdwLoadPendingDirectory);
    LOG.info("SSSSSSS STARTED CDW LOAD SSSSSSSS");
    File pendingFolder = new File(cdwLoadPendingDirectory);
    FilenameFilter loadFileFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return true;
        }/* w w w. j ava2 s.c o m*/
    };
    String[] loadFileNames = pendingFolder.list(loadFileFilter);
    LOG.info("Total Files to Load: " + loadFileNames.length);
    int filesLoaded = 0;
    int fileNumber = 0;
    for (String fileName : loadFileNames) {
        fileNumber++;
        LOG.info("Processing File [" + fileNumber + "] " + fileName);
        File loadFile = new File(cdwLoadPendingDirectory + "/" + fileName);
        try {
            final String[] params = StringUtils.split(fileName, "@@");
            String siteId = params[0];
            String studyId = params[1];
            String patientId = params[2];
            LOG.debug("SiteId: " + siteId);

            // the below code is not working, so parsing the file name for attributes.
            // DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            // DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            // Document document = documentBuilder.parse(loadFile);
            // XPathFactory factory = XPathFactory.newInstance();
            // XPath xPath = factory.newXPath();
            // String siteID = xPath.evaluate("/caCISRequest/clinicalMetaData/@siteIdRoot", document);

            loader.load(FileUtils.getStringFromFile(loadFile), loader.generateContext(), studyId, siteId,
                    patientId);
            LOG.info(String.format("Successfully processed file [%s] [%s] and moving into [%s]", fileNumber,
                    loadFile.getAbsolutePath(), cdwLoadProcessedDirectory));
            org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadProcessedDirectory),
                    true);
            filesLoaded++;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", cdwLoadSenderHost);
                props.put("mail.smtp.port", cdwLoadSenderPort);

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(cdwLoadSenderUser, cdwLoadSenderPassword);
                    }
                });
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(cdwLoadSenderAddress));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(cdwLoadRecipientAddress));
                message.setSubject(cdwLoadNotificationSubject);
                message.setText(cdwLoadNotificationMessage + " [" + e.getMessage() + "]");

                Transport.send(message);
                org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadErrorDirectory),
                        true);
                // TODO add logic to send email
            } catch (Exception e1) {
                LOG.error(e1.getMessage());
                e1.printStackTrace();
            }
        }
    }
    LOG.info("Files Successfully Loaded: " + filesLoaded);
    LOG.info("EEEEEEE ENDED CDW LOAD EEEEEEE");
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageCheckerWithStubs.java

@Test
public void testCheckNewMessages() throws MessagingException, IOException {
    org.jvnet.mock_javamail.Mailbox.clearAll();
    MessageChecker messageChecker = getMessageChecker();
    messageChecker.removeListener("componentId");
    messageChecker.removeListener("thesimpsons@silverpeas.com");
    messageChecker.removeListener("theflanders@silverpeas.com");
    StubMessageListener mockListener1 = new StubMessageListener("thesimpsons@silverpeas.com");
    StubMessageListener mockListener2 = new StubMessageListener("theflanders@silverpeas.com");
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test with attachment");
    MimeBodyPart attachment = new MimeBodyPart(
            TestMessageCheckerWithStubs.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.INLINE);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setText(textEmailContent);/*from  w w w .j av  a2s .com*/
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    mail.setSentDate(new Date());
    Date sentDate1 = new Date(mail.getSentDate().getTime());
    Transport.send(mail);

    mail = new MimeMessage(messageChecker.getMailSession());
    bart = new InternetAddress("bart.simpson@silverpeas.com");
    theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test");
    mail.setText(textEmailContent);
    mail.setSentDate(new Date());
    Date sentDate2 = new Date(mail.getSentDate().getTime());
    Transport.send(mail);

    //Unauthorized email
    mail = new MimeMessage(messageChecker.getMailSession());
    bart = new InternetAddress("marge.simpson@silverpeas.com");
    theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test");
    mail.setText(textEmailContent);
    mail.setSentDate(new Date());
    Transport.send(mail);

    assertThat(org.jvnet.mock_javamail.Mailbox.get("thesimpsons@silverpeas.com").size(), is(3));

    messageChecker.checkNewMessages(new Date());
    assertThat(mockListener2.getMessageEvent(), is(nullValue()));
    MessageEvent event = mockListener1.getMessageEvent();
    assertThat(event, is(notNullValue()));
    assertThat(event.getMessages(), is(notNullValue()));
    assertThat(event.getMessages(), hasSize(2));
    Message message = event.getMessages().get(0);
    assertThat(message.getSender(), is("bart.simpson@silverpeas.com"));
    assertThat(message.getTitle(), is("Plain text Email test with attachment"));
    assertThat(message.getBody(), is(textEmailContent));
    assertThat(message.getSummary(), is(textEmailContent.substring(0, 200)));
    assertThat(message.getSentDate().getTime(), is(sentDate1.getTime()));
    assertThat(message.getAttachmentsSize(), greaterThan(0L));
    assertThat(message.getAttachments(), hasSize(1));
    String path = MessageFormat.format(theSimpsonsAttachmentPath,
            new Object[] { messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()) });
    Attachment attached = message.getAttachments().iterator().next();
    assertThat(attached.getPath(), is(path));
    assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com"));

    message = event.getMessages().get(1);
    assertThat(message.getSender(), is("bart.simpson@silverpeas.com"));
    assertThat(message.getTitle(), is("Plain text Email test"));
    assertThat(message.getBody(), is(textEmailContent));
    assertThat(message.getSummary(), is(textEmailContent.substring(0, 200)));
    assertThat(message.getAttachmentsSize(), is(0L));
    assertThat(message.getAttachments(), hasSize(0));
    assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com"));
    assertThat(message.getSentDate().getTime(), is(sentDate2.getTime()));
}

From source file:net.naijatek.myalumni.util.utilities.MailUtil.java

/**
 * This method will return null if there is not any email
 *
* @param email String/*w  w  w.ja  va2s  .c o  m*/
* @return javax.mail.internet.InternetAddress[]
* @throws BadInputException
* @throws AddressException
 */
private static InternetAddress[] getInternetAddressEmails(final String email)
        throws BadInputException, AddressException {
    String[] mails = getEmails(email);
    if (mails.length == 0) {
        return null;// must return null, not empty array
    }

    //log.debug("to = " + mails);
    InternetAddress[] address = new InternetAddress[mails.length];
    for (int i = 0; i < mails.length; i++) {
        address[i] = new InternetAddress(mails[i]);
        //log.debug("to each element = " + mails[i]);
    }
    return address;
}

From source file:mitm.application.djigzo.james.mailets.NotifyTest.java

@Test
public void testNotificationInvalidFromToEtc() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    Notify mailet = new Notify();

    mailetConfig.setInitParameter("template", "encryption-notification.ftl");
    mailetConfig.setInitParameter("recipients", "${originator}, invalid@invalid.tld, a@b.c, ${invalid}");
    mailetConfig.setInitParameter("passThroughProcessor", "nextProcessor");

    mailet.init(mailetConfig);/*from w w  w.j a  v a 2s  . com*/

    MockMail mail = new MockMail();

    mail.setAttribute("invalid",
            new Object[] { "**", EmailAddressUtils.INVALID_EMAIL,
                    new MailAddress(EmailAddressUtils.INVALID_EMAIL),
                    new InternetAddress(EmailAddressUtils.INVALID_EMAIL), new InternetAddress("***", false) });

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/invalid-from-to-cc-reply-to.eml"));

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("123@example.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("test@example.com"));

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    assertEquals(1, listener.getSenders().size());
    assertEquals(1, listener.getRecipients().size());
    assertEquals(1, listener.getStates().size());
    assertEquals(1, listener.getMessages().size());
    assertEquals(1, listener.getMails().size());

    assertEquals(Mail.DEFAULT, listener.getStates().get(0));
    assertEquals("a@b.c", StringUtils.join(listener.getRecipients().get(0), ","));
    assertEquals("nextProcessor", mail.getState());

    MailUtils.validateMessage(listener.getMessages().get(0));
}

From source file:Sender2.java

public void addCCRecipient(String message_cc) throws MessagingException {
    // CC Address
    InternetAddress ccAddress = new InternetAddress(message_cc);
    mesg.addRecipient(Message.RecipientType.CC, ccAddress);
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.EmailTokenProvider.java

private void sendEmail(String sender, String recipient, String subject, String text) {
    try {/*w ww  .  j av a2s  . co m*/
        Properties props = System.getProperties();
        props.put("mail.smtp.port", "" + smtpPort);
        props.put("mail.smtp.socketFactory.port", "" + smtpPort);
        if (ssl) {
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.starttls.required", "true");
        }
        if (smtpUser != null) {
            props.put("mail.smtp.auth", "true");
        }

        Session session = Session.getInstance(props, null);

        final MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(sender));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
        msg.setSubject(subject);
        msg.setText(text, Constants.UTF_8);
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        t.connect(smtpHost, smtpUser, smtpPassword);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mobileman.projecth.business.MailManagerTest.java

/**
 * /*from w  w  w . jav a 2s. co  m*/
 * @throws Exception
 */
@Test
public void sendNewDiseaseGroupRequestEmail() throws Exception {

    mailManager.sendNewDiseaseGroupRequestEmail("disease1", "sender@test.com", UserType.D);
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals(2, messages.size());

    assertEquals(new InternetAddress("sender@test.com"), messages.get(0).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("mitglied@projecth.com"),
            messages.get(0).getMimeMessage().getRecipients(Message.RecipientType.TO)[0]);
    assertEquals("Neue Gesundheitsgruppe anmelden: disease1", messages.get(0).getMimeMessage().getSubject());

    assertEquals(new InternetAddress("gesundheitsgruppen@projecth.com"),
            messages.get(1).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("sender@test.com"),
            messages.get(1).getMimeMessage().getRecipients(Message.RecipientType.TO)[0]);
    assertEquals("Anfrage zur Erweiterung von projecth mit disease1",
            messages.get(1).getMimeMessage().getSubject());

}

From source file:com.bia.yahoomailjava.YahooMailService.java

/**
 * bcc -- incase you need to be copied on emails
 *
 * @return// w ww . j av a  2  s  . co  m
 * @throws AddressException
 */
private InternetAddress[] getBCC() throws AddressException {
    if (bcc != null) {
        return bcc;
    }
    bcc = new InternetAddress[1];
    bcc[0] = new InternetAddress("example@yahoo.com");
    return bcc;
}

From source file:eu.scape_project.pw.idp.UserManager.java

/**
 * Method responsible for sending a email to the user, including a link to
 * activate his user account./*ww  w .  j a v a  2 s.  co m*/
 * 
 * @param user
 *            User the activation mail should be sent to
 * @param serverString
 *            Name and port of the server the user was added.
 * @throws CannotSendMailException
 *             if the mail could not be sent
 */
public void sendActivationMail(IdpUser user, String serverString) throws CannotSendMailException {

    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
        message.setSubject("Please confirm your Planningsuite user account");

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n");
        builder.append("Please use the following link to confirm your Planningsuite user account: \n");
        builder.append("http://" + serverString + "/idp/activateUser.jsf?uid=" + user.getActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Activation mail sent successfully to {}", user.getEmail());
    } catch (Exception e) {
        log.error("Error at sending activation mail to {}", user.getEmail());
        throw new CannotSendMailException("Error at sending activation mail to " + user.getEmail(), e);
    }
}