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:hudson.plugins.emailext.plugins.recipients.FailingTestSuspectsRecipientProviderTest.java

private static void checkRecipients(final Build build, final String... inAuthors) throws AddressException {
    ExtendedEmailPublisherContext context = new ExtendedEmailPublisherContext(null, build,
            new Launcher.LocalLauncher(StreamTaskListener.fromStdout()),
            new StreamBuildListener(System.out, Charset.defaultCharset()));
    EnvVars envVars = new EnvVars();
    Set<InternetAddress> to = new HashSet<InternetAddress>();
    Set<InternetAddress> cc = new HashSet<InternetAddress>();
    Set<InternetAddress> bcc = new HashSet<InternetAddress>();
    FailingTestSuspectsRecipientProvider provider = new FailingTestSuspectsRecipientProvider();
    provider.addRecipients(context, envVars, to, cc, bcc);
    final List<InternetAddress> authors = new ArrayList<InternetAddress>();
    for (final String author : inAuthors) {
        authors.add(new InternetAddress(author + AT_DOMAIN));
    }/*from   ww w.j av a  2 s . co m*/
    // All of the authors should have received an email, so the list should be empty.
    authors.removeAll(to);
    assertTrue("Authors not receiving mail: " + authors.toString(), authors.isEmpty());
    assertTrue(cc.isEmpty());
    assertTrue(bcc.isEmpty());
}

From source file:com.silverpeas.mailinglist.service.notification.TestNotificationHelper.java

@Test
public void testSimpleSendMail() throws Exception {
    MimeMessage mail = new MimeMessage(notificationHelper.getSession());
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { theSimpsons });
    mail.setSubject("Simple text Email test");
    mail.setText(textEmailContent);/*from  w w w  . j  av  a2  s  .  co m*/
    List<ExternalUser> externalUsers = new LinkedList<ExternalUser>();
    ExternalUser user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("bart.simpson@silverpeas.com");
    externalUsers.add(user);
    notificationHelper.sendMail(mail, externalUsers);
    checkSimpleEmail("bart.simpson@silverpeas.com", "Simple text Email test");
}

From source file:com.mobileman.projecth.business.messages.MessageServiceTest.java

/**
 * //from   w  w w .  ja va 2  s  . c  o  m
 * @throws Exception
 */
@Test
public void sendMessage() throws Exception {

    User pat1 = userService.findUserByLogin("sysuser1");
    assertNotNull(pat1);
    User pat2 = userService.findUserByLogin("sysuser2");
    assertNotNull(pat2);

    List<Message> messagesOld = messageService.findAll();

    messageService.sendMessage(pat1.getId(), pat2.getId(), "Hallo pat2", "How are you?", false);

    List<Message> messages = messageService.findAll();
    assertEquals(messagesOld.size() + 1, messages.size());
    Message message = messages.get(messages.size() - 1);
    assertEquals(pat1.getId(), message.getSender().getId());
    assertEquals(pat2.getId(), message.getReceiver().getId());

    List<WiserMessage> mailMessages = wiser.getMessages();
    assertEquals(1, mailMessages.size());
    assertEquals(new InternetAddress("nachrichten@projecth.com"),
            mailMessages.get(0).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("doc1@projecth.com"),
            mailMessages.get(0).getMimeMessage().getRecipients(javax.mail.Message.RecipientType.TO)[0]);
    assertEquals("Hallo pat2", mailMessages.get(0).getMimeMessage().getSubject());
}

From source file:com.mirth.connect.client.ui.UserEditPanel.java

public String validateUser() {
    if (!checkIfAbleToFinish()) {
        return "Please fill in all required information.";
    }/*from w w w .j av  a2s . co m*/

    // If it's a new user or the username was changed, make sure the username isn't already used.
    if (user.getId() == null || !user.getUsername().equals(username.getText())) {
        for (int i = 0; i < parent.users.size(); i++) {
            if (parent.users.get(i).getUsername().equals(username.getText())) {
                return "This username already exists. Please choose another one.";
            }
        }
    }

    if (!String.valueOf(password.getPassword()).equals(String.valueOf(confirmPassword.getPassword()))) {
        return "Passwords must be the same.";
    }

    try {
        String emailAddress = email.getText();
        if (StringUtils.isNotBlank(emailAddress)) {
            new InternetAddress(emailAddress).validate();
        }
    } catch (Exception e) {
        return "The email address is invalid: " + e.getMessage();
    }

    return null;
}

