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:org.ktunaxa.referral.server.command.email.SendEmailCommand.java

private void addRecipients(MimeMessage mimeMessage, Message.RecipientType recipientType, String recipients)
        throws MessagingException {
    if (null != recipients && recipients.length() > 0) {
        for (String part : recipients.split("[,;\\s]")) {
            String address = part.trim();
            if (address.length() > 0) {
                mimeMessage.addRecipient(recipientType, new InternetAddress(address));
            }//from  w w  w.j a v  a2  s . c  o m
        }
    }
}

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

protected void createInitialIMAPTestdata(final Properties props, final String user, final String password,
        final int count, final boolean deleteall) throws MessagingException {
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);/*from w  w w  .  j a v a2s  . c o m*/
    checkStoreForTestConnection(store);
    final Folder root = store.getDefaultFolder();
    final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS");
    final Folder testrootl2 = testroot.getFolder("Level(2!");

    if (deleteall) {

        deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password);

        if (testroot.exists()) {
            testroot.delete(true);
        }

        final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS");
        if (testrootenamed.exists()) {
            testrootenamed.delete(true);
        }

    }

    if (!testroot.exists()) {

        testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testroot.open(Folder.READ_WRITE);

        testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testrootl2.open(Folder.READ_WRITE);

    }

    final Folder inbox = root.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);

    final Message[] msgs = new Message[count];

    for (int i = 0; i < count; i++) {
        final MimeMessage message = new MimeMessage(session);
        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());
        msgs[i] = message;

    }

    inbox.appendMessages(msgs);
    testroot.appendMessages(msgs);
    testrootl2.appendMessages(msgs);

    IMAPUtils.close(inbox);
    IMAPUtils.close(testrootl2);
    IMAPUtils.close(testroot);
    IMAPUtils.close(store);

}

From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java

public void send(Message msg) {
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.transport.protocol", "smtp");

    if (username != null && !username.isEmpty()) {
        properties.setProperty("mail.user", username);
        properties.setProperty("mail.password", password);
    }// w ww .  j a  va2  s  .  c  om

    if (port != null && !port.isEmpty()) {
        properties.setProperty("mail.smtp.port", port);
    }

    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(msg.getFrom());
        if (msg.getTo().size() > 1) {
            List<InternetAddress> addresses = msg.getTo();
            message.addRecipients(TO, addresses.toArray(new Address[addresses.size()]));
        } else {
            message.addRecipient(TO, msg.getTo().get(0));
        }
        if (msg.getBcc() != null && msg.getBcc().size() != 0) {
            if (msg.getTo().size() > 1) {
                List<InternetAddress> addresses = msg.getBcc();
                message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(TO, msg.getBcc().get(0));
            }
        }
        if (msg.getCc() != null && msg.getCc().size() > 0) {
            if (msg.getCc().size() > 1) {
                List<InternetAddress> addresses = msg.getCc();
                message.addRecipients(CC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(CC, msg.getCc().get(0));
            }
        }
        message.setSubject(msg.getSubject(), "UTF-8");
        MimeBodyPart mbp1 = new MimeBodyPart();
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();

        if (msg.getBodyType() == Message.BodyType.HTML_TEXT) {
            mbp1.setContent(msg.getBody(), "text/html");
        } else {
            mbp1.setText(msg.getBody(), "UTF-8");
        }
        if (port != null && !port.isEmpty()) {
            properties.setProperty("mail.smtp.port", port);
        }
        mp.addBodyPart(mbp1);
        if (msg.getAttachments().size() > 0) {
            for (String fileName : msg.getAttachments()) {
                // create the second message part
                MimeBodyPart mbpFile = new MimeBodyPart();
                // attach the file to the message
                FileDataSource fds = new FileDataSource(fileName);
                mbpFile.setDataHandler(new DataHandler(fds));
                mbpFile.setFileName(fds.getName());

                mp.addBodyPart(mbpFile);
            }
        }
        // add the Multipart to the message
        message.setContent(mp);

        if (username != null && !username.isEmpty()) {
            properties.setProperty("mail.user", username);
            properties.setProperty("mail.password", password);
            properties.put("mail.smtp.auth", auth);
            properties.put("mail.smtp.starttls.enable", starttls);
            Transport mailTransport = session.getTransport();
            mailTransport.connect(host, username, password);
            mailTransport.sendMessage(message, message.getAllRecipients());

        } else {
            Transport.send(message);
            log.debug("Message successfully sent.");
        }
    } catch (Throwable e) {
        log.error("Exception while sending mail", e);
    }
}

From source file:com.basicservice.service.MailService.java

