Example usage for javax.mail.internet MimeMessage setSentDate

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

Introduction

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

Prototype

@Override
public void setSentDate(Date d) throws MessagingException 

Source Link

Document

Set the RFC 822 "Date" header field.

Usage

From source file:org.tightblog.service.EmailService.java

/**
 * This method is used to send an HTML Message
 *
 * @param from    e-mail address of sender
 * @param to      e-mail address(es) of recipients
 * @param subject subject of e-mail//from  w  w w  .  j a v  a  2 s .c  o  m
 * @param content the body of the e-mail
 */
private void sendMessage(String from, String[] to, String[] cc, String subject, String content) {
    try {
        MimeMessage message = mailSender.createMimeMessage();

        // n.b. any default from address is expected to be determined by caller.
        if (!StringUtils.isEmpty(from)) {
            InternetAddress sentFrom = new InternetAddress(from);
            message.setFrom(sentFrom);
            log.debug("e-mail from: {}", sentFrom);
        }

        if (to != null) {
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                sendTo[i] = new InternetAddress(to[i]);
                log.debug("sending e-mail to: {}", to[i]);
            }
            message.setRecipients(Message.RecipientType.TO, sendTo);
        }

        if (cc != null) {
            InternetAddress[] copyTo = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                copyTo[i] = new InternetAddress(cc[i]);
                log.debug("copying e-mail to: {}", cc[i]);
            }
            message.setRecipients(Message.RecipientType.CC, copyTo);
        }

        message.setSubject((subject == null) ? "(no subject)" : subject, "UTF-8");
        message.setContent(content, "text/html; charset=utf-8");
        message.setSentDate(new java.util.Date());

        // First collect all the addresses together.
        boolean bFailedToSome = false;
        SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            mailSender.send(message);
        } catch (MailAuthenticationException | MailSendException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);
        }

        if (bFailedToSome) {
            throw sendex;
        }
    } catch (MessagingException e) {
        log.error("ERROR: Problem sending email with subject {}", subject, e);
    }
}

From source file:org.gcaldaemon.core.GmailEntry.java

public final void send(String to, String cc, String bcc, String subject, String memo, boolean html)
        throws Exception {
    MimeMessage mimeMessage = new MimeMessage(smtpSession);

    // Add 'to' fields
    StringTokenizer st = new StringTokenizer(to, ", ");
    while (st.hasMoreTokens()) {
        mimeMessage.addRecipients(Message.RecipientType.TO, st.nextToken());
    }/*from w w  w . ja  v a 2s  .  c om*/

    // Add 'cc' fields
    if (cc != null && cc.length() != 0) {
        st = new StringTokenizer(cc, ", ");
        while (st.hasMoreTokens()) {
            mimeMessage.addRecipients(Message.RecipientType.CC, st.nextToken());
        }
    }

    // Add 'bcc' fields
    if (bcc != null && bcc.length() != 0) {
        st = new StringTokenizer(bcc, ", ");
        while (st.hasMoreTokens()) {
            mimeMessage.addRecipients(Message.RecipientType.BCC, st.nextToken());
        }
    }

    // Set message
    if (html) {
        mimeMessage.setHeader("Content-Type", "text/html");
        mimeMessage.setContent(memo.trim(), "text/html; charset=UTF-8");
    } else {
        mimeMessage.setHeader("Content-Type", "text/plain");
        mimeMessage.setContent(memo.trim(), "text/plain; charset=UTF-8");
    }

    // Set 'from', 'subject' and date fields
    mimeMessage.setFrom(new InternetAddress(username));
    mimeMessage.setSubject(subject.trim(), "UTF-8");
    mimeMessage.setSentDate(new Date());
    Transport.send(mimeMessage);
}

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 {// w  ww  .ja va 2 s. com
        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: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 a2s . 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 boolean sendMsgAsGMail(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, @SuppressWarnings("unused") final String port,
        @SuppressWarnings("unused") final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;
    Boolean fail = false;

    ArrayList<String> userAndPass = new ArrayList<String>();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host); //$NON-NLS-1$
    props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    boolean usingSSL = false;
    if (usingSSL) {
        props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
        props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    }

    Session 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$
    }

    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 {
            InternetAddress[] address = { new InternetAddress(toEMailAddr) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        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);
        }

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

        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                t.connect(host, userName, password);

                t.sendMessage(msg, msg.getAllRecipients());

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

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

                //wrong username or password, get new one
                if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    fail = true;
                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) {//the user is done
                        return false;
                    }
                    // else
                    //try again
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }
            } finally {

                log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                t.close();
            }
        } while (fail && cnt < 6);

    } catch (MessagingException 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 ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return false;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
        ex.printStackTrace();
    }

    if (fail) {
        return false;
    } //else
    return true;
}

