Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Multipart mp) throws MessagingException 

Source Link

Document

This method sets the Message's content to a Multipart object.

Usage

From source file:com.sonicle.webtop.core.app.WebTopApp.java

public void sendEmail(javax.mail.Session session, InternetAddress from, Collection<InternetAddress> to,
        Collection<InternetAddress> cc, Collection<InternetAddress> bcc, String subject, MimeMultipart part)
        throws MessagingException {

    try {//from   w  w w  . j a v  a 2  s . c o  m
        subject = MimeUtility.encodeText(subject);
    } catch (Exception ex) {
    }

    MimeMessage message = new MimeMessage(session);
    message.setSubject(subject);
    message.addFrom(new InternetAddress[] { from });

    if (to != null) {
        for (InternetAddress ia : to)
            message.addRecipient(Message.RecipientType.TO, ia);
    }
    if (cc != null) {
        for (InternetAddress ia : cc)
            message.addRecipient(Message.RecipientType.CC, ia);
    }
    if (bcc != null) {
        for (InternetAddress ia : bcc)
            message.addRecipient(Message.RecipientType.BCC, ia);
    }

    message.setContent(part);
    message.setSentDate(new java.util.Date());
    Transport.send(message);
}

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

@Override
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage, RemoteException {

    try {/*from  w w  w.  ja  va  2 s . c om*/
        log.info("Sending notification email to " + notificationEmailAddress + " from "
                + getEMailProperties().getProperty("mail.smtp.from", "jUDDI"));
        if (session != null && notificationEmailAddress != null) {
            MimeMessage message = new MimeMessage(session);
            InternetAddress address = new InternetAddress(notificationEmailAddress);
            Address[] to = { address };
            message.setRecipients(RecipientType.TO, to);
            message.setFrom(new InternetAddress(getEMailProperties().getProperty("mail.smtp.from", "jUDDI")));
            //maybe nice to use a template rather then sending raw xml.
            String subscriptionResultXML = JAXBMarshaller.marshallToString(body,
                    JAXBMarshaller.PACKAGE_SUBSCR_RES);
            Multipart mp = new MimeMultipart();

            MimeBodyPart content = new MimeBodyPart();
            String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.body");

            msg_content = String
                    .format(msg_content, StringEscapeUtils.escapeHtml(this.publisherName),
                            StringEscapeUtils.escapeHtml(AppConfig.getConfiguration()
                                    .getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                            GetSubscriptionType(body), GetChangeSummary(body));

            content.setContent(msg_content, "text/html; charset=UTF-8;");
            mp.addBodyPart(content);

            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
            attachment.setFileName("uddiNotification.xml");
            mp.addBodyPart(attachment);

            message.setContent(mp);
            message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " "
                    + body.getSubscriptionResultsList().getSubscription().getSubscriptionKey());
            Transport.send(message);
        } else {
            throw new DispositionReportFaultMessage("Session is null!", null);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DispositionReportFaultMessage(e.getMessage(), null);
    }

    DispositionReport dr = new DispositionReport();
    Result res = new Result();
    dr.getResult().add(res);

    return dr;
}

From source file:ee.cyber.licensing.service.MailService.java

public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId)
        throws MessagingException, IOException, SQLException {
    License license = licenseRepository.findById(licenseId);
    List<Contact> contacts = contactRepository.findAll(license.getCustomer());
    List<String> receivers = getReceivers(mailbody, contacts);

    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }//ww  w.jav a2 s.c o m
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "License dude"));
    //mailMessage.setReplyTo(InternetAddress.parse(email, false));
    mailMessage.setSubject(mailbody.getSubject());
    //String emailBody = body + "<br><br> Regards, <br>Cybernetica team";
    mailMessage.setSentDate(new Date());

    for (String receiver : receivers) {
        mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
    }

    if (fileId != 0) {
        MailAttachment file = fileRepository.findById(fileId);
        if (file != null) {
            String fileName = file.getFileName();
            byte[] fileData = file.getData_b();
            if (fileName != null) {
                // Create a multipart message for attachment
                Multipart multipart = new MimeMultipart();
                // Body part
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(mailbody.getBody(), "text/html");
                multipart.addBodyPart(messageBodyPart);

                //Attachment part
                messageBodyPart = new MimeBodyPart();
                ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream");
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(fileName);
                multipart.addBodyPart(messageBodyPart);

                mailMessage.setContent(multipart);
            }
        }
    } else {
        mailMessage.setContent(mailbody.getBody(), "text/html");
    }

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);
}

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

