Example usage for javax.mail.internet MimeMultipart MimeMultipart

List of usage examples for javax.mail.internet MimeMultipart MimeMultipart

Introduction

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

Prototype

public MimeMultipart() 

Source Link

Document

Default constructor.

Usage

From source file:org.apache.camel.component.mail.MailBinding.java

private MimeMultipart createMixedMultipartAttachments(MailConfiguration configuration, Exchange exchange)
        throws MessagingException, IOException {

    // fill the body with text
    MimeMultipart multipart = new MimeMultipart();
    multipart.setSubType("mixed");
    addBodyToMultipart(configuration, multipart, exchange);
    String partDisposition = configuration.isUseInlineAttachments() ? Part.INLINE : Part.ATTACHMENT;
    if (exchange.getIn().hasAttachments()) {
        addAttachmentsToMultipart(multipart, partDisposition, exchange);
    }/*from w ww  .  j  a  v  a  2  s  . c o  m*/
    return multipart;
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send a calendar message./* w  w  w.  j  av a  2  s  .  c o  m*/
 * @param strRecipientsTo The list of the main recipients email. Every
 *            recipient must be separated by the mail separator defined in
 *            config.properties
 * @param strRecipientsCc The recipients list of the carbon copies .
 * @param strRecipientsBcc The recipients list of the blind carbon copies .
 * @param strSenderName The sender name.
 * @param strSenderEmail The sender email address.
 * @param strSubject The message subject.
 * @param strMessage The HTML message.
 * @param strCalendarMessage The calendar message.
 * @param bCreateEvent True to create the event, false to remove it
 * @param transport the smtp transport object
 * @param session the smtp session object
 * @throws AddressException If invalid address
 * @throws SendFailedException If an error occurred during sending
 * @throws MessagingException If a messaging error occurred
 */
protected static void sendMessageCalendar(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, String strCalendarMessage, boolean bCreateEvent, Transport transport,
        Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    MimeMultipart multipart = new MimeMultipart();
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));

    multipart.addBodyPart(msgBodyPart);

    BodyPart calendarBodyPart = new MimeBodyPart();
    //        calendarBodyPart.addHeader( "Content-Class", "urn:content-classes:calendarmessage" );
    calendarBodyPart.setContent(strCalendarMessage,
            AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_CALENDAR)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET)
                    + AppPropertiesService.getProperty(PROPERTY_CALENDAR_SEPARATOR)
                    + AppPropertiesService.getProperty(
                            bCreateEvent ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL));
    calendarBodyPart.addHeader(HEADER_NAME, CONSTANT_BASE64);
    multipart.addBodyPart(calendarBodyPart);

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

From source file:checkwebsite.Mainframe.java

/**
 *
 * @param email/*  w ww  .java  2s .  c o  m*/
 * @param msg
 */
protected void notify(String email, String msg) {
    // Recipient's email ID needs to be mentioned.
    String to = email;//change accordingly

    // go to link below and turn on Access for less secure apps
    //https://www.google.com/settings/security/lesssecureapps
    // Sender's email ID needs to be mentioned
    String from = "";//Enter your email id here
    final String username = "";//Enter your email id here
    final String password = "";//Enter your password here

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Report of your website : " + wurl);

        //            // Now set the actual message
        //            message.setText("Hello, " + msg + " this is sample for to check send "
        //                    + "email using JavaMailAPI ");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setText("Please! find your website report in attachment");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "WebsiteReport.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);
        lblWarning.setText("report sent...");
        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:nl.nn.adapterframework.senders.MailSender.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection recipients, Collection attachments)
        throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }//from  w  ww.  j  a v a2  s . c  o  m
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url ["
                        + attachmentUrl + "]contents [" + attachmentText + "]");

                messageBodyPart = new MimeBodyPart();

                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }

                messageBodyPart.setFileName(attachmentName);

                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "")