From source file:org.nuxeo.ecm.platform.ec.notification.email.EmailHelper.java

protected void sendmail0(Map<String, Object> mail)
        throws MessagingException, IOException, TemplateException, LoginException, RenderingException {

    Session session = getSession();//from  w w  w.ja va  2 s. c om
    if (javaMailNotAvailable || session == null) {
        log.warn("Not sending email since JavaMail is not configured");
        return;
    }

    // Construct a MimeMessage
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(session.getProperty("mail.from")));
    Object to = mail.get("mail.to");
    if (!(to instanceof String)) {
        log.error("Invalid email recipient: " + to);
        return;
    }
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) to, false));

    RenderingService rs = Framework.getService(RenderingService.class);

    DocumentRenderingContext context = new DocumentRenderingContext();
    context.remove("doc");
    context.putAll(mail);
    context.setDocument((DocumentModel) mail.get("document"));
    context.put("Runtime", Framework.getRuntime());

    String customSubjectTemplate = (String) mail.get(NotificationConstants.SUBJECT_TEMPLATE_KEY);
    if (customSubjectTemplate == null) {
        String subjTemplate = (String) mail.get(NotificationConstants.SUBJECT_KEY);
        Template templ = new Template("name", new StringReader(subjTemplate), stringCfg);

        Writer out = new StringWriter();
        templ.process(mail, out);
        out.flush();

        msg.setSubject(out.toString(), "UTF-8");
    } else {
        rs.registerEngine(new NotificationsRenderingEngine(customSubjectTemplate));

        LoginContext lc = Framework.login();

        Collection<RenderingResult> results = rs.process(context);
        String subjectMail = "<HTML><P>No parsing Succeded !!!</P></HTML>";

        for (RenderingResult result : results) {
            subjectMail = (String) result.getOutcome();
        }
        subjectMail = NotificationServiceHelper.getNotificationService().getEMailSubjectPrefix() + subjectMail;
        msg.setSubject(subjectMail, "UTF-8");

        lc.logout();
    }

    msg.setSentDate(new Date());

    rs.registerEngine(new NotificationsRenderingEngine((String) mail.get(NotificationConstants.TEMPLATE_KEY)));

    LoginContext lc = Framework.login();

    Collection<RenderingResult> results = rs.process(context);
    String bodyMail = "<HTML><P>No parsing Succedeed !!!</P></HTML>";

    for (RenderingResult result : results) {
        bodyMail = (String) result.getOutcome();
    }

    lc.logout();

    rs.unregisterEngine("ftl");

    msg.setContent(bodyMail, "text/html; charset=utf-8");

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

From source file:org.liveSense.service.email.EmailServiceImpl.java

