Example usage for javax.mail.internet MimeMessage addRecipient

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

Introduction

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

Prototype

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

Source Link

Document

Add this recipient address to the existing ones of the given type.

Usage

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void putMailInMailbox(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
        final MimeMessage message = new MimeMessage((Session) null);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS).getInbox().add(message);
    }/*from   w  w  w  .  j  a va 2s.com*/

    logger.info("Putted " + messages + " into mailbox " + EMAIL_USER_ADDRESS);
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void putMailInMailbox2(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
        final MimeMessage message = new MimeMessage((Session) null);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS2));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS2).getInbox().add(message);
    }/*from w w w.jav  a  2s. c o  m*/

    logger.info("Putted " + messages + " into mailbox " + EMAIL_USER_ADDRESS2);
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void putMailInMailbox3(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
        final MimeMessage message = new MimeMessage((Session) null);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS3));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS3).getInbox().add(message);
    }//from  ww w  . ja v  a 2s .co  m

    logger.info("Putted " + messages + " into mailbox " + EMAIL_USER_ADDRESS3);
}

From source file:org.nuxeo.ecm.automation.core.mail.Mailer.java

/**
 * Send a single email.//from w  ww  . ja v  a 2s.co m
 */
public void sendEmail(String from, String to, String subject, String body) throws MessagingException {
    // Here, no Authenticator argument is used (it is null).
    // Authenticators are used to prompt the user for user
    // name and password.
    MimeMessage message = new MimeMessage(getSession());
    // the "from" address may be set in code, or set in the
    // config file under "mail.from" ; here, the latter style is used
    message.setFrom(new InternetAddress(from));
    message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(body);
    Transport.send(message);
}

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

@Test
public void testGetAllRecipients() throws AddressException, MessagingException {
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    mail.addFrom(new InternetAddress[] { new InternetAddress("bart.simpson@silverpeas.com") });
    mail.addRecipient(RecipientType.TO, new InternetAddress("lisa.simpson@silverpeas.com"));
    mail.addRecipient(RecipientType.TO, new InternetAddress("marge.simpson@silverpeas.com"));
    mail.addRecipient(RecipientType.CC, new InternetAddress("homer.simpson@silverpeas.com"));
    mail.addRecipient(RecipientType.CC, new InternetAddress("krusty.theklown@silverpeas.com"));
    mail.addRecipient(RecipientType.BCC, new InternetAddress("ned.flanders@silverpeas.com"));
    mail.addRecipient(RecipientType.BCC, new InternetAddress("ted.flanders@silverpeas.com"));
    Set<String> recipients = messageChecker.getAllRecipients(mail);
    assertNotNull(recipients);/*from  w  w  w  .  j  a  v a  2s.c  o m*/
    assertEquals(6, recipients.size());
    assertTrue(recipients.contains("lisa.simpson@silverpeas.com"));
    assertTrue(recipients.contains("marge.simpson@silverpeas.com"));
    assertTrue(recipients.contains("homer.simpson@silverpeas.com"));
    assertTrue(recipients.contains("krusty.theklown@silverpeas.com"));
    assertTrue(recipients.contains("ned.flanders@silverpeas.com"));
    assertTrue(recipients.contains("ted.flanders@silverpeas.com"));
}

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   ww w.ja  v a2 s  . c  om*/
    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:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java