@APIParam(params = { "url", "function(data)" })
public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings)
        throws AddressException, MessagingException {

    if (emailSettings == null) {
        return;//from www . j  a  v  a2 s  .c  om
    }

    // final String host = "smtp.gmail.com";
    // final String address = "@gmail.com";
    // final String pass = "";

    Multipart multiPart;
    String finalString = "";

    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", emailSettings.ttl);
    props.put("mail.smtp.host", emailSettings.host);
    props.put("mail.smtp.user", emailSettings.user);
    props.put("mail.smtp.password", emailSettings.password);
    props.put("mail.smtp.port", emailSettings.port);
    props.put("mail.smtp.auth", emailSettings.auth);

    Log.i("Check", "done pops");
    final Session session = Session.getDefaultInstance(props, null);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
    final MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setDataHandler(handler);
    Log.i("Check", "done sessions");

    multiPart = new MimeMultipart();

    InternetAddress toAddress;
    toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Log.i("Check", "added recipient");
    message.setSubject(subject);
    message.setContent(multiPart);
    message.setText(text);

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                MLog.i("check", "transport");
                Transport transport = session.getTransport("smtp");
                MLog.i("check", "connecting");
                transport.connect(emailSettings.host, emailSettings.user, emailSettings.password);
                MLog.i("check", "wana send");
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

                MLog.i("check", "sent");

            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }
    });
    t.start();

}

From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java

private void sendEmail(boolean test, AmazonSimpleEmailServiceClient emailService, String email,
        List<ApplicationGroup> appGroups) throws IOException, MessagingException {

    StringBuilder body = new StringBuilder();
    body.append(//from w ww .jav  a  2 s.c om
            "<html><head><style type=\"text/css\">a:link, a:visited{color:#006DBA;}a:link, a:visited, a:hover {\n"
                    + "text-decoration: none;\n" + "}\n" + "body {\n" + "color: #333;\n" + "}"
                    + "</style></head>");
    List<MimeBodyPart> mimeBodyParts = Lists.newArrayList();
    int index = 0;
    String subject = "";
    for (ApplicationGroup appGroup : appGroups) {
        boolean hasData = false;
        for (String prodName : appGroup.data.keySet()) {
            if (config.productService.getProductByName(prodName) == null)
                continue;
            hasData = appGroup.data.get(prodName) != null && appGroup.data.get(prodName).size() > 0;
            if (hasData)
                break;
        }
        if (!hasData)
            continue;

        try {
            MimeBodyPart mimeBodyPart = constructEmail(index, appGroup, body);
            index++;
            if (mimeBodyPart != null) {
                mimeBodyParts.add(mimeBodyPart);
                subject = subject + (subject.length() > 0 ? ", " : "") + appGroup.getDisplayName();
            }
        } catch (Exception e) {
            logger.error("Error contructing email", e);
        }
    }
    body.append("</html>");

    if (mimeBodyParts.size() == 0)
        return;

    DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
    subject = String.format("%s Weekly AWS Costs (%s - %s)", subject, formatter.print(end.minusWeeks(1)),
            formatter.print(end));
    String toEmail = test ? testEmail : email;
    Session session = Session.getInstance(new Properties());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, toEmail);
    if (!test && !StringUtils.isEmpty(bccEmail)) {
        mimeMessage.addRecipients(Message.RecipientType.BCC, bccEmail);
    }
    MimeMultipart mimeMultipart = new MimeMultipart();
    BodyPart p = new MimeBodyPart();
    p.setContent(body.toString(), "text/html");
    mimeMultipart.addBodyPart(p);

    for (MimeBodyPart mimeBodyPart : mimeBodyParts)
        mimeMultipart.addBodyPart(mimeBodyPart);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    mimeMessage.setContent(mimeMultipart);
    mimeMessage.writeTo(outputStream);
    RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));

    SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
    rawEmailRequest.setDestinations(Lists.<String>newArrayList(toEmail));
    rawEmailRequest.setSource(fromEmail);
    logger.info("sending email to " + toEmail + " " + body.toString());
    emailService.sendRawEmail(rawEmailRequest);
}

From source file:com.emc.kibana.emailer.KibanaEmailer.java

private static void sendFileEmail(String security) {

    final String username = smtpUsername;
    final String password = smtpPassword;

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);

    if (security.equals(SMTP_SECURITY_TLS)) {
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.port", smtpPort);
    } else if (security.equals(SMTP_SECURITY_SSL)) {
        properties.put("mail.smtp.socketFactory.port", smtpPort);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", smtpPort);
    }//from www.j av  a2s .  c  om

    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(sourceAddress));

        // Set To: header field of the header.
        for (String destinationAddress : destinationAddressList) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress));
        }

        // Set Subject: header field
        message.setSubject(mailTitle);

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        StringBuffer bodyBuffer = new StringBuffer(mailBody);
        if (!kibanaUrls.isEmpty()) {
            bodyBuffer.append("\n\n");
        }

        // Add urls info to e-mail
        for (Map<String, String> kibanaUrl : kibanaUrls) {
            // Add urls to e-mail
            String urlName = kibanaUrl.get(NAME_KEY);
            String reportUrl = kibanaUrl.get(URL_KEY);
            if (urlName != null && reportUrl != null) {
                bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n");
            }
        }

        // Fill the message
        messageBodyPart.setText(bodyBuffer.toString());

        // Create a multipart message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachments
        for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) {
            messageBodyPart = new MimeBodyPart();
            String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY);
            String filename = kibanaScreenCapture.get(FILE_NAME_KEY);
            DataSource source = new FileDataSource(absoluteFilename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);
        }

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);
        logger.info("Sent mail message successfully");
    } catch (MessagingException mex) {
        throw new RuntimeException(mex);
    }
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

