Example usage for javax.mail.internet MimeMessage setRecipients

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

Introduction

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

Prototype

public void setRecipients(Message.RecipientType type, String addresses) throws MessagingException 

Source Link

Document

Set the specified recipient type to the given addresses.

Usage

From source file:org.projectforge.mail.SendMail.java

private void sendIt(final Mail composedMessage) {
    final Session session = Session.getInstance(properties);
    Transport transport = null;/*www . java 2  s  . c  om*/
    try {
        MimeMessage message = new MimeMessage(session);
        if (composedMessage.getFrom() != null) {
            message.setFrom(new InternetAddress(composedMessage.getFrom()));
        } else {
            message.setFrom();
        }
        message.setRecipients(Message.RecipientType.TO, composedMessage.getTo());
        String subject;
        subject = composedMessage.getSubject();
        /*
         * try { subject = MimeUtility.encodeText(composedMessage.getSubject()); } catch (UnsupportedEncodingException ex) {
         * log.error("Exception encountered while encoding subject." + ex, ex); subject = composedMessage.getSubject(); }
         */
        message.setSubject(subject, sendMailConfig.getCharset());
        message.setSentDate(new Date());
        if (composedMessage.getContentType() != null) {
            message.setText(composedMessage.getContent(), composedMessage.getCharset(),
                    composedMessage.getContentType());
        } else {
            message.setText(composedMessage.getContent(), sendMailConfig.getCharset());
        }
        message.saveChanges(); // don't forget this
        transport = session.getTransport();
        if (StringUtils.isNotEmpty(sendMailConfig.getUser()) == true) {
            transport.connect(sendMailConfig.getUser(), sendMailConfig.getPassword());
        } else {
            transport.connect();
        }
        transport.sendMessage(message, message.getAllRecipients());
    } catch (MessagingException ex) {
        log.error("While creating and sending message: " + composedMessage.toString(), ex);
        throw new InternalErrorException("mail.error.exception");
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException ex) {
                log.error("While creating and sending message: " + composedMessage.toString(), ex);
                throw new InternalErrorException("mail.error.exception");
            }
        }
    }
    log.info("E-Mail successfully sent: " + composedMessage.toString());
}

From source file:com.reizes.shiva.net.mail.Mail.java

public void sendHtmlMail(String fromName, String from, String to, String cc, String bcc, String subject,
        String content) throws UnsupportedEncodingException, MessagingException {
    boolean parseStrict = false;
    MimeMessage message = new MimeMessage(getSessoin());
    InternetAddress address = InternetAddress.parse(from, parseStrict)[0];

    if (fromName != null) {
        address.setPersonal(fromName, charset);
    }//from  w ww .  j  ava  2 s  .c o  m

    message.setFrom(address);

    message.setRecipients(Message.RecipientType.TO, parseAddresses(to));

    if (cc != null) {
        message.setRecipients(Message.RecipientType.CC, parseAddresses(cc));
    }
    if (bcc != null) {
        message.setRecipients(Message.RecipientType.BCC, parseAddresses(bcc));
    }

    message.setSubject(subject, charset);

    message.setHeader("X-Mailer", "sendMessage");
    message.setSentDate(new java.util.Date()); //   

    Multipart multipart = new MimeMultipart();
    MimeBodyPart bodypart = new MimeBodyPart();
    bodypart.setContent(content, "text/html; charset=" + charset);
    multipart.addBodyPart(bodypart);

    message.setContent(multipart);
    Transport.send(message);
}

From source file:org.cgiar.ccafs.marlo.action.TestSMTPAction.java