/**
 * Send email with Amazon Simple Email Service.
 * <p/>/*from  w w  w. ja  v  a2s  .c  o  m*/
 * 
 * Please note that the sender (ie 'from') must be a verified address (see
 * {@link AmazonSimpleEmailService#verifyEmailAddress(com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest)}
 * ).
 * <p/>
 * 
 * Please note that the sender is a CC of the meail to ease support.
 * <p/>
 * 
 * @param subject
 * @param body
 * @param from
 * @param toAddresses
 * @throws MessagingException
 * @throws AddressException
 */
public void sendEmail(String subject, String body, AccessKey accessKey, KeyPair sshKeyPair,
        java.security.KeyPair x509KeyPair, X509Certificate x509Certificate,
        SigningCertificate signingCertificate, String from, String toAddress) {

    try {
        Session s = Session.getInstance(new Properties(), null);
        MimeMessage msg = new MimeMessage(s);

        msg.setFrom(new InternetAddress(from));
        msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress));
        msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(from));

        msg.setSubject(subject);

        MimeMultipart mimeMultiPart = new MimeMultipart();
        msg.setContent(mimeMultiPart);

        // body
        BodyPart plainTextBodyPart = new MimeBodyPart();
        mimeMultiPart.addBodyPart(plainTextBodyPart);
        plainTextBodyPart.setContent(body, "text/plain");

        // aws-credentials.txt / accessKey
        {
            BodyPart awsCredentialsBodyPart = new MimeBodyPart();
            awsCredentialsBodyPart.setFileName("aws-credentials.txt");
            StringWriter awsCredentialsStringWriter = new StringWriter();
            PrintWriter awsCredentials = new PrintWriter(awsCredentialsStringWriter);
            awsCredentials
                    .println("#Insert your AWS Credentials from http://aws.amazon.com/security-credentials");
            awsCredentials.println("#" + new DateTime());
            awsCredentials.println();
            awsCredentials.println("# ec2, rds & elb tools use accessKey and secretKey");
            awsCredentials.println("accessKey=" + accessKey.getAccessKeyId());
            awsCredentials.println("secretKey=" + accessKey.getSecretAccessKey());
            awsCredentials.println();
            awsCredentials.println("# iam tools use AWSAccessKeyId and AWSSecretKey");
            awsCredentials.println("AWSAccessKeyId=" + accessKey.getAccessKeyId());
            awsCredentials.println("AWSSecretKey=" + accessKey.getSecretAccessKey());

            awsCredentialsBodyPart.setContent(awsCredentialsStringWriter.toString(), "text/plain");
            mimeMultiPart.addBodyPart(awsCredentialsBodyPart);
        }
        // private ssh key
        {
            BodyPart keyPairBodyPart = new MimeBodyPart();
            keyPairBodyPart.setFileName(sshKeyPair.getKeyName() + ".pem.txt");
            keyPairBodyPart.setContent(sshKeyPair.getKeyMaterial(), "application/octet-stream");
            mimeMultiPart.addBodyPart(keyPairBodyPart);
        }

        // x509 private key
        {
            BodyPart x509PrivateKeyBodyPart = new MimeBodyPart();
            x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem.txt");
            String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate());
            x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/octet-stream");
            mimeMultiPart.addBodyPart(x509PrivateKeyBodyPart);
        }
        // x509 private key
        {
            BodyPart x509CertificateBodyPart = new MimeBodyPart();
            x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem.txt");
            String x509CertificatePem = Pems.pem(x509Certificate);
            x509CertificateBodyPart.setContent(x509CertificatePem, "application/octet-stream");
            mimeMultiPart.addBodyPart(x509CertificateBodyPart);
        }
        // Convert to raw message
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);

        RawMessage rawMessage = new RawMessage();
        rawMessage.setData(ByteBuffer.wrap(out.toString().getBytes()));

        ses.sendRawEmail(new SendRawEmailRequest().withRawMessage(rawMessage));
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.evolveum.midpoint.notifications.impl.api.transports.MailTransport.java