From source file:nl.surfnet.coin.teams.control.JoinTeamController.java

private void sendJoinTeamMessage(final Team team, final Person person, final String message,
        final Locale locale) throws IllegalStateException, IOException {

    Object[] subjectValues = { team.getName() };
    final String subject = messageSource.getMessage(REQUEST_MEMBERSHIP_SUBJECT, subjectValues, locale);

    final Set<Member> admins = grouperTeamService.findAdmins(team);
    if (CollectionUtils.isEmpty(admins)) {
        throw new RuntimeException("Team '" + team.getName() + "' has no admins to mail invites");
    }/*from ww  w  .j a va  2  s. c om*/

    final String html = composeJoinRequestMailMessage(team, person, message, locale, "html");
    final String plainText = composeJoinRequestMailMessage(team, person, message, locale, "plaintext");

    final List<InternetAddress> bcc = new ArrayList<InternetAddress>();
    for (Member admin : admins) {
        try {
            bcc.add(new InternetAddress(admin.getEmail()));
        } catch (AddressException ae) {
            log.debug("Admin has malformed email address", ae);
        }
    }
    if (bcc.isEmpty()) {
        throw new RuntimeException(
                "Team '" + team.getName() + "' has no admins with valid email addresses to mail invites");
    }

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");

            mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail()));
            mimeMessage.setRecipients(Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()]));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);

}

From source file:com.knowarth.portlet.downloadinterceptor.DownloadInterceptorPortlet.java

public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws IOException {
    //Setting out email parameters
    String emailAdd = resourceRequest.getParameter("emailAddress");
    String visitorName = resourceRequest.getParameter("visitorName");
    String cmpName = resourceRequest.getParameter("companyName");
    String phoneNumber = resourceRequest.getParameter("phoneNumber");
    String comments = resourceRequest.getParameter("comments");

    //Getting the preferences and reading URL Location reading from edit mode
    PortletPreferences prefs = resourceRequest.getPreferences();
    String resourceurl = prefs.getValue("resourceurl", "");
    String caseStudyName = prefs.getValue("caseStudyName", "");
    String receiveEmailAdd = prefs.getValue("receiverEmailAdd", "");
    //emailBodyContent Return the template stored in preferences edit mode.
    String emailBodyContent = prefs.getValue("emailBodyTemplate", "");
    String emailsubj = prefs.getValue("emailSubjectTemplate", "");
    String resExtension = prefs.getValue("ResourceExtension", "");
    String body = StringUtil.replace(emailBodyContent,
            new String[] { "[$VISITOR_NAME$]", "[$COMPANY_NAME$]", "[$EMAIL_ADDRESS$]", "[$PHONE_NUMBER$]",
                    "[$COMMENTS$]", "[$CASE_STUDY_NAME$]" },
            new String[] { visitorName, cmpName, emailAdd, phoneNumber, comments, caseStudyName });

    //Setting out body and email parameters
    String subject = StringUtil.replace(emailsubj, new String[] { "[$VISITOR_NAME$]", "[$CASE_STUDY_NAME$]" },
            new String[] { visitorName, caseStudyName });
    //code for sending email
    try {/*from  ww w  . j av a 2s  .  c om*/
        InternetAddress fromAddress = new InternetAddress(emailAdd);
        InternetAddress toAddress = new InternetAddress(receiveEmailAdd);

        MailMessage mailMessage = new MailMessage(fromAddress, toAddress, subject, body, true);
        MailServiceUtil.sendEmail(mailMessage);

    } catch (AddressException e) {
        // TODO Auto-generated catch block
        _log.error("Error Sending Message", e);
    } finally {
        //For Downloading a resource

        String contentDisposition = "attachment; filename=" + caseStudyName + "." + resExtension;
        OutputStream out = resourceResponse.getPortletOutputStream();

        //LInk for resource URL Goes here. Uncomment it out for dynamic location and comment out the static link
        URL url = new URL(resourceurl);
        URLConnection conn = url.openConnection();
        resourceResponse.setContentType(conn.getContentType());
        resourceResponse.setContentLength(conn.getContentLength());
        resourceResponse.setCharacterEncoding(conn.getContentEncoding());
        resourceResponse.setProperty(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
        resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600");

        // open the stream and put it into BufferedReader
        InputStream stream = conn.getInputStream();
        int c;
        while ((c = stream.read()) != -1) {
            out.write(c);
        }
        out.flush();
        out.close();
        stream.close();

    }

}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateEmailMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateEmailMessageMethod = _clazz.getDeclaredMethod("_populateEmailMessage", Map.class,
            String.class, String.class, Session.class);

    populateEmailMessageMethod.setAccessible(true);

    List<SearchResult> searchResults = new ArrayList<>();

    SearchQuery searchQuery = new SearchQuery(1, _USER_ID, "Test keywords");

    SearchResult searchResult = new SearchResult(1, "1234", "itemTitle", "$14.99", "$29.99",
            "http://www.ebay.com/itm/1234", "http://www.ebay.com/123.jpg");

    searchResults.add(searchResult);//w  ww  .j  a v  a 2 s .c om

    Map<SearchQuery, List<SearchResult>> searchQueryResultMap = new HashMap<>();

    searchQueryResultMap.put(searchQuery, searchResults);

    Message message = (Message) populateEmailMessageMethod.invoke(_classInstance, searchQueryResultMap,
            "user@test.com", "unsubscribeToken", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertTrue(message.getSubject().contains("New Search Results - "));
    Assert.assertEquals(_EMAIL_CONTENT, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}

From source file:com.vaushell.superpipes.dispatch.ErrorMailer.java

private void sendHTML(final String message) throws MessagingException, IOException {
    if (message == null || message.isEmpty()) {
        throw new IllegalArgumentException("message");
    }//from   w w w . j av  a 2  s  .c o m

    final String host = properties.getConfigString("host");

    final Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", host);

    final String port = properties.getConfigString("port", null);
    if (port != null) {
        props.setProperty("mail.smtp.port", port);
    }

    if ("true".equalsIgnoreCase(properties.getConfigString("ssl", null))) {
        props.setProperty("mail.smtp.ssl.enable", "true");
    }

    final Session session = Session.getInstance(props, null);
    //        session.setDebug( true );

    final javax.mail.Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(properties.getConfigString("from")));

    msg.setRecipients(javax.mail.Message.RecipientType.TO,
            InternetAddress.parse(properties.getConfigString("to"), false));

    msg.setSubject("superpipes error message");

    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, "text/html")));

    msg.setHeader("X-Mailer", "superpipes");

    Transport t = null;
    try {
        t = session.getTransport("smtp");

        final String username = properties.getConfigString("username", null);
        final String password = properties.getConfigString("password", null);
        if (username == null || password == null) {
            t.connect();
        } else {
            if (port == null || port.isEmpty()) {
                t.connect(host, username, password);
            } else {
                t.connect(host, Integer.parseInt(port), username, password);
            }
        }

        t.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }
}