@Override
public String execute() throws Exception {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", config.getEmailHost());
    properties.put("mail.smtp.port", config.getEmailPort());

    Session session = Session.getInstance(properties, new Authenticator() {

        @Override// w  w w.  ja  v  a2 s  . co  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(config.getEmailUsername(), config.getEmailPassword());
        }
    });

    // Create a new message
    MimeMessage msg = new MimeMessage(session) {

        @Override
        protected void updateMessageID() throws MessagingException {
            if (this.getHeader("Message-ID") == null) {
                super.updateMessageID();
            }
        }
    };

    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("h.jimenez@cgiar.org", false));
    msg.setSubject("Test email");
    msg.setSentDate(new Date());
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("If you receive this email, it means that the server is working correctly.",
            "text; charset=utf-8");

    Thread thread = new Thread() {

        @Override
        public void run() {

            sent = false;
            int i = 0;
            while (!sent) {
                try {
                    Transport.send(sendMail);
                    LOG.info("Message sent TRIED#: " + i + " \n" + "Test email");
                    sent = true;

                } catch (MessagingException e) {
                    LOG.info("Message  DON'T sent: \n" + "Test email");

                    i++;
                    if (i == 10) {
                        break;

                    }
                    try {
                        Thread.sleep(1 * // minutes to sleep
                        60 * // seconds to a minute
                        1000);
                    } catch (InterruptedException e1) {

                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                }

            }

        };
    };

    thread.run();

    if (sent) {
        return SUCCESS;
    } else {
        return INPUT;
    }
}

From source file:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java

@Override
protected void executeImpl(Action action, NodeRef nodeRef) {
    try {/*from   w w w .j av a  2  s .c  om*/
        MimeMessage mimeMessage = mailService.createMimeMessage();
        mimeMessage.setFrom(new InternetAddress((String) action.getParameterValue(PARAM_FROM)));
        if (action.getParameterValue(PARAM_BCC) != null) {
            mimeMessage.setRecipients(Message.RecipientType.BCC, (String) action.getParameterValue(PARAM_BCC));
        }
        mimeMessage.setRecipients(Message.RecipientType.TO, (String) action.getParameterValue(PARAM_TO));
        mimeMessage.setSubject((String) action.getParameterValue(PARAM_SUBJECT));
        mimeMessage.setHeader("Content-Transfer-Encoding", "text/html; charset=UTF-8");
        addAttachments(action, nodeRef, mimeMessage);
        mailService.send(mimeMessage);
        logger.info("success!");
    } catch (AddressException ex) {
        logger.error("There was an error processing the email address for the mail documents action");
        logger.error(ex);
    } catch (MessagingException ex) {
        logger.error("There was an error processing the email for the mail documents action");
        logger.error(ex);
    } catch (MailException ex) {
        logger.error("There was an error processing the action");
        logger.error(ex);
    }
}

From source file:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java

/**
 * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME
 * format)./*  w w  w.  j av a 2s.  c o m*/
 *
 * @param pFrom : from field that will appear in the email header.
 * @param personalName :
 * @see {@link InternetAddress}
 * @param pTo : the email target destination.
 * @param pSubject : the subject of the email.
 * @param pMessage : the message or payload of the email.
 */