@Override
public void send(Message mailMessage, String transportName, Task task, OperationResult parentResult) {

    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo());
    result.addParam("mailMessage subject", mailMessage.getSubject());

    SystemConfigurationType systemConfiguration = NotificationsUtil
            .getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null
            || systemConfiguration.getNotificationConfiguration().getMail() == null) {
        String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);// w ww.  j a va 2 s  . c o m
        result.recordWarning(msg);
        return;
    }

    MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
    String redirectToFile = mailConfigurationType.getRedirectToFile();
    if (redirectToFile != null) {
        try {
            TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage));
            result.recordSuccess();
        } catch (IOException e) {
            LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile);
            result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e);
        }
        return;
    }

    if (mailConfigurationType.getServer().isEmpty()) {
        String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    long start = System.currentTimeMillis();

    String from = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom()
            : "nobody@nowhere.org";

    for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) {

        OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer");
        final String host = mailServerConfigurationType.getHost();
        resultForServer.addContext("server", host);
        resultForServer.addContext("port", mailServerConfigurationType.getPort());

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        if (mailServerConfigurationType.getPort() != null) {
            properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort()));
        }
        MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType
                .getTransportSecurity();

        boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false;
        switch (mailTransportSecurityType) {
        case STARTTLS_ENABLED:
            starttlsEnable = true;
            break;
        case STARTTLS_REQUIRED:
            starttlsEnable = true;
            starttlsRequired = true;
            break;
        case SSL:
            sslEnabled = true;
            break;
        }
        properties.put("mail.smtp.ssl.enable", "" + sslEnabled);
        properties.put("mail.smtp.starttls.enable", "" + starttlsEnable);
        properties.put("mail.smtp.starttls.required", "" + starttlsRequired);
        if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) {
            properties.put("mail.debug", "true");
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Using mail properties: ");
            for (Object key : properties.keySet()) {
                if (key instanceof String && ((String) key).startsWith("mail.")) {
                    LOGGER.debug(" - " + key + " = " + properties.get(key));
                }
            }
        }

        task.recordState("Sending notification mail via " + host);

        Session session = Session.getInstance(properties);

        try {
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            for (String recipient : mailMessage.getTo()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
            }
            mimeMessage.setSubject(mailMessage.getSubject(), "utf-8");
            String contentType = mailMessage.getContentType();
            if (StringUtils.isEmpty(contentType)) {
                contentType = "text/plain; charset=UTF-8";
            }
            mimeMessage.setContent(mailMessage.getBody(), contentType);
            javax.mail.Transport t = session.getTransport("smtp");
            if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) {
                ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword();
                String password = null;
                if (passwordProtected != null) {
                    try {
                        password = protector.decryptString(passwordProtected);
                    } catch (EncryptionException e) {
                        String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host
                                + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any.";
                        LoggingUtils.logException(LOGGER, msg, e);
                        resultForServer.recordFatalError(msg, e);
                        continue;
                    }
                }
                t.connect(mailServerConfigurationType.getUsername(), password);
            } else {
                t.connect();
            }
            t.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + ".");
            resultForServer.recordSuccess();
            result.recordSuccess();
            long duration = System.currentTimeMillis() - start;
            task.recordState(
                    "Notification mail sent successfully via " + host + ", in " + duration + " ms overall.");
            task.recordNotificationOperation(NAME, true, duration);
            return;
        } catch (MessagingException e) {
            String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host
                    + ", trying another mail server, if there is any";
            LoggingUtils.logException(LOGGER, msg, e);
            resultForServer.recordFatalError(msg, e);
            task.recordState("Error sending notification mail via " + host);
        }
    }
    LOGGER.warn(
            "No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent.");
    result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent.");
    task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start);
}

From source file:org.wf.dp.dniprorada.util.Mail.java

@Override
public void send() throws EmailException {

    try {//from  w w w.  java  2  s .  c om
        log.info("init");
        MultiPartEmail oMultiPartEmail = new MultiPartEmail();
        oMultiPartEmail.setHostName(getHost());
        log.info("getHost()=" + getHost());
        oMultiPartEmail.addTo(getTo(), "receiver");
        log.info("getTo()=" + getTo());
        oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov"
        log.info("getFrom()=" + getFrom());
        oMultiPartEmail.setSubject(getHead());
        log.info("getHead()=" + getHead());

        oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword());
        log.info("getAuthUser()=" + getAuthUser());
        log.info("getAuthPassword()=" + getAuthPassword());
        oMultiPartEmail.setSmtpPort(getPort());
        log.info("getPort()=" + getPort());
        oMultiPartEmail.setSSL(isSSL());
        log.info("isSSL()=" + isSSL());
        oMultiPartEmail.setTLS(isTLS());
        log.info("isTLS()=" + isTLS());

        oSession = oMultiPartEmail.getMailSession();
        MimeMessage oMimeMessage = new MimeMessage(oSession);

        //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING));
        oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom()));
        //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING));
        oMimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING));

        oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING);

        _Attach(getBody());

        oMimeMessage.setContent(oMultiparts);

        //            oMimeMessage.getRecipients(Message.RecipientType.CC);
        Transport.send(oMimeMessage);
        log.info("[send]:Transport.send!");
    } catch (Exception exc) {
        log.error("[send]", exc);
        throw new EmailException("Error happened when sending email", exc);
    }
}

From source file:org.snopoke.util.Emailer.java

/**
 * Create the MimeMessage and set the to/from/subject
 * // w  w  w . j  av  a  2s  .  c om
 * @return MimeMessaeg
 * @throws MessagingException
 */
private MimeMessage getMessasge() throws MessagingException {
    MimeMessage message = new MimeMessage(getSession());
    message.setSentDate(new Date());

    for (Address toAddress : to) {
        message.addRecipient(RecipientType.TO, toAddress.getInternetAddress());
    }

    for (Address toAddress : cc) {
        message.addRecipient(RecipientType.CC, toAddress.getInternetAddress());
    }

    for (Address toAddress : bcc) {
        message.addRecipient(RecipientType.BCC, toAddress.getInternetAddress());
    }

    message.setFrom(from.getInternetAddress());

    if (subject != null && !subject.isEmpty())
        message.setSubject(subject, "UTF-8");
    return message;
}