Example usage for javax.mail.internet MimeMessage getAllRecipients

List of usage examples for javax.mail.internet MimeMessage getAllRecipients

Introduction

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

Prototype

@Override
public Address[] getAllRecipients() throws MessagingException 

Source Link

Document

Get all the recipient addresses for the message.

Usage

From source file:ru.codemine.ccms.mail.EmailService.java

public void sendSimpleMessage(String address, String subject, String content) {
    try {/*from   w ww  . ja  v  a 2s .  co  m*/
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.mime.charset", "UTF-8");
        props.put("mail.smtp.ssl.enable", ssl);

        Session session = Session.getInstance(props, new EmailAuthenticator(username, password));

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username, ""));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
        message.setSubject(subject);
        message.setText(content, "utf-8", "html");
        Transport transport = session.getTransport("smtp");
        transport.connect();
        transport.sendMessage(message, message.getAllRecipients());
    } catch (MessagingException | UnsupportedEncodingException ex) {
        log.error(
                "?  ? email,  : "
                        + ex.getLocalizedMessage());
        ex.printStackTrace();
    }

}

From source file:ste.xtest.mail.BugFreeFileTransport.java

private void sendSimpleMessage(String from, String to, String subject, String body) throws Exception {
    Session session = Session.getInstance(config);

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);// w  ww.j a v  a2  s  . c o m
    message.setText(body);

    session.getTransport().sendMessage(message, message.getAllRecipients());
}

From source file:easyproject.utils.SendMail.java

@Override
public void run() {

    Properties props = new Properties();

    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", servidorSMTP);
    props.put("mail.smtp.port", puerto);

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

    try {//w  w w.  j  av a 2s .c om
        MimeMessage message1 = new MimeMessage(session);

        message1.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
        message1.setSubject(asunto);
        message1.setSentDate(new Date());
        message1.setContent(mensaje, "text/html; charset=utf-8");

        Transport tr = session.getTransport("smtp");
        tr.connect(servidorSMTP, usuario, password);
        message1.saveChanges();
        tr.sendMessage(message1, message1.getAllRecipients());
        tr.close();

    } catch (MessagingException e) {
        e.printStackTrace();
    }

}

From source file:ch.entwine.weblounge.kernel.mail.SmtpService.java

/**
 * Sends <code>message</code> using the configured transport.
 * /* w  ww.ja  v a  2s  . c  o m*/
 * @param message
 *          the message
 * @throws MessagingException
 *           if sending the message failed
 */
public void send(MimeMessage message) throws MessagingException {
    Transport t = getSession().getTransport(MAIL_TRANSPORT);
    try {
        if (mailUser != null)
            t.connect(mailUser, mailPassword);
        else
            t.connect();
        t.sendMessage(message, message.getAllRecipients());
    } finally {
        t.close();
    }
}

From source file:cl.preguntame.controller.PlataformaController.java

@ResponseBody
@RequestMapping(value = "/email", method = RequestMethod.POST)
public String correo(HttpServletRequest req) {

    try {/*www .  j  a  va 2  s .  c o m*/
        String host = "smtp.gmail.com";

        Properties prop = System.getProperties();

        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", host);
        prop.put("mail.smtp.user", "hector.riquelme1169@gmail.com");
        prop.put("mail.smtp.password", "rriiqquueellmmee");
        prop.put("mail.smtp.port", 587);
        prop.put("mail.smtp.auth", "true");

        Session sesion = Session.getDefaultInstance(prop, null);
        MimeMessage mensaje = new MimeMessage(sesion);

        mensaje.setFrom(new InternetAddress());
        mensaje.setRecipient(Message.RecipientType.TO, new InternetAddress("hector.riquelme1169@gmail.com"));
        mensaje.setSubject("CONTACTO MIS CONCEPTOS");
        mensaje.setText(req.getParameter("mensaje_contacto"));

        Transport transport = sesion.getTransport("smtp");
        transport.connect(host, "hector.riquelme1169@gmail.com", "rriiqquueellmmee");
        transport.sendMessage(mensaje, mensaje.getAllRecipients());

        transport.close();

    } catch (Exception e) {

    }

    return req.getParameter("mensaje_contacto") + "  -  " + req.getParameter("email_contacto");
}

From source file:org.alfresco.repo.security.authentication.ResetPasswordServiceImplTest.java

