Example usage for javax.mail.internet MimeMessage setFrom

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

Introduction

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

Prototype

public void setFrom(String address) throws MessagingException 

Source Link

Document

Set the RFC 822 "From" header field.

Usage

From source file:nl.surfnet.coin.teams.control.DetailTeamController.java

/**
 * Notifies the user that requested to join a team that his request has been
 * declined// w w w  . ja  v  a2 s  . c om
 *
 * @param memberToAdd {@link Person} that wanted to join the team
 * @param team        {@link Team} he wanted to join
 * @param locale      {@link Locale}
 */
private void sendAcceptMail(final Person memberToAdd, final Team team, final Locale locale) {
    final String subject = messageSource.getMessage("request.mail.accepted.subject", null, locale);
    final String html = composeAcceptMailMessage(team, locale, "html");
    final String plainText = composeAcceptMailMessage(team, locale, "plaintext");

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");

            mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail()));
            mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails()));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);
}

From source file:it.infn.ct.downtime.Downtime.java

private void sendHTMLEmail(String TO, String FROM, String SMTP_HOST, File file) {

    String[] downtime_text = new String[4];

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

    // Get the default Session object.
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    try {//  ww  w. j a va 2 s.co  m
        //Get Document Builder
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        //Build Document
        Document document = builder.parse(file);

        //Normalize the XML Structure; It's just too important !!
        document.getDocumentElement().normalize();

        //Here comes the root node
        Element root = document.getDocumentElement();
        NodeList List = document.getElementsByTagName("DOWNTIME");

        for (int i = 0; i < List.getLength(); i++) {
            Node node = List.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) node;

                // Downtime period
                downtime_text[0] = "SCHEDULED Downtime period <br/>";
                downtime_text[0] += "Start of downtime \t[UCT]: "
                        + eElement.getElementsByTagName("FORMATED_START_DATE").item(0).getTextContent()
                        + "<br/>";
                downtime_text[0] += "End  of downtime \t[UCT]: "
                        + eElement.getElementsByTagName("FORMATED_END_DATE").item(0).getTextContent()
                        + "<br/><br/>";

                // Entities in downtime
                downtime_text[1] = "<b><u>Entities in downtime:</u></b><br/>";
                downtime_text[1] += "Server Host: "
                        + eElement.getElementsByTagName("HOSTED_BY").item(0).getTextContent() + "<br/><br/>";
                for (int k = 0; k < eElement.getElementsByTagName("SERVICE").getLength(); k++) {
                    downtime_text[1] += "Nodes: "
                            + eElement.getElementsByTagName("HOSTNAME").item(k).getTextContent() + "<br/>";
                    downtime_text[1] += "Service Type: "
                            + eElement.getElementsByTagName("SERVICE_TYPE").item(k).getTextContent() + "<br/>";
                    downtime_text[1] += "Hosted service(s): "
                            + eElement.getElementsByTagName("HOSTNAME").item(k).getTextContent() + "<br/><br/>";
                }

                // Description
                downtime_text[2] = "<b><u>Description:</u></b><br/>";
                downtime_text[2] += eElement.getElementsByTagName("DESCRIPTION").item(0).getTextContent()
                        + "<br/>";
                downtime_text[2] += "More details are available in this <a href="
                        + eElement.getElementsByTagName("GOCDB_PORTAL_URL").item(0).getTextContent()
                        + "> link</a>" + "<br/><br/>";

                // Severity
                downtime_text[3] = "<b><u>Severity:</u></b> ";
                downtime_text[3] += eElement.getElementsByTagName("SEVERITY").item(0).getTextContent()
                        + "<br/><br/>";

                // Sending notification                
                // Create a default MimeMessage object.
                javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);

                // Set From: header field of the header.
                message.setFrom(new javax.mail.internet.InternetAddress(FROM));

                // Set To: header field of the header.
                message.addRecipient(javax.mail.Message.RecipientType.TO,
                        new javax.mail.internet.InternetAddress(TO));
                //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

                // Set Subject: header field
                message.setSubject(" [EGI DOWNTIME] ANNOUNCEMENT ");

                Date currentDate = new Date();
                currentDate.setTime(currentDate.getTime());

                // Send the actual HTML message, as big as you like
                message.setContent("<br/><H4>"
                        + "<img src=\"http://scilla.man.poznan.pl:8080/confluence/download/attachments/5505438/egi_logo.png\" width=\"100\">"
                        + "</H4>" + "Long Tail of Science (LToS) services in downtime<br/><br/>"
                        + downtime_text[0] + downtime_text[1] + downtime_text[2] + downtime_text[3]
                        + "<b><u>TimeStamp:</u></b><br/>" + currentDate + "<br/><br/>"
                        + "<b><u>Disclaimer:</u></b><br/>"
                        + "<i>This is an automatic message sent by the LToS Science Gateway based on Liferay technology."
                        + "<br/><br/>", "text/html");

                // Send notification to the user
                javax.mail.Transport.send(message);
            }
        }
    } catch (MessagingException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.harvard.iq.dataverse.MailServiceBean.java

public void sendMail(String host, String from, String to, String subject, String messageText) {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(props, null);

    try {/*w  w  w  .  ja  v a2  s .c  o  m*/
        MimeMessage msg = new MimeMessage(session);
        String[] recipientStrings = to.split(",");
        InternetAddress[] recipients = new InternetAddress[recipientStrings.length];
        try {
            msg.setFrom(new InternetAddress(from, charset));
            for (int i = 0; i < recipients.length; i++) {
                recipients[i] = new InternetAddress(recipientStrings[i], "", charset);
            }
        } catch (UnsupportedEncodingException ex) {
            logger.severe(ex.getMessage());
        }
        msg.setRecipients(Message.RecipientType.TO, recipients);
        msg.setSubject(subject, charset);
        msg.setText(messageText, charset);
        Transport.send(msg, recipients);
    } catch (AddressException ae) {
        ae.printStackTrace(System.out);
    } catch (MessagingException me) {
        me.printStackTrace(System.out);
    }
}

From source file:org.exoplatform.chat.server.ChatServer.java

public void sendMailWithAuth(String senderFullname, List<String> toList, String htmlBody, String subject)
        throws Exception {

    String host = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_HOST);
    String user = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_USER);
    String password = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PASSWORD);
    String port = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PORT);

    Properties props = System.getProperties();

    props.put("mail.smtp.user", user);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    //props.put("mail.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.EnableSSL.enable", "true");

    Session session = Session.getInstance(props, null);
    //session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(user, senderFullname));

    // To get the array of addresses
    for (String to : toList) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    }/*from w w w.j  ava  2 s  . co m*/

    message.setSubject(subject);
    message.setContent(htmlBody, "text/html");

    Transport transport = session.getTransport("smtp");
    try {
        transport.connect(host, user, password);
        transport.sendMessage(message, message.getAllRecipients());
    } finally {
        transport.close();
    }
}