From source file:edu.harvard.med.iccbl.screensaver.io.AdminEmailApplication.java

public boolean sendEmail(String subject, String msg, ScreensaverUser user) throws MessagingException {
    List<String> failMessages = Lists.newArrayList();
    if (StringUtils.isEmpty(user.getEmail())) {
        failMessages.add("Empty address for the user: " + printUser(user));
    } else {//from   w w w.ja v  a  2 s  .  c  om
        EmailService emailService = getEmailServiceBasedOnCommandLineOption();
        if (isAdminEmailOnly()) {
            sendAdminEmails("Admin email only: " + subject,
                    "originally for: " + printUser(user) + "\nOriginal Message:\n" + msg);
        } else {
            try {
                InternetAddress userAddress = new InternetAddress(user.getEmail());
                emailService.send(subject, msg, getAdminEmail(), new InternetAddress[] { userAddress }, null);
            } catch (AddressException e) {
                failMessages.add("Address exception for user: " + printUser(user) + ", " + e.getMessage());
            }
        }
    }
    if (!failMessages.isEmpty()) {
        sendFailMessages("User message: " + subject, msg, failMessages);
    }
    return failMessages.isEmpty();
}

From source file:com.bia.gmailjava.EmailService.java

/**
 *
 * @param addressTo//from  ww  w  .ja  v a2s.c om
 * @param subject
 * @param message
 * @throws AddressException
 * @throws MessagingException
 */
private void send(InternetAddress[] addressTo, String subject, String message)
        throws AddressException, MessagingException {
    Message msg = new MimeMessage(createSession());
    InternetAddress addressFrom = new InternetAddress(USERNAME);
    msg.setFrom(addressFrom);
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // set bcc
    //InternetAddress[] bcc1 = getBCC();
    //msg.setRecipients(Message.RecipientType.BCC, bcc1);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    //String message = comment;
    msg.setContent(message, EMAIL_CONTENT_TYPE);

    Transport.send(msg);
}