@Test
public void testResetPasswordInvalid() throws Exception {
    // Request password reset
    resetPasswordService.requestReset(testPerson.userName, "share");
    assertEquals("A reset password email should have been sent.", 1, emailUtil.getSentCount());
    // Check the email
    MimeMessage msg = emailUtil.getLastEmail();
    assertNotNull(msg);/*from  ww  w .ja v  a2  s. com*/
    assertEquals("Should've been only one email recipient.", 1, msg.getAllRecipients().length);
    // Check the reset password url.
    String resetPasswordUrl = (String) emailUtil.getLastEmailTemplateModelValue("reset_password_url");
    assertNotNull("Wrong email is sent.", resetPasswordUrl);
    // Get the workflow id and key
    Pair<String, String> pair = getWorkflowIdAndKeyFromUrl(resetPasswordUrl);
    assertNotNull("Workflow Id can't be null.", pair.getFirst());
    assertNotNull("Workflow Key can't be null.", pair.getSecond());

    emailUtil.reset();

    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(null),
            IllegalArgumentException.class, "null parameter.");

    // Now that we have got the email, try to reset the password
    ResetPasswordDetails passwordDetails = new ResetPasswordDetails().setUserId(null)// user id is not provided
            .setPassword("newPassword").setWorkflowId(pair.getFirst()).setWorkflowKey(pair.getSecond());

    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            IllegalArgumentException.class, "User id is mandatory.");

    passwordDetails.setUserId(testPerson.userName).setPassword(null); // Password is not provided
    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            IllegalArgumentException.class, "Password is mandatory.");

    passwordDetails.setPassword(""); // Invalid password value
    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            IllegalArgumentException.class, "Invalid password value.");

    passwordDetails.setPassword("newPassword").setWorkflowId(null); // Workflow id is not provided
    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            IllegalArgumentException.class, "Workflow id is mandatory.");

    passwordDetails.setWorkflowId(pair.getFirst()).setWorkflowKey(null); //Workflow key is not provided
    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            IllegalArgumentException.class, "Workflow key is mandatory.");

    passwordDetails.setWorkflowId("activiti$" + System.currentTimeMillis()) // Invalid Id
            .setWorkflowKey(pair.getSecond());
    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            ResetPasswordWorkflowNotFoundException.class,
            "The workflow instance with the invalid id should not have been found.");

    passwordDetails.setWorkflowId(pair.getFirst()).setWorkflowKey(GUID.generate()); // Invalid key
    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            InvalidResetPasswordWorkflowException.class,
            "The recovered key does not match the given workflow key.");

    passwordDetails.setUserId("marco.polo").setWorkflowId(pair.getFirst()).setWorkflowKey(pair.getSecond());
    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            InvalidResetPasswordWorkflowException.class,
            "The given user id does not match the person's user id who requested the password reset.");

    assertEquals("No email should have been sent.", 0, emailUtil.getSentCount());
}

From source file:com.wso2telco.workflow.notification.EmailService.java

public void sendEmail(final String emailAddress, final String subject, final String content) {

    new Thread() {
        @Override/*from  w  w  w  .j a  v a2 s  .c om*/
        public void run() {
            Map<String, String> workflowProperties = WorkflowProperties.loadWorkflowPropertiesFromXML();
            String emailHost = workflowProperties.get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_HOST);
            String fromEmailAddress = workflowProperties
                    .get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_ADDRESS);
            String fromEmailPassword = workflowProperties
                    .get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_PASSWORD);

            Properties props = System.getProperties();
            props.put("mail.smtp.host", emailHost);
            props.put("mail.smtp.user", fromEmailAddress);
            props.put("mail.smtp.password", fromEmailPassword);
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.auth", "true");

            try {
                Session session = Session.getDefaultInstance(props, null);
                InternetAddress toAddress = new InternetAddress(emailAddress);

                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(fromEmailAddress));
                message.addRecipient(Message.RecipientType.TO, toAddress);
                message.setSubject(subject);
                message.setContent(content, "text/html; charset=UTF-8");

                Transport transport = session.getTransport("smtp");
                transport.connect(emailHost, fromEmailAddress, fromEmailPassword);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

            } catch (Exception e) {
                log.error("Email sending failed. ", e);
            }
        }
    }.start();
}

From source file:org.alfresco.repo.security.authentication.ResetPasswordServiceImplTest.java