private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage,
        boolean htmlFormat) throws NotificationServerException {
    // retrieves system properties and set up Delivery Status Notification
    // @see RFC1891
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", getMailServer());
    properties.put("mail.smtp.auth", String.valueOf(isAuthenticated()));
    javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
    session.setDebug(isDebug()); // print on the console all SMTP messages.
    Transport transport = null;
    try {
        InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName);
        InternetAddress replyToAddress = null;
        InternetAddress[] toAddress = null;
        // parsing destination address for compliance with RFC822
        try {
            toAddress = InternetAddress.parse(pTo, false);
            if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom)
                    && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) {
                replyToAddress = new InternetAddress(pFrom, false);
                if (StringUtil.isDefined(personalName)) {
                    replyToAddress.setPersonal(personalName, CharEncoding.UTF_8);
                }
            }
        } catch (AddressException e) {
            SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "From = " + pFrom + ", To = " + pTo);
        }
        MimeMessage email = new MimeMessage(session);
        email.setFrom(fromAddress);
        if (replyToAddress != null) {
            email.setReplyTo(new InternetAddress[] { replyToAddress });
        }
        email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress);
        email.setHeader("Precedence", "list");
        email.setHeader("List-ID", fromAddress.getAddress());
        String subject = pSubject;
        if (subject == null) {
            subject = "";
        }
        String content = pMessage;
        if (content == null) {
            content = "";
        }
        email.setSubject(subject, CharEncoding.UTF_8);
        if (content.toLowerCase().contains("<html>") || htmlFormat) {
            email.setContent(content, "text/html; charset=\"UTF-8\"");
        } else {
            email.setText(content, CharEncoding.UTF_8);
        }
        email.setSentDate(new Date());

        // create a Transport connection (TCP)
        if (isSecure()) {
            transport = session.getTransport(SECURE_TRANSPORT);
        } else {
            transport = session.getTransport(SIMPLE_TRANSPORT);
        }
        if (isAuthenticated()) {
            SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin());
            transport.connect(getMailServer(), getPort(), getLogin(), getPassword());
        } else {
            transport.connect();
        }

        transport.sendMessage(email, toAddress);
    } catch (MessagingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (Exception e) {
        throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR,
                "smtp.EX_CANT_SEND_SMTP_MESSAGE", e);
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (Exception e) {
                SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e);
            }
        }
    }
}

From source file:pt.webdetails.cdv.notifications.EmailOutlet.java

private void applyMessageHeaders(final MimeMessage msg, Alert alert) throws MessagingException {
    String from = getSetting("from"), to = getSetting("to"), cc = getSetting("cc"), bcc = getSetting("bcc"),
            subject = getSubject(alert);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

    if ((cc != null) && (cc.trim().length() > 0)) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
    }//from   www.  java  2 s.c o m
    if ((bcc != null) && (bcc.trim().length() > 0)) {
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
    }

    if (subject != null) {
        msg.setSubject(subject, CharsetHelper.getEncoding());

    }

}

From source file:com.cosmicpush.plugins.smtp.EmailMessage.java

/**
 * @param session the applications current session.
 * @throws EmailMessageException in response to any other type of exception.
 *///  ww  w .  jav a  2  s  . c  o m