protected Message createMessage(String personalName, String sender, Address[] to, Address[] cc, Address[] bcc,
        String subject, String body, List<MailFile> mailFiles)
        throws MessagingException, UnsupportedEncodingException {

    Message jxMessage = new MimeMessage(_imapConnection.getSession());

    jxMessage.setFrom(new InternetAddress(sender, personalName));
    jxMessage.addRecipients(Message.RecipientType.TO, to);
    jxMessage.addRecipients(Message.RecipientType.CC, cc);
    jxMessage.addRecipients(Message.RecipientType.BCC, bcc);
    jxMessage.setSentDate(new Date());
    jxMessage.setSubject(subject);// w ww.j  av  a  2s  .co  m

    MimeMultipart multipart = new MimeMultipart();

    BodyPart messageBodyPart = new MimeBodyPart();

    messageBodyPart.setContent(body, ContentTypes.TEXT_HTML_UTF8);

    multipart.addBodyPart(messageBodyPart);

    if (mailFiles != null) {
        for (MailFile mailFile : mailFiles) {
            File file = mailFile.getFile();

            if (!file.exists()) {
                continue;
            }

            DataSource dataSource = new FileDataSource(file);

            BodyPart attachmentBodyPart = new MimeBodyPart();

            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(mailFile.getFileName());

            multipart.addBodyPart(attachmentBodyPart);
        }
    }

    jxMessage.setContent(multipart);

    return jxMessage;
}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private MimeMessage prepareMessageWithAttachment(String scriptContent, String subject)
        throws MessagingException, IOException {
    MimeMessage message = prepareMimeMessage(subject);
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(//from ww w .j  a  v a  2  s.c om
            new DataHandler(new ByteArrayDataSource(scriptContent, "application/sieve; charset=UTF-8")));
    scriptPart.setDisposition(MimeBodyPart.ATTACHMENT);
    // setting a DataHandler with no mailcap definition is not
    // supported by the specs. Javamail activation still work,
    // but Geronimo activation translate it to text/plain.
    // Let's manually force the header.
    scriptPart.setHeader("Content-Type", "application/sieve; charset=UTF-8");
    scriptPart.setFileName(SCRIPT_NAME);
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    return message;
}

From source file:org.sakaiproject.tool.mailtool.Mailtool.java