protected void sendEmail(Email email, List<Email> successfulEmails) {
    try {/* w w w. j a va  2s  . co m*/
        if (logger.isDebugEnabled()) {
            logger.debug("Attempting to send " + email.getId() + " " + email.getSubject());
            if (email.getTo() != null) {
                logger.debug("To: " + Arrays.toString(email.getTo().toArray()));
            } else {
                logger.debug("To is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("CC: " + Arrays.toString(email.getCc().toArray()));
            } else {
                logger.debug("CC is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("BCC: " + Arrays.toString(email.getBcc().toArray()));
            } else {
                logger.debug("BCC is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("FROM: " + email.getFrom());
            } else {
                logger.debug("FROM is NULL");
            }
            if (email.getAttachments() != null) {
                logger.debug("Attachments: " + Arrays.toString(email.getAttachments().toArray()));
                for (Attachments attachment : email.getAttachments()) {
                    logger.debug("Attachment: " + attachment.getName());
                }
            } else {
                logger.debug("No attachments");
            }
        }
        //Send email
        if (StringUtils.isBlank(email.getSubject()) || StringUtils.isBlank(email.getFrom())) {
            logger.warn(new StringBuilder("Invalid email without either from or a subject, thus ignoring it ")
                    .append(email.getId()).toString());
            return;
        }
        MimeMessage message = new MimeMessage(session);
        message.setSubject(email.getSubject());
        message.setFrom(new InternetAddress(email.getFrom()));
        addRecipients(message, Message.RecipientType.TO, email.getTo());
        addRecipients(message, Message.RecipientType.CC, email.getCc());
        addRecipients(message, Message.RecipientType.BCC, email.getBcc());
        if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())
                && email.getMessage().getMsgType().equals(MsgType.PLAIN)
                && (email.getAttachments() == null || email.getAttachments().isEmpty())) {
            message.setText(email.getMessage().getMsgBody());
        } else {
            Multipart multipart = new MimeMultipart();
            if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())) {
                MimeBodyPart bodyPart = new MimeBodyPart();
                switch (email.getMessage().getMsgType()) {
                case HTML:
                    bodyPart.setContent(email.getMessage().getMsgBody(), "html");
                    break;
                case PLAIN:
                default:
                    bodyPart.setText(email.getMessage().getMsgBody());
                }
                multipart.addBodyPart(bodyPart);
            }
            if (email.getAttachments() != null && !email.getAttachments().isEmpty()) {
                for (Attachments attachment : email.getAttachments()) {
                    addAttachment(multipart, attachment);
                }
            }
            message.setContent(multipart);
        }
        Transport.send(message);
        if (logger.isDebugEnabled()) {
            logger.debug("Sent " + email.getId());
        }
        //Update status
        email.setMailStatus(Email.MailStatus.SENT);
        successfulEmails.add(email);
        if (logger.isDebugEnabled()) {
            logger.debug("Set new mail status and add to successful queue " + email.getSubject());
        }
    } catch (Exception ex) {
        logger.warn(
                new StringBuilder("Error sending email with subject ").append(email.getSubject()).toString(),
                ex);
    }
}

From source file:org.apache.axis2.transport.mail.EMailSender.java