private MimeMessage prepareMimeMessage(MimeMessage mimeMessage, Node node, String template, String subject,
        Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc,
        HashMap<String, Object> variables) throws AddressException, MessagingException, ValueFormatException,
        PathNotFoundException, RepositoryException, UnsupportedEncodingException {

    if (replyTo != null) {
        mimeMessage.setReplyTo(convertToInternetAddress(replyTo));
    } else {//from w  w  w . j  av  a  2 s . c om
        if (node != null && node.hasProperty("replyTo")) {
            mimeMessage.setReplyTo(convertToInternetAddress(node.getProperty("replyTo").getString()));
        } else if (variables != null && variables.containsKey("replyTo")) {
            mimeMessage.setReplyTo(convertToInternetAddress(variables.get("replyTo")));
        }
    }
    if (date == null) {
        if (node != null && node.hasProperty("mailDate")) {
            mimeMessage.setSentDate(node.getProperty("mailDate").getDate().getTime());
        } else if (variables != null && variables.containsKey("mailDate")) {
            mimeMessage.setSentDate((Date) variables.get("mailDate"));
        } else {
            mimeMessage.setSentDate(new Date());
        }
    } else {
        mimeMessage.setSentDate(date);
    }

    if (subject != null) {
        mimeMessage.setSubject(MimeUtility.encodeText(subject, configurator.getEncoding(), "Q"));
    } else {
        if (node != null && node.hasProperty("subject")) {
            mimeMessage.setSubject(MimeUtility.encodeText(node.getProperty("subject").getString(),
                    configurator.getEncoding(), "Q"));
        } else if (variables != null && variables.containsKey("subject")) {
            mimeMessage.setSubject(
                    MimeUtility.encodeText((String) variables.get("subject"), configurator.getEncoding(), "Q"));
        }
    }

    if (from != null) {
        mimeMessage.setFrom(convertToInternetAddress(from)[0]);
    } else {
        if (node != null && node.hasProperty("from")) {
            mimeMessage.setFrom(convertToInternetAddress(node.getProperty("from").getString())[0]);
        } else if (variables != null && variables.containsKey("from")) {
            mimeMessage.setFrom(convertToInternetAddress(variables.get("from"))[0]);
        }
    }

    if (to != null) {
        mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(to));
    } else {
        if (node != null && node.hasProperty("to")) {
            if (node.getProperty("to").isMultiple()) {
                Value[] values = node.getProperty("to").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.TO,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.TO,
                        convertToInternetAddress(node.getProperty("to").getString()));
            }
        } else if (variables != null && variables.containsKey("to")) {
            mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(variables.get("to")));
        }

    }

    if (cc != null) {
        mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(cc));
    } else {
        if (node != null && node.hasProperty("cc")) {
            if (node.getProperty("cc").isMultiple()) {
                Value[] values = node.getProperty("cc").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.CC,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.CC,
                        convertToInternetAddress(node.getProperty("cc").getString()));
            }
        } else if (variables != null && variables.containsKey("cc")) {
            mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(variables.get("cc")));
        }
    }

    if (bcc != null) {
        mimeMessage.addRecipients(Message.RecipientType.BCC, convertToInternetAddress(bcc));
    } else {
        if (node != null && node.hasProperty("bcc")) {
            if (node.getProperty("bcc").isMultiple()) {
                Value[] values = node.getProperty("bcc").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.BCC,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.BCC,
                        convertToInternetAddress(node.getProperty("bcc").getString()));
            }
        } else if (variables != null && variables.containsKey("bcc")) {
            mimeMessage.addRecipients(Message.RecipientType.BCC,
                    convertToInternetAddress(variables.get("bcc")));
        }
    }
    return mimeMessage;
}

From source file:org.pentaho.platform.scheduler2.email.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {/*from  w w  w  .j av  a 2s .c  om*/
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        if (attachment == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }

        ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

        if (body != null) {
            MimeBodyPart bodyMessagePart = new MimeBodyPart();
            bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
            multipart.addBodyPart(bodyMessagePart);
        }

        // attach the file to the message
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
        multipart.addBodyPart(attachmentBodyPart);

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

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

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//w w w .j  a va2  s  .  c o m
 * @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;
}

From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java