public String processSendEmail() {
    /* EmailUser */ selected = m_recipientSelector.getSelectedUsers();
    if (m_selectByTree) {
        selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers();
        selectedGroupUsers = m_recipientSelector2.getSelectedUsers();
        selectedSectionUsers = m_recipientSelector3.getSelectedUsers();

        selected.addAll(selectedGroupAwareRoleUsers);
        selected.addAll(selectedGroupUsers);
        selected.addAll(selectedSectionUsers);
    }/*from  w  w  w .  j  a  v  a  2 s . c  o m*/
    // Put everyone in a set so the same person doesn't get multiple emails.
    Set emailusers = new TreeSet();
    if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future 
        for (Iterator i = getEmailGroups().iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            emailusers.addAll(group.getEmailusers());
        }
    }
    if (isAllGroupSelected()) {
        for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("section")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    if (isAllSectionSelected()) {
        for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("group")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    if (isAllGroupAwareRoleSelected()) {
        for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("role_groupaware")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    emailusers = new TreeSet(selected); // convert List to Set (remove duplicates)

    m_subjectprefix = getSubjectPrefixFromConfig();

    EmailUser curUser = getCurrentUser();

    String fromEmail = "";
    String fromDisplay = "";
    if (curUser != null) {
        fromEmail = curUser.getEmail();
        fromDisplay = curUser.getDisplayname();
    }
    String fromString = fromDisplay + " <" + fromEmail + ">";

    m_results = "Message sent to: <br>";

    String subject = m_subject;

    //Should we append this to the archive?
    String emailarchive = "/mailarchive/channel/" + m_siteid + "/main";
    if (m_archiveMessage && isEmailArchiveInSite()) {
        String attachment_info = "<br/>";
        Attachment a = null;
        Iterator iter = attachedFiles.iterator();
        int i = 0;
        while (iter.hasNext()) {
            a = (Attachment) iter.next();
            attachment_info += "<br/>";
            attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize()
                    + " Bytes)";
            i++;
        }
        this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info);
    }
    List headers = new ArrayList();
    if (getTextFormat().equals("htmltext"))
        headers.add("content-type: text/html");
    else
        headers.add("content-type: text/plain");

    String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
    //String smtp_port = ServerConfigurationService.getString("smtp.port");
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", smtp_server);
        //props.put("mail.smtp.port", smtp_port);
        Session s = Session.getInstance(props, null);

        MimeMessage message = new MimeMessage(s);

        InternetAddress from = new InternetAddress(fromString);
        message.setFrom(from);
        String reply = getReplyToSelected().trim().toLowerCase();
        if (reply.equals("yes")) {
            // "reply to sender" is default. So do nothing
        } else if (reply.equals("no")) {
            String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">";
            InternetAddress noreplyemail = new InternetAddress(noreply);
            message.setFrom(noreplyemail);
        } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) {
            // need input(email) validation
            InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) };
            message.setReplyTo(replytoList);
        }
        message.setSubject(subject);
        String text = m_body;
        String attachmentdirectory = getUploadDirectory();

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        String messagetype = "";

        if (getTextFormat().equals("htmltext")) {
            messagetype = "text/html";
        } else {
            messagetype = "text/plain";
        }
        messageBodyPart.setContent(text, messagetype);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        Attachment a = null;
        Iterator iter = attachedFiles.iterator();
        while (iter.hasNext()) {
            a = (Attachment) iter.next();
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(
                    attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename());
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(a.getFilename());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);

        //Send the emails
        String recipientsString = "";
        for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") {
            EmailUser euser = (EmailUser) i.next();
            String toEmail = euser.getEmail(); // u.getEmail();
            String toDisplay = euser.getDisplayname(); // u.getDisplayName();
            // if AllUsers are selected, do not add current user's email to recipients
            if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) {
                // don't add sender to recipients
            } else {
                recipientsString += toEmail;
                m_results += toDisplay + (i.hasNext() ? "<br/>" : "");
            }
            //               InternetAddress to[] = {new InternetAddress(toEmail) };
            //               Transport.send(message,to);
        }
        if (m_otheremails.trim().equals("") != true) {
            //
            // multiple email validation is needed here
            //
            String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ',');
            recipientsString += refinedOtherEmailAddresses;
            m_results += "<br/>" + refinedOtherEmailAddresses;
            //               InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) };
            //               Transport.send(message, to);
        }
        if (m_sendmecopy) {
            message.addRecipients(Message.RecipientType.CC, fromEmail);
            // trying to solve SAK-7410
            // recipientsString+=fromEmail;
            //               InternetAddress to[] = {new InternetAddress(fromEmail) };
            //               Transport.send(message, to);
        }
        //            message.addRecipients(Message.RecipientType.TO, recipientsString);
        message.addRecipients(Message.RecipientType.BCC, recipientsString);

        Transport.send(message);
    } catch (Exception e) {
        log.debug("Mailtool Exception while trying to send the email: " + e.getMessage());
    }

    //   Clear the Subject and Body of the Message
    m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix();
    m_otheremails = "";
    m_body = "";
    num_files = 0;
    attachedFiles.clear();
    m_recipientSelector = null;
    m_recipientSelector1 = null;
    m_recipientSelector2 = null;
    m_recipientSelector3 = null;
    setAllUsersSelected(false);
    setAllGroupSelected(false);
    setAllSectionSelected(false);

    //  Display Users with Bad Emails if the option is turned on.
    boolean showBadEmails = getDisplayInvalidEmailAddr();
    if (showBadEmails == true) {
        m_results += "<br/><br/>";

        List /* String */ badnames = new ArrayList();

        for (Iterator i = selected.iterator(); i.hasNext();) {
            EmailUser user = (EmailUser) i.next();
            /* This check should maybe be some sort of regular expression */
            if (user.getEmail().equals("")) {
                badnames.add(user.getDisplayname());
            }
        }
        if (badnames.size() > 0) {
            m_results += "The following users do not have valid email addresses:<br/>";
            for (Iterator i = badnames.iterator(); i.hasNext();) {
                String name = (String) i.next();
                if (i.hasNext() == true)
                    m_results += name + "/ ";
                else
                    m_results += name;
            }
        }
    }
    return "results";
}