private void createMailMimeMessage(final MimeMessage msg, MailToInfo mailToInfo, OMOutputFormat format)
        throws MessagingException {

    // Create the message part
    BodyPart messageBodyPart = new MimeBase64BodyPart();
    messageBodyPart.setText("");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    DataSource source = null;//from  w w  w  .ja v  a 2s .c  o m

    // Part two is attachment
    if (outputStream instanceof ByteArrayOutputStream) {
        source = new ByteArrayDataSource(((ByteArrayOutputStream) outputStream).toByteArray());
    }
    messageBodyPart = new MimeBase64BodyPart();
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setDisposition(Part.ATTACHMENT);

    messageBodyPart.addHeader("Content-Description", "\"" + mailToInfo.getContentDescription() + "\"");

    String contentType = format.getContentType() != null ? format.getContentType()
            : Constants.DEFAULT_CONTENT_TYPE;
    if (contentType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) {
        if (messageContext.getSoapAction() != null) {
            messageBodyPart.setHeader(Constants.HEADER_SOAP_ACTION, messageContext.getSoapAction());
        }
    }

    if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
        if (messageContext.getSoapAction() != null) {
            messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding()
                    + " ; action=\"" + messageContext.getSoapAction() + "\"");
        }
    } else {
        messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding());
    }

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

}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendHTMLAndCalendarInvitationMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Session session = Session.getInstance(this.configuration.getAllProperties());

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("alternative");
    // Add an HTML body part
    multipart.addBodyPart(/*from w w  w.j  av  a2  s  . co m*/
            this.htmlBodyPartFactory.create("<font size=\"\\\"2\\\"\">simple meeting invitation</font>",
                    Collections.<String, Object>emptyMap()));
    // Add the Calendar invitation body part
    String calendarContent = "BEGIN:VCALENDAR\r\n" + "METHOD:REQUEST\r\n" + "PRODID: Meeting\r\n"
            + "VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "DTSTAMP:20140616T164100\r\n"
            + "DTSTART:20140616T164100\r\n" + "DTEND:20140616T194100\r\n" + "SUMMARY:test request\r\n"
            + "UID:324\r\n"
            + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:john@doe.com\r\n"
            + "ORGANIZER:MAILTO:john@doe.com\r\n" + "LOCATION:on the net\r\n"
            + "DESCRIPTION:learn some stuff\r\n" + "SEQUENCE:0\r\n" + "PRIORITY:5\r\n" + "CLASS:PUBLIC\r\n"
            + "STATUS:CONFIRMED\r\n" + "TRANSP:OPAQUE\r\n" + "BEGIN:VALARM\r\n" + "ACTION:DISPLAY\r\n"
            + "DESCRIPTION:REMINDER\r\n" + "TRIGGER;RELATED=START:-PT00H15M00S\r\n" + "END:VALARM\r\n"
            + "END:VEVENT\r\n" + "END:VCALENDAR";
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("mimetype", "text/calendar;method=CANCEL");
    parameters.put("headers", Collections.singletonMap("Content-Class", "urn:content-classes:calendarmessage"));
    multipart.addBodyPart(this.defaultBodyPartFactory.create(calendarContent, parameters));

    message.setContent(multipart);

    // Step 4: Send the mail and wait for it to be sent
    this.sender.sendAsynchronously(Arrays.asList(message), session, null);

    // Verify that the mail has been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    assertEquals(2, ((MimeMultipart) messages[0].getContent()).getCount());

    BodyPart htmlBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/html; charset=UTF-8", htmlBodyPart.getHeader("Content-Type")[0]);
    assertEquals("<font size=\"\\\"2\\\"\">simple meeting invitation</font>", htmlBodyPart.getContent());

    BodyPart calendarBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(1);
    assertEquals("text/calendar;method=CANCEL", calendarBodyPart.getHeader("Content-Type")[0]);
    InputStream is = (InputStream) calendarBodyPart.getContent();
    assertEquals(calendarContent, IOUtils.toString(is));
}

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

@Override
public int send(Mail mail) {
    Session session = null;//from   w ww  .j av  a 2s .  c om
    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:org.j2free.email.EmailService.java

private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body,
        ContentType contentType, Priority priority, boolean ccSender)
        throws AddressException, MessagingException, RejectedExecutionException {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);//from w  w  w  .  j a  v  a2s  .  c  o  m
    message.setRecipients(Message.RecipientType.TO, recipients);

    for (Map.Entry<String, String> header : headers.entrySet())
        message.setHeader(header.getKey(), header.getValue());

    // CC the sender if they want
    if (ccSender)
        message.addRecipient(Message.RecipientType.CC, from);

    message.setReplyTo(new InternetAddress[] { from });

    message.setSubject(subject);
    message.setSentDate(new Date());

    if (contentType == ContentType.PLAIN) {
        // Just set the body as plain text
        message.setText(body, "UTF-8");
    } else {
        MimeMultipart multipart = new MimeMultipart("alternative");

        // Create the text part
        MimeBodyPart text = new MimeBodyPart();
        text.setText(new HtmlFilter().filterForEmail(body), "UTF-8");

        // Add the text part
        multipart.addBodyPart(text);

        // Create the HTML portion
        MimeBodyPart html = new MimeBodyPart();
        html.setContent(body, ContentType.HTML.toString());

        // Add the HTML portion
        multipart.addBodyPart(html);

        // set the message content
        message.setContent(multipart);
    }
    enqueue(message, priority);
}

From source file:bean.RedSocial.java