public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception {
    try {//from   w w w.jav  a2 s.c  om
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.auth", "true");
        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        // mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        Multipart multipart = new MimeMultipart("alternative");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html");
        multipart.addBodyPart(htmlPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(from));
        message.setSubject(subject, "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        transport.connect();
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        transport.close();
    } catch (Exception e) {
        LOG.debug("Exception while sending email: ", e);
        throw e;
    }
}

From source file:org.georchestra.console.mailservice.Email.java

protected void sendMsg(String msg) throws AddressException, MessagingException {

    if (LOG.isDebugEnabled()) {
        LOG.debug("body: " + msg);
    }// w w  w  . j  av  a2  s. co m

    // Replace {publicUrl} token with the configured public URL
    msg = msg.replaceAll("\\{publicUrl\\}", this.georConfig.getProperty("publicUrl"));

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", smtpHost);
    session.getProperties().setProperty("mail.smtp.port", (new Integer(smtpPort)).toString());

    final MimeMessage message = new MimeMessage(session);

    if (isValidEmailAddress(from)) {
        message.setFrom(new InternetAddress(from));
    }
    boolean validRecipients = false;
    for (String recipient : recipients) {
        if (isValidEmailAddress(recipient)) {
            validRecipients = true;
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        }
    }

    if (!validRecipients) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(from));
        message.setSubject("[ERREUR] Message non dlivr : " + subject, subjectEncoding);
    } else {
        message.setSubject(subject, subjectEncoding);
    }

    if (msg != null) {
        /* See http://www.rgagnon.com/javadetails/java-0321.html */
        if ("true".equalsIgnoreCase(emailHtml)) {
            message.setContent(msg, "text/html; charset=" + bodyEncoding);
        } else {
            message.setContent(msg, "text/plain; charset=" + bodyEncoding);
        }
        LOG.debug(msg);
    }

    Transport.send(message);
    LOG.debug("email has been sent to:\n" + Arrays.toString(recipients));
}

From source file:cc.kune.core.server.mail.MailServiceDefault.java

@Override
public void send(final String from, final AbstractFormattedString subject, final AbstractFormattedString body,
        final boolean isHtml, final String... tos) {
    if (smtpSkip) {
        return;//  w  ww  .  j av  a 2s  .c o m
    }

    // Get session
    final Session session = Session.getDefaultInstance(props, null);

    // Define message
    final MimeMessage message = new MimeMessage(session);
    for (final String to : tos) {
        try {
            message.setFrom(new InternetAddress(from));
            // In case we should use utf8 also in address:
            // http://stackoverflow.com/questions/2656478/send-javax-mail-internet-mimemessage-to-a-recipient-with-non-ascii-name
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // If additional header should be added
            // message.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B"));
            final String formatedSubject = subject.getString();
            message.setSubject(formatedSubject, "utf-8");
            final String formatedBody = body.getString();
            if (isHtml) {
                // message.setContent(formatedBody, "text/html");
                message.setText(formatedBody, "UTF-8", "html");
            } else {
                message.setText(formatedBody, "UTF-8");
            }
            // Send message
            Transport.send(message);
        } catch (final AddressException e) {
        } catch (final MessagingException e) {
            final String error = String.format("Error sendind an email to %s, with subject: %s, and body: %s",
                    from, subject, to);
            log.error(error, e);
            // Better not to throw exceptions because users emails can be wrong...
            // throw new DefaultException(error, e);
        }
    }
}

From source file:com.fstx.stdlib.common.messages.MailSenderImpl.java

/**
 * @see com.ess.messages.MailSender#send()
 *///from  w w  w . j a v a  2s  .  c o  m
public boolean send() {

    try {
        // 2005-11-27 RSC always requires authentication.
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");

        props.put("mail.smtp.host", host.getAddress());
        /*
         * 2005-11-27 RSC
         * Since webmail.us is starting to make other ports available
         * as Comcast blocks port 25.
         */
        props.put("mail.smtp.port", host.getPort());

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

        MimeMessage messageOut = new MimeMessage(s);

        InternetAddress fromOut = new InternetAddress(from.getAddress());

        //reid 2004-12-20
        fromOut.setPersonal(from.getName());

        messageOut.setFrom(fromOut);

        InternetAddress toOut = new InternetAddress(this.to.getAddress());

        //reid 2004-12-20
        toOut.setPersonal(to.getName());

        messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut);

        messageOut.setSubject(message.getSubject());

        messageOut.setText(message.getMessage());

        if (host.useAuthentication()) {

            Transport transport = s.getTransport("smtp");
            transport.connect(host.getAddress(), host.getUsername(), host.getPassword());
            transport.sendMessage(messageOut, messageOut.getAllRecipients());
            transport.close();
        } else {

            Transport.send(messageOut);
        }

    } catch (Exception e) {
        log.info("\n\nMailSenderIMPL3: " + host.getAddress());
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    return true;
}