public boolean send() {
    String cc = null;/*w ww .  ja v a 2s.  com*/
    String bcc = null;
    String from = props.getProperty("mail.from.default");
    String to = props.getProperty("to");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + "with the subject '" + subject
            + "' and the body " + body);

    try {
        // Get a Session object
        Session session;

        if (authenticate) {
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        if (body != null) {
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            multipart.addBodyPart(textBodyPart);
        }

        // need to create a multi-part message...
        // create the Multipart and add its parts to it

        // create and fill the first message part
        IPentahoStreamSource source = attachment;
        if (source == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }
        DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);

        // create the second message part
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();

        // attach the file to the message
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(attachmentName);

        multipart.addBodyPart(attachmentBodyPart);

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

        msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$

    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:com.flexive.shared.FxMailUtils.java

/**
 * Sends an email/*from   www . ja  v a  2s. com*/
 *
 * @param SMTPServer      IP Address of the SMTP server
 * @param subject         subject of the email
 * @param textBody        plain text
 * @param htmlBody        html text
 * @param to              recipient
 * @param cc              cc recepient
 * @param bcc             bcc recipient
 * @param from            sender
 * @param replyTo         reply-to address
 * @param mimeAttachments strings containing mime encoded attachments
 * @throws FxApplicationException on errors
 */
public static void sendMail(String SMTPServer, String subject, String textBody, String htmlBody, String to,
        String cc, String bcc, String from, String replyTo, String... mimeAttachments)
        throws FxApplicationException {

    try {
        // Set the mail server
        java.util.Properties properties = System.getProperties();
        if (SMTPServer != null)
            properties.put("mail.smtp.host", SMTPServer);

        // Get a session and create a new message
        javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
        MimeMessage msg = new MimeMessage(session);

        // Set the sender
        if (StringUtils.isBlank(from))
            msg.setFrom(); // Uses local IP Adress and the user under which the server is running
        else {
            msg.setFrom(createAddress(from));
        }

        if (!StringUtils.isBlank(replyTo))
            msg.setReplyTo(encodePersonal(InternetAddress.parse(replyTo, false)));

        // Set the To, Cc and Bcc fields
        if (!StringUtils.isBlank(to))
            msg.setRecipients(MimeMessage.RecipientType.TO, encodePersonal(InternetAddress.parse(to, false)));
        if (!StringUtils.isBlank(cc))
            msg.setRecipients(MimeMessage.RecipientType.CC, encodePersonal(InternetAddress.parse(cc, false)));
        if (!StringUtils.isBlank(bcc))
            msg.setRecipients(MimeMessage.RecipientType.BCC, encodePersonal(InternetAddress.parse(bcc, false)));

        // Set the subject
        msg.setSubject(subject, "UTF-8");

        String sMainType = "Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"";

        StringBuilder body = new StringBuilder(5000);

        if (mimeAttachments.length > 0) {
            sMainType = "Multipart/Mixed;\n\tboundary=\"" + BOUNDARY2 + "\"";
            body.append("This is a multi-part message in MIME format.\n\n");
            body.append("--" + BOUNDARY2 + "\n");
            body.append("Content-Type: Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"\n\n\n");
        }

        if (textBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/plain; charset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            body.append(encodeQuotedPrintable(textBody)).append("\n");
        }
        if (htmlBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/html;\n\tcharset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            if (htmlBody.toLowerCase().indexOf("<html>") < 0) {
                body.append("<HTML><HEAD>\n<TITLE></TITLE>\n");
                body.append(
                        "<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Dutf-8\"></HEAD>\n<BODY>\n");
                body.append(encodeQuotedPrintable(htmlBody)).append("</BODY></HTML>\n");
            } else
                body.append(encodeQuotedPrintable(htmlBody)).append("\n");
        }

        body.append("\n--" + BOUNDARY1 + "--\n");

        if (mimeAttachments.length > 0) {
            for (String mimeAttachment : mimeAttachments) {
                body.append("\n--" + BOUNDARY2 + "\n");
                body.append(mimeAttachment).append("\n");
            }
            body.append("\n--" + BOUNDARY2 + "--\n");
        }

        msg.setDataHandler(
                new javax.activation.DataHandler(new ByteArrayDataSource(body.toString(), sMainType)));

        // Set the header
        msg.setHeader("X-Mailer", "JavaMailer");

        // Set the sent date
        msg.setSentDate(new java.util.Date());

        // Send the message
        javax.mail.Transport.send(msg);
    } catch (AddressException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.address", e.getRef());
    } catch (javax.mail.MessagingException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (IOException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (EncoderException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    }
}