/**
 * /*w ww. j a v a  2  s  .c o  m*/
 * @param _username
 * @param _email
 * @param _password 
 */
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class)
public void solicitarAcceso(String _username, String _email, String _password) {
    if (daoUsuario.obtenerUsuario(_username) != null) {
        throw new exceptionsBusiness.UsernameNoDisponible();
    }

    String hash = BCrypt.hashpw(_password, BCrypt.gensalt());

    Token token = new Token(_username, _email, hash);
    daoToken.guardarToken(token);

    //enviar token de acceso a la direccion email

    String correoEnvia = "skala2climbing@gmail.com";
    String claveCorreo = "vNspLa5H";

    // La configuracin para enviar correo
    Properties properties = new Properties();
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.user", correoEnvia);
    properties.put("mail.password", claveCorreo);

    // Obtener la sesion
    Session session = Session.getInstance(properties, null);

    try {
        // Crear el cuerpo del mensaje
        MimeMessage mimeMessage = new MimeMessage(session);

        // Agregar quien enva el correo
        mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing"));

        // Los destinatarios
        InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) };

        // Agregar los destinatarios al mensaje
        mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses);

        // Agregar el asunto al correo
        mimeMessage.setSubject("Confirmacin de registro");

        // Creo la parte del mensaje
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        String ip = "90.165.24.228";
        mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip
                + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token="
                + token.getToken());
        //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible");

        // Crear el multipart para agregar la parte del mensaje anterior
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        // Agregar el multipart al cuerpo del mensaje
        mimeMessage.setContent(multipart);

        // Enviar el mensaje
        Transport transport = session.getTransport("smtp");
        transport.connect(correoEnvia, claveCorreo);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();

    } catch (UnsupportedEncodingException | MessagingException ex) {
        throw new ErrorEnvioEmail();
    }

}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server//from  w  w  w.j a  v a 2 s .  com
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static ErrorType sendMsg(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, final String port, final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;

    if (StringUtils.isEmpty(toEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR");
        return ErrorType.Error;
    }

    if (StringUtils.isEmpty(fromEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR");
        return ErrorType.Error;
    }

    //if (isGmailEmail())
    //{
    //    return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment);
    //}

    Boolean fail = false;
    ArrayList<String> userAndPass = new ArrayList<String>();

    boolean isSSL = security.equals("SSL");

    String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable",
            "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback",
            "mail.imap.auth.plain.disable", };
    Properties props = System.getProperties();
    for (String key : keys) {
        props.remove(key);
    }

    props.put("mail.smtp.host", host); //$NON-NLS-1$

    if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) {
        props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        props.remove("mail.smtp.port");
    }

    if (StringUtils.isNotEmpty(security)) {
        if (security.equals("TLS")) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

        } else if (isSSL) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$

            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.imap.auth.plain.disable", "true");
        }
    }

    Session session = null;
    if (isSSL) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uName, pWord);
            }
        });

    } else {
        session = Session.getInstance(props, null);
    }

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
        log.debug("Port:     " + port); //$NON-NLS-1$
        log.debug("Security: " + security); //$NON-NLS-1$
    }

    try {

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

        msg.setFrom(new InternetAddress(fromEMailAddr));

        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            try {
                InternetAddress[] address = { new InternetAddress(toEMailAddr) };
                msg.setRecipients(Message.RecipientType.TO, address);

            } catch (javax.mail.internet.AddressException ex) {
                UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr);
                return ErrorType.Error;
            }
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        final int TRIES = 1;

        // set the Date: header
        msg.setSentDate(new Date());

        Exception exception = null;
        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                if (isSSL) {
                    Transport.send(msg);

                } else {
                    t.connect(host, userName, password);
                    t.sendMessage(msg, msg.getAllRecipients());
                }

                fail = false;

            } catch (SendFailedException mex) {
                mex.printStackTrace();
                exception = mex;

            } catch (MessagingException mex) {
                if (mex.getCause() instanceof UnknownHostException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host);

                } else if (mex.getCause() instanceof ConnectException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError(
                            "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port);

                } else {
                    mex.printStackTrace();
                    exception = mex;
                }

            } catch (Exception mex) {
                mex.printStackTrace();
                exception = mex;

            } finally {
                if (t != null) {
                    log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                    t.close();
                }
            }

            if (exception != null) {
                fail = true;

                instance.lastErrorMsg = exception.toString();

                //wrong username or password, get new one
                if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName);

                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) { //the user is done
                        instance.lastErrorMsg = null;
                        return ErrorType.Cancel;
                    }
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }

            }
            exception = null;

        } while (fail && cnt < TRIES);

    } catch (Exception mex) {
        //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        mex.printStackTrace();
        Exception ex = null;
        if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return ErrorType.Error;

    }

    if (fail) {
        return ErrorType.Error;
    } //else

    return ErrorType.OK;
}