From source file:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailMessage.java

public boolean send() {
    try {/*from w ww  .j  ava2  s. c  om*/
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setReplyTo(new Address[] { replyToAddress });

        if (fromAddress == null) {
            msg.addFrom(new Address[] { replyToAddress });
        } else {
            msg.addFrom(new Address[] { fromAddress });
        }

        for (Recipient recipient : recipients) {
            msg.addRecipient(recipient.type, recipient.address);
        }

        msg.setSubject(subject);

        if (textContent.isEmpty()) {
            if (htmlContent.isEmpty()) {
                log.error("Message has neither text body nor HTML body");
            } else {
                msg.setContent(htmlContent, "text/html");
            }
        } else {
            if (htmlContent.isEmpty()) {
                msg.setContent(textContent, "text/plain");
            } else {
                MimeMultipart content = new MimeMultipart("alternative");
                addBodyPart(content, textContent, "text/plain");
                addBodyPart(content, htmlContent, "text/html");
                msg.setContent(content);
            }
        }

        msg.setSentDate(new Date());

        Transport.send(msg);
        return true;
    } catch (MessagingException e) {
        log.error("Failed to send message.", e);
        return false;
    }
}

From source file:com.fsrin.menumine.common.message.MailSenderImpl.java

/**
 * @see com.ess.messages.MailSender#send()
 *//* ww  w  .  j ava2  s .  c o  m*/
public boolean send() {

    try {

        Properties props = new Properties();

        props.put("mail.smtp.host", host.getAddress());

        if (host.useAuthentication()) {

            props.put("mail.smtp.auth", "true");
        }

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

        s.setDebug(true);

        //            PasswordAuthentication pa = new PasswordAuthentication(host
        //                    .getUsername(), host.getPassword());
        //
        //            URLName url = new URLName(host.getAddress());
        //
        //            s.setPasswordAuthentication(url, pa);

        MimeMessage messageOut = new MimeMessage(s);

        InternetAddress fromOut = new InternetAddress(from.getAddress());

        //reid 2004-12-20
        fromOut.setPersonal(from.getName());

        messageOut.setFrom(fromOut);

        InternetAddress toOut = new InternetAddress(this.to.getAddress());

        //reid 2004-12-20
        toOut.setPersonal(to.getName());

        messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut);

        messageOut.setSubject(message.getSubject());

        messageOut.setText(message.getMessage());

        if (host.useAuthentication()) {

            Transport transport = s.getTransport("smtp");
            transport.connect(host.getAddress(), host.getUsername(), host.getPassword());
            transport.sendMessage(messageOut, messageOut.getAllRecipients());
            transport.close();
        } else {

            Transport.send(messageOut);
        }

    } catch (Exception e) {
        log.info("\n\nMailSenderIMPL3: " + host.getAddress());

        e.printStackTrace();
        throw new RuntimeException(e);

    }

    return true;
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

private void sendEmail(Map<String, String> templatesParams, List<BodyPart> attachments, String toAddress)
        throws MessagingException {

    MimeBodyPart htmlAndPlainTextAlternativeBody = new MimeBodyPart();

    // TEXT AND HTML MESSAGE (gmail requires plain text alternative, otherwise, it displays the 1st plain text attachment in the preview)
    MimeMultipart cover = new MimeMultipart("alternative");
    htmlAndPlainTextAlternativeBody.setContent(cover);
    BodyPart textHtmlBodyPart = new MimeBodyPart();
    String textHtmlBody = FreemarkerUtils.generate(templatesParams,
            "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier()
                    + ".html.ftl");
    textHtmlBodyPart.setContent(textHtmlBody, "text/html");
    cover.addBodyPart(textHtmlBodyPart);

    BodyPart textPlainBodyPart = new MimeBodyPart();
    cover.addBodyPart(textPlainBodyPart);
    String textPlainBody = FreemarkerUtils.generate(templatesParams,
            "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier()
                    + ".txt.ftl");
    textPlainBodyPart.setContent(textPlainBody, "text/plain");

    MimeMultipart content = new MimeMultipart("related");
    content.addBodyPart(htmlAndPlainTextAlternativeBody);

    // ATTACHMENTS
    for (BodyPart bodyPart : attachments) {
        content.addBodyPart(bodyPart);/*from ww w  .j  av a  2 s.c  o m*/
    }

    MimeMessage msg = new MimeMessage(mailSession);

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

    String subject = "[Xebia Amazon AWS " + environment.getIdentifier() + "] Credentials";

    msg.setSubject(subject);
    msg.setContent(content);

    mailTransport.sendMessage(msg, msg.getAllRecipients());
}