From source file:it.infn.ct.chipster.Chipster.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String user_emailAddress, String credential, String chipster_HOST) {

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- User's email = " + user_emailAddress);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);
    properties.setProperty("mail.debug", "true");

    //properties.setProperty("mail.smtp.auth", "false");        

    // Get the default Session object.
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    try {//ww w.  jav  a2 s  .  c  o  m
        // Create a default MimeMessage object.
        javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new javax.mail.internet.InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(javax.mail.Message.RecipientType.TO, new javax.mail.internet.InternetAddress(TO));
        message.addRecipient(javax.mail.Message.RecipientType.CC,
                new javax.mail.internet.InternetAddress(user_emailAddress));
        //new javax.mail.internet.InternetAddress("glarocca75@gmail.com")); // <== Change here!

        // Set Subject: header field
        message.setSubject(" Chipster Account Generator service notification ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://scilla.man.poznan.pl:8080/confluence/download/attachments/5505438/egi_logo.png\" width=\"100\">"
                + "</H4><hr><br/>" + "<b>Description:</b> " + ApplicationAcronym
                + " notification service <br/><br/>"
                + "<i>A request to create a new temporary chipster account has been successfully sent from the LToS Science Gateway</i><br/><br/>"
                + "<b>Chipster Front Node:</b> " + chipster_HOST + "<br/>" + "<b>Credentials:</b> " + credential
                + "<br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>" + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Catania Science Gateway (CSG) tailored for the EGI Long of Tail Science.<br/><br/>",
                "text/html");

        // Send message
        javax.mail.Transport.send(message);
    } catch (javax.mail.MessagingException ex) {
        Logger.getLogger(Chipster.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.xwiki.commons.internal.DefaultMailSender.java

@Override
public int send(Mail mail) {
    Session session = null;/*from www  .ja  v  a2s . c o m*/
    Transport transport = null;
    if ((mail.getTo() == null || StringUtils.isEmpty(mail.getTo()))
            && (mail.getCc() == null || StringUtils.isEmpty(mail.getCc()))
            && (mail.getBcc() == null || StringUtils.isEmpty(mail.getBcc()))) {
        logger.error("This mail has no recipient");
        return 0;
    }
    if (mail.getContents().size() == 0) {
        logger.error("This mail is empty. You should add a content");
        return 0;
    }
    try {
        if ((transport == null) || (session == null)) {
            logger.info("Sending mail : Initializing properties");
            Properties props = initProperties();
            session = Session.getInstance(props, null);
            transport = session.getTransport("smtp");
            if (session.getProperty("mail.smtp.auth") == "true")
                transport.connect(session.getProperty("mail.smtp.server.username"),
                        session.getProperty("mail.smtp.server.password"));
            else
                transport.connect();
            try {
                Multipart wrapper = generateMimeMultipart(mail);
                InternetAddress[] adressesTo = this.toInternetAddresses(mail.getTo());
                MimeMessage message = new MimeMessage(session);
                message.setSentDate(new Date());
                message.setSubject(mail.getSubject());
                message.setFrom(new InternetAddress(mail.getFrom()));
                message.setRecipients(javax.mail.Message.RecipientType.TO, adressesTo);
                if (mail.getReplyTo() != null && !StringUtils.isEmpty(mail.getReplyTo())) {
                    logger.info("Adding ReplyTo field");
                    InternetAddress[] adressesReplyTo = this.toInternetAddresses(mail.getReplyTo());
                    if (adressesReplyTo.length != 0)
                        message.setReplyTo(adressesReplyTo);
                }
                if (mail.getCc() != null && !StringUtils.isEmpty(mail.getCc())) {
                    logger.info("Adding Cc recipients");
                    InternetAddress[] adressesCc = this.toInternetAddresses(mail.getCc());
                    if (adressesCc.length != 0)
                        message.setRecipients(javax.mail.Message.RecipientType.CC, adressesCc);
                }
                if (mail.getBcc() != null && !StringUtils.isEmpty(mail.getBcc())) {
                    InternetAddress[] adressesBcc = this.toInternetAddresses(mail.getBcc());
                    if (adressesBcc.length != 0)
                        message.setRecipients(javax.mail.Message.RecipientType.BCC, adressesBcc);
                }
                message.setContent(wrapper);
                message.setSentDate(new Date());
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            } catch (SendFailedException sfex) {
                logger.error("Error encountered while trying to send the mail");
                logger.error("SendFailedException has occured.", sfex);
                try {
                    transport.close();
                } catch (MessagingException Mex) {
                    logger.error("MessagingException has occured.", Mex);
                }
                return 0;
            } catch (MessagingException mex) {
                logger.error("Error encountered while trying to send the mail");
                logger.error("MessagingException has occured.", mex);

                try {
                    transport.close();
                } catch (MessagingException ex) {
                    logger.error("MessagingException has occured.", ex);
                }
                return 0;
            }
        }
    } catch (Exception e) {
        System.out.println(e.toString());
        logger.error("Error encountered while trying to setup mail properties");
        try {
            if (transport != null) {
                transport.close();
            }
        } catch (MessagingException ex) {
            logger.error("MessagingException has occured.", ex);
        }
        return 0;
    }

    return 1;
}

From source file:at.molindo.notify.channel.mail.AbstractMailClient.java

@Override
public synchronized void send(Dispatch dispatch) throws MailException {

    Message message = dispatch.getMessage();

    String recipient = dispatch.getParams().get(MailChannel.RECIPIENT);
    String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME);
    String subject = message.getSubject();

    try {// ww w.  ja v a 2 s .com
        MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) {
            @Override
            protected void updateMessageID() throws MessagingException {
                String domain = _from.getAddress();
                int idx = _from.getAddress().indexOf('@');
                if (idx >= 0) {
                    domain = domain.substring(idx + 1);
                }
                setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">");
            }
        };
        mm.setFrom(_from);
        mm.setSender(_from);

        InternetAddress replyTo = getReplyTo();
        if (replyTo != null) {
            mm.setReplyTo(new Address[] { replyTo });
        }
        mm.setHeader("X-Mailer", "molindo-notify");
        mm.setSentDate(new Date());

        mm.setRecipient(RecipientType.TO,
                new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName()));
        mm.setSubject(subject, CharsetUtils.UTF_8.displayName());

        if (_format == Format.HTML) {
            if (message.getType() == Type.TEXT) {
                throw new MailException("can't send HTML mail from TEXT message", false);
            }
            mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");
        } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) {
            mm.setText(message.getText(), CharsetUtils.UTF_8.displayName());
        } else if (_format == Format.MULTI) {
            MimeBodyPart html = new MimeBodyPart();
            html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");

            MimeBodyPart text = new MimeBodyPart();
            text.setText(message.getText(), CharsetUtils.UTF_8.displayName());

            /*
             * The formats are ordered by how faithful they are to the
             * original, with the least faithful first and the most faithful
             * last. (http://en.wikipedia.org/wiki/MIME#Alternative)
             */
            MimeMultipart mmp = new MimeMultipart();
            mmp.setSubType("alternative");

            mmp.addBodyPart(text);
            mmp.addBodyPart(html);

            mm.setContent(mmp);
        } else {
            throw new NotifyRuntimeException(
                    "unexpected format (" + _format + ") or type (" + message.getType() + ")");
        }

        send(mm);

    } catch (final MessagingException e) {
        throw new MailException(
                "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e,
                isTemporary(e));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("utf8 unknown?", e);
    }
}

