Example usage for javax.mail.internet MimeMessage setRecipient

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

Introduction

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

Prototype

public void setRecipient(RecipientType type, Address address) throws MessagingException 

Source Link

Document

Set the recipient address.

Usage

From source file:org.medici.bia.service.mail.MailServiceImpl.java

/**
 * {@inheritDoc}//from   w w  w.j a va  2s.  c o m
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public Boolean sendEmailMessageUser(final EmailMessageUser emailMessageUser) {
    try {
        if (!StringUtils.isBlank(emailMessageUser.getUser().getMail())) {
            //            SimpleMailMessage message = new SimpleMailMessage();
            //            message.setFrom(getMailFrom());
            //            message.setTo(emailMessageUser.getUser().getMail());
            //            message.setSubject(emailMessageUser.getSubject());
            //            message.setText(emailMessageUser.getBody());

            MimeMessagePreparator preparator = new MimeMessagePreparator() {

                @Override
                public void prepare(MimeMessage mimeMessage) throws Exception {
                    mimeMessage.setFrom(new InternetAddress(getMailFrom()));
                    mimeMessage.setRecipient(Message.RecipientType.TO,
                            new InternetAddress(emailMessageUser.getUser().getMail()));
                    mimeMessage.setSubject(emailMessageUser.getSubject());
                    mimeMessage.setText(emailMessageUser.getBody(), "utf-8", "html");
                }
            };

            getJavaMailSender().send(preparator);
            emailMessageUser.setMailSended(Boolean.TRUE);
            emailMessageUser.setMailSendedDate(new Date());
            getEmailMessageUserDAO().merge(emailMessageUser);
        } else {
            logger.error("Email message not sended for user " + emailMessageUser.getUser().getAccount()
                    + ". Check mail field on tblUser for account " + emailMessageUser.getUser().getAccount());
        }
        return Boolean.TRUE;
    } catch (Throwable throwable) {
        logger.error(throwable);
        return Boolean.FALSE;
    }
}

From source file:org.mule.transport.email.AbstractGreenMailSupport.java

public MimeMessage getValidMessage(String to) throws Exception {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    message.setContent(MESSAGE, "text/plain");
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    return message;
}

From source file:org.mule.transport.email.GreenMailUtilities.java

public static MimeMessage toMessage(String text, String email, String charset) throws MessagingException {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    if (charset != null) {
        message.setContent(text, "text/plain; charset=" + charset);
    } else {/*from   w  w w. j av a  2  s. co m*/
        message.setContent(text, "text/plain");
    }
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
    return message;
}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendTextMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Session session = Session.getInstance(this.configuration.getAllProperties());

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("mixed");
    // Add text in the body
    multipart.addBodyPart(this.defaultBodyPartFactory.create("some text here",
            Collections.<String, Object>singletonMap("mimetype", "text/plain")));
    message.setContent(multipart);//from  ww  w.  j a v  a2 s .com

    // We also test using some default BCC addresses from configuration in this test
    this.configuration.setBCCAddresses(Arrays.asList("bcc1@doe.com", "bcc2@doe.com"));

    // Ensure we do not reuse the same message identifier for multiple similar messages in this test
    MimeMessage message2 = new MimeMessage(message);
    message2.saveChanges();
    MimeMessage message3 = new MimeMessage(message);
    message3.saveChanges();

    // Step 4: Send the mail and wait for it to be sent
    // Send 3 mails (3 times the same mail) to verify we can send several emails at once.
    MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory");
    this.sender.sendAsynchronously(Arrays.asList(message, message2, message3), session, memoryMailListener);

    // Note: we don't test status reporting from the listener since this is already tested in the
    // ScriptingIntegrationTest test class.

    // Verify that the mails have been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 3);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    // Note: we're receiving 9 messages since we sent 3 with 3 recipients (2 BCC and 1 to)!
    assertEquals(9, messages.length);

    // Assert the email parts that are the same for all mails
    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount());
    BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]);
    assertEquals("some text here", textBodyPart.getContent());
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    // Note: We cannot assert that the BCC worked since by definition BCC information are not visible in received
    // messages ;) But we checked that we received 9 emails above so that's good enough.
}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendHTMLAndCalendarInvitationMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Session session = Session.getInstance(this.configuration.getAllProperties());

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("alternative");
    // Add an HTML body part
    multipart.addBodyPart(//from   ww w .  j a  v a2s. c o  m
            this.htmlBodyPartFactory.create("<font size=\"\\\"2\\\"\">simple meeting invitation</font>",
                    Collections.<String, Object>emptyMap()));
    // Add the Calendar invitation body part
    String calendarContent = "BEGIN:VCALENDAR\r\n" + "METHOD:REQUEST\r\n" + "PRODID: Meeting\r\n"
            + "VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "DTSTAMP:20140616T164100\r\n"
            + "DTSTART:20140616T164100\r\n" + "DTEND:20140616T194100\r\n" + "SUMMARY:test request\r\n"
            + "UID:324\r\n"
            + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:john@doe.com\r\n"
            + "ORGANIZER:MAILTO:john@doe.com\r\n" + "LOCATION:on the net\r\n"
            + "DESCRIPTION:learn some stuff\r\n" + "SEQUENCE:0\r\n" + "PRIORITY:5\r\n" + "CLASS:PUBLIC\r\n"
            + "STATUS:CONFIRMED\r\n" + "TRANSP:OPAQUE\r\n" + "BEGIN:VALARM\r\n" + "ACTION:DISPLAY\r\n"
            + "DESCRIPTION:REMINDER\r\n" + "TRIGGER;RELATED=START:-PT00H15M00S\r\n" + "END:VALARM\r\n"
            + "END:VEVENT\r\n" + "END:VCALENDAR";
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("mimetype", "text/calendar;method=CANCEL");
    parameters.put("headers", Collections.singletonMap("Content-Class", "urn:content-classes:calendarmessage"));
    multipart.addBodyPart(this.defaultBodyPartFactory.create(calendarContent, parameters));

    message.setContent(multipart);

    // Step 4: Send the mail and wait for it to be sent
    this.sender.sendAsynchronously(Arrays.asList(message), session, null);

    // Verify that the mail has been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    assertEquals(2, ((MimeMultipart) messages[0].getContent()).getCount());

    BodyPart htmlBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/html; charset=UTF-8", htmlBodyPart.getHeader("Content-Type")[0]);
    assertEquals("<font size=\"\\\"2\\\"\">simple meeting invitation</font>", htmlBodyPart.getContent());

    BodyPart calendarBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(1);
    assertEquals("text/calendar;method=CANCEL", calendarBodyPart.getHeader("Content-Type")[0]);
    InputStream is = (InputStream) calendarBodyPart.getContent();
    assertEquals(calendarContent, IOUtils.toString(is));
}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendMailWithCustomMessageId() throws Exception {
    Session session = Session.getInstance(this.configuration.getAllProperties());
    MimeMessage message = new MimeMessage(session) {
        @Override/* w ww.  ja v a 2 s. c  om*/
        protected void updateMessageID() throws MessagingException {
            if (getMessageID() == null) {
                super.updateMessageID();
            }
        }
    };
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));
    message.setText("Test message Id support");
    message.setHeader("Message-ID", "<custom@domain>");
    message.setSubject("subject");

    MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory");
    this.sender.sendAsynchronously(Arrays.asList(message), session, memoryMailListener);

    // Verify that the mails have been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals("<custom@domain>", messages[0].getMessageID());
}