@SuppressWarnings({ "ConstantConditions" })
protected void send(Session session) throws EmailMessageException {
    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        //set some of the basic attributes.
        msg.setFrom(fromAddress);
        msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses));
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        if (replyToAddress.isEmpty() == false) {
            msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress));
        }

        // create the Multipart and add set it as the content of the message
        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // create and fill the HTML part of the messgae if it exists
        if (html != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(html, "UTF-8", "html");
            multipart.addBodyPart(bodyPart);
        }

        // create and fill the text part of the messgae if it exists
        if (text != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(text, "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        if (html == null && text == null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText("", "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        // remove any nulls from the list of attachments.
        while (attachments.remove(null)) {
            /* keep going */ }

        // Attach any files that we have, making sure that they exist first
        for (File file : attachments) {
            if (file.exists() == false) {
                throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist.");
            } else {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(file);
                multipart.addBodyPart(attachmentPart);
            }
        }

        // send the message
        Transport.send(msg);

    } catch (EmailMessageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new EmailMessageException("Exception sending email\n" + toString(), ex);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.utils.MailUtil.java

public void sendMessage(String messageText, String subject, String from, String to, List<String> deliverToArray)
        throws IOException {

    Session s = FreemarkerEmailFactory.getEmailSession(req);

    try {//from  w w w.j  a va 2s.  c  o  m

        int recipientCount = (deliverToArray == null) ? 0 : deliverToArray.size();
        if (recipientCount == 0) {
            log.error("To establish the Contact Us mail capability the system administrators must  "
                    + "specify at least one email address in the current portal.");
        }

        MimeMessage msg = new MimeMessage(s);
        // Set the from address
        msg.setFrom(new InternetAddress(from));

        // Set the recipient address

        if (recipientCount > 0) {
            InternetAddress[] address = new InternetAddress[recipientCount];
            for (int i = 0; i < recipientCount; i++) {
                address[i] = new InternetAddress(deliverToArray.get(i));
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        }

        // Set the subject and text
        msg.setSubject(subject);

        // add the multipart to the message
        msg.setContent(messageText, "text/html");

        // set the Date: header
        msg.setSentDate(new Date());
        Transport.send(msg); // try to send the message via smtp - catch error exceptions
    } catch (Exception ex) {
        log.error("Exception sending message :" + ex.getMessage(), ex);
    }
}

From source file:au.org.paperminer.main.UserFilter.java

/**
 * Sends an email to the user asking they follow a link to validate their email address
 * @param id DB key to be embedded in response link
 * @param email Address target/* ww w .  j  a  v a 2 s.co m*/
 */
private void sendVerificationEmail(String id, String email, ServletRequest req) {
    m_logger.debug("sending mail");
    String from = "admin@" + m_serverName;
    Properties props = new Properties();
    props.put("mail.smpt.host", m_serverName);
    props.put("mail.from", from);
    Session session = Session.getInstance(props, null);
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setRecipients(Message.RecipientType.TO, email);
        msg.setSubject("Verify your PaperMiner email address");
        msg.setSentDate(new Date());
        // FIXME: the verify address needs to be more robust
        msg.setText("Dear " + email.substring(0, email.indexOf("@")) + ",\n\n"
                + "PaperMiner has sent you this message to validate that the email address which you "
                + "supplied is able to receive notifications from our server.\n"
                + "To complete the verification process, please click the link below.\n\n" + "http://"
                + m_serverName + ":8080/PaperMiner/pm/vfy?id=" + id + "\n\n"
                + "If you are unable to click the link above, verification can be completed by copying "
                + "and pasting it into the address bar of your web browser.\n\n" + "Your email address is "
                + email + ". Use this to log in when returning to the PaperMiner site.\n"
                + "You can update your email address, or change your TROVE API key at any time through the "
                + "\"Manage Your Details\" option of the User menu, but an email change will require re-validation.\n\n"
                + "Paper Miner Administrator");
        Transport.send(msg);
        m_logger.info("Verifcation mail sent to " + email);
    } catch (MessagingException ex) {
        m_logger.error("Email verification to " + email + " failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e109");
    }
}

From source file:org.apache.james.protocols.smtp.AbstractStartTlsSMTPServerTest.java

@Test
public void testStartTLSWithJavamail() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/*from   ww  w  .ja  v a 2s.  co m*/
    try {
        TestMessageHook hook = new TestMessageHook();
        server = createServer(createProtocol(hook), address,
                Encryption.createStartTls(BogusSslContextFactory.getServerContext()));
        server.bind();

        Properties mailProps = new Properties();
        mailProps.put("mail.smtp.from", "test@localhost");
        mailProps.put("mail.smtp.host", address.getHostName());
        mailProps.put("mail.smtp.port", address.getPort());
        mailProps.put("mail.smtp.socketFactory.class", BogusSSLSocketFactory.class.getName());
        mailProps.put("mail.smtp.socketFactory.fallback", "false");
        mailProps.put("mail.smtp.starttls.enable", "true");

        Session mailSession = Session.getDefaultInstance(mailProps);

        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress("test@localhost"));
        String[] emails = { "valid@localhost" };
        Address rcpts[] = new Address[emails.length];
        for (int i = 0; i < emails.length; i++) {
            rcpts[i] = new InternetAddress(emails[i].trim().toLowerCase());
        }
        message.setRecipients(Message.RecipientType.TO, rcpts);
        message.setSubject("Testmail", "UTF-8");
        message.setText("Test.....");

        SMTPTransport transport = (SMTPTransport) mailSession.getTransport("smtps");

        transport.connect(new Socket(address.getHostName(), address.getPort()));
        transport.sendMessage(message, rcpts);

        assertEquals(1, hook.getQueued().size());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}