From source file:com.gtwm.jasperexecute.RunJasperReports.java

public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients,
        String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException {
    Properties props = new Properties();
    //props.setProperty("mail.debug", "true");
    props.setProperty("mail.smtp.host", emailHost);
    if (emailUser != null) {
        props.setProperty("mail.smtp.auth", "true");
    }/*from  ww  w  . j av  a2  s .  co m*/
    Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass);
    Session mailSession = Session.getDefaultInstance(props, emailAuthenticator);
    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");
    // transport.connect(emailHost, emailUser, emailPass);
    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java

public void send(EmailModel model) throws EmailException {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Sending email: " + model);

    if (model == null)
        throw new NullPointerException("model");

    Properties emailProps;/*  w w  w  .ja v a 2s. c  om*/
    Session emailSession;

    // set the relay host as a property of the email session
    emailProps = new Properties();
    emailProps.setProperty("mail.transport.protocol", "smtp");
    emailProps.put("mail.smtp.host", host);
    emailProps.setProperty("mail.smtp.port", String.valueOf(port));
    // set the timeouts
    emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS));
    emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Email properties: " + emailProps);

    // set up email session
    emailSession = Session.getInstance(emailProps, null);
    emailSession.setDebug(false);

    String from;
    String displayFrom;

    String body;
    String subject;
    List<EmailAttachment> attachments;

    if (model.getFrom() == null)
        throw new NullPointerException("from");
    if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc())
            && MiscUtils.isEmpty(model.getCc()))
        throw new IllegalArgumentException("model has no addresses");

    from = model.getFrom();
    displayFrom = model.getDisplayFrom();
    body = model.getBody();
    subject = model.getSubject();
    attachments = model.getAttachments();

    MimeMessage emailMessage;
    InternetAddress emailAddressFrom;

    // create an email message from the current session
    emailMessage = new MimeMessage(emailSession);

    // set the from
    try {
        emailAddressFrom = new InternetAddress(from, displayFrom);
        emailMessage.setFrom(emailAddressFrom);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    if (!MiscUtils.isEmpty(model.getTo()))
        setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO);
    if (!MiscUtils.isEmpty(model.getCc()))
        setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC);
    if (!MiscUtils.isEmpty(model.getBcc()))
        setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC);

    try {

        if (!MiscUtils.isEmpty(subject))
            emailMessage.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (body != null) {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            String bodyContentType;
            //        body = Utils.base64Encode(body);
            bodyContentType = "text/html; charset=UTF-8";

            messageBodyPart.setContent(body, bodyContentType);
            //Content-Transfer-Encoding : base64
            //        messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
            multipart.addBodyPart(messageBodyPart);
        }
        // Part two is attachment
        if (attachments != null && !attachments.isEmpty()) {
            try {
                for (EmailAttachment a : attachments) {
                    MimeBodyPart attachBodyPart = new MimeBodyPart();
                    // don't base 64 encode
                    DataSource source = new StreamDataSource(
                            new DefaultStreamFactory(a.getInputStream(), false), a.getName(),
                            a.getContentType());
                    attachBodyPart.setDataHandler(new DataHandler(source));
                    attachBodyPart.setFileName(a.getName());
                    attachBodyPart.setHeader("Content-Type", a.getContentType());
                    attachBodyPart.addHeader("Content-Transfer-Encoding", "base64");

                    // add the attachment to the message
                    multipart.addBodyPart(attachBodyPart);

                }
            }
            // close all the input streams
            finally {
                for (EmailAttachment a : attachments)
                    MiscUtils.closeStream(a.getInputStream());
            }
        }

        // set the content
        emailMessage.setContent(multipart);
        emailMessage.saveChanges();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email message: " + emailMessage);

        Transport.send(emailMessage);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email complete.");

    } catch (Exception e) {
        throw new EmailException(e);
    }

}