@Test
public void testResetPassword() throws Exception {
    // Try the credential before change of password
    authenticateUser(testPerson.userName, testPerson.password);

    // Make sure to run as system
    AuthenticationUtil.clearCurrentSecurityContext();
    AuthenticationUtil.setRunAsUserSystem();

    // Request password reset
    resetPasswordService.requestReset(testPerson.userName, "share");
    assertEquals("A reset password email should have been sent.", 1, emailUtil.getSentCount());
    // Check the email
    MimeMessage msg = emailUtil.getLastEmail();
    assertNotNull("There should be an email.", msg);
    assertEquals("Should've been only one email recipient.", 1, msg.getAllRecipients().length);
    // Check the recipient is the person who requested the reset password
    assertEquals(testPerson.email, msg.getAllRecipients()[0].toString());
    //Check the sender is what we set as default
    assertEquals(DEFAULT_SENDER, msg.getFrom()[0].toString());
    // There should be a subject
    assertNotNull("There should be a subject.", msg.getSubject());
    // Check the default email subject - (check that we are sending the right email)
    String emailSubjectKey = getDeclaredField(SendResetPasswordEmailDelegate.class, "EMAIL_SUBJECT_KEY");
    assertNotNull(emailSubjectKey);//ww w .j  a  v a 2  s . c  o  m
    assertEquals(msg.getSubject(), I18NUtil.getMessage(emailSubjectKey));

    // Check the reset password url.
    String resetPasswordUrl = (String) emailUtil.getLastEmailTemplateModelValue("reset_password_url");
    assertNotNull("Wrong email is sent.", resetPasswordUrl);
    // Get the workflow id and key
    Pair<String, String> pair = getWorkflowIdAndKeyFromUrl(resetPasswordUrl);
    assertNotNull("Workflow Id can't be null.", pair.getFirst());
    assertNotNull("Workflow Key can't be null.", pair.getSecond());

    emailUtil.reset();
    // Now that we have got the email, try to reset the password
    ResetPasswordDetails passwordDetails = new ResetPasswordDetails().setUserId(testPerson.userName)
            .setPassword("newPassword").setWorkflowId(pair.getFirst()).setWorkflowKey(pair.getSecond());

    resetPasswordService.initiateResetPassword(passwordDetails);
    assertEquals("A reset password confirmation email should have been sent.", 1, emailUtil.getSentCount());
    // Check the email
    msg = emailUtil.getLastEmail();
    assertNotNull("There should be an email.", msg);
    assertEquals("Should've been only one email recipient.", 1, msg.getAllRecipients().length);
    // Check the recipient is the person who requested the reset password
    assertEquals(testPerson.email, msg.getAllRecipients()[0].toString());
    // Check the sender is what we set as default
    assertEquals(DEFAULT_SENDER, msg.getFrom()[0].toString());
    // There should be a subject
    assertNotNull("There should be a subject.", msg.getSubject());
    // Check the default email subject - (check that we are sending the right email)
    emailSubjectKey = getDeclaredField(SendResetPasswordConfirmationEmailDelegate.class, "EMAIL_SUBJECT_KEY");
    assertNotNull(emailSubjectKey);
    assertEquals(msg.getSubject(), I18NUtil.getMessage(emailSubjectKey));

    // Try the old credential
    TestHelper.assertThrows(() -> authenticateUser(testPerson.userName, testPerson.password),
            AuthenticationException.class,
            "As the user changed her password, the authentication should have failed.");

    // Try the new credential
    authenticateUser(testPerson.userName, "newPassword");

    // Make sure to run as system
    AuthenticationUtil.clearCurrentSecurityContext();
    AuthenticationUtil.setRunAsUserSystem();
    emailUtil.reset();
    // Try reset again with the used workflow
    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            InvalidResetPasswordWorkflowException.class,
            "The workflow instance is not active (it has already been used).");
    assertEquals("No email should have been sent.", 0, emailUtil.getSentCount());
}

From source file:org.opencastproject.kernel.mail.BaseSmtpService.java

/**
 * Sends <code>message</code> using the configured transport.
 *
 * @param message/*from  w ww.  j  a  v  a 2 s .c o m*/
 *          the message
 * @throws MessagingException
 *           if sending the message failed
 */
public void send(MimeMessage message) throws MessagingException {
    if (!productionMode) {
        logger.debug("Skipping sending of message {} due to test mode", message);
        return;
    }
    Transport t = getSession().getTransport(mailTransport);
    try {
        if (user != null)
            t.connect(user, password);
        else
            t.connect();
        t.sendMessage(message, message.getAllRecipients());
    } finally {
        t.close();
    }
}

From source file:com.zimbra.cs.mime.MimeTest.java

@Test
public void semiColonAddressSeparator() throws Exception {
    StringBuilder to = new StringBuilder("To: ");
    int count = 4;
    for (int i = 1; i < count + 1; i++) {
        to.append("user").append(count).append("@example.com").append(";");
    }//from ww  w  . j  a  v  a 2 s  . c o  m
    to.setLength(to.length() - 1);
    to.append("\r\n");
    String content = "From: user1@example.com\r\n" + to.toString() + "Subject: test\r\n"
            + "Content-Type: test/plain\r\n\r\n" + "test message";

    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession(),
            new SharedByteArrayInputStream(content.getBytes()));

    Address[] recipients = mm.getAllRecipients();
    Assert.assertEquals(count, recipients.length);
}