From source file:mitm.common.tools.SendMail.java

private void sendMultiThreaded(final MailTransport mailSender, final MimeMessage message,
        final Address[] recipients) throws InterruptedException {
    ExecutorService threadPool = Executors.newCachedThreadPool();

    final Semaphore semaphore = new Semaphore(threads, true);

    final long startTime = System.currentTimeMillis();

    for (int i = 1; i <= count; i++) {
        long threadStart = System.currentTimeMillis();

        semaphore.acquireUninterruptibly();

        threadPool.execute(new Runnable() {
            @Override/*from  w  ww  .j a  v a  2 s  .  com*/
            public void run() {
                try {
                    MimeMessage clone = MailUtils.cloneMessage(message);

                    int sent = sentCount.incrementAndGet();

                    if (uniqueFrom) {
                        Address[] froms = clone.getFrom();

                        if (froms != null && froms.length > 0) {
                            clone.setFrom(
                                    new InternetAddress(sent + EmailAddressUtils.getEmailAddress(froms[0])));
                        }
                    }

                    mailSender.sendMessage(clone, recipients);

                    long timePassed = DateTimeUtils
                            .millisecondsToSeconds(System.currentTimeMillis() - startTime);

                    StrBuilder sb = new StrBuilder();

                    sb.append("Message\t" + sent + "\tsent.");

                    if (timePassed > 0) {
                        float msgPerSec = (float) sent / timePassed;

                        sb.append("\tmessages/second\t" + String.format("%.2f", msgPerSec));
                    }

                    logger.info(sb.toString());
                } catch (MessagingException e) {
                    logger.error("Error sending message.", e);
                } finally {
                    semaphore.release();
                }
            }
        });

        if (forceQuit.get()) {
            break;
        }

        if (throtllingSemaphore != null) {
            /* for throttling the sending of emails */
            throtllingSemaphore.acquire();
        } else {
            /* no throttling so use delay */
            long sleepTime = delay - (System.currentTimeMillis() - threadStart);

            if (sleepTime > 0) {
                Thread.sleep(sleepTime);
            }
        }
    }

    threadPool.shutdown();
    threadPool.awaitTermination(30, TimeUnit.SECONDS);

    waitForReceiveThreads();

    logger.info("Total sent: " + sentCount.intValue() + ". Total time: "
            + DateTimeUtils.millisecondsToSeconds(System.currentTimeMillis() - startTime) + " (sec.)");
}