Example usage for org.apache.commons.mail HtmlEmail setMailSession

List of usage examples for org.apache.commons.mail HtmlEmail setMailSession

Introduction

In this page you can find the example usage for org.apache.commons.mail HtmlEmail setMailSession.

Prototype

public void setMailSession(final Session aSession) 

Source Link

Document

Supply a mail Session object to use.

Usage

From source file:com.actionbazaar.email.EmailService.java

/**
 * Sends out an email//  w ww . j  a v  a2s  .c o m
 * @param message - message to be sent
 */
public void onMessage(Message message) {

    try {
        EmailRequest emailRequest = (EmailRequest) ((ObjectMessage) message).getObject();

        Query query = entityManager.createQuery("select e from Email e where e.action = ?1");
        query.setParameter(1, emailRequest.getAction());
        List results = query.getResultList();
        if (results.size() != 1) {
            logger.severe("A total of " + results.size() + " email templates were returned for action "
                    + emailRequest.getAction());
            return;
        }
        System.out.println("--> Sending email.");
        Email emailInfo = (Email) results.get(0);
        logger.info("Speaker Directory: " + attachmentDirectory);
        HtmlEmail email = new HtmlEmail();
        email.setMailSession(mailSession);
        email.setTextMsg("Hello World!");
        //  email.setSubject(template.getSubject());
        email.addTo("rcuprak@mac.com");
        email.setFrom("java@ctjava.org");
        //  email.send();

        /*       emailTemplate.process(emailRecipient.getReplacementTokens());
                for (Map.Entry<String,File> entry : emailTemplate.getCidMappings().entrySet()) {
                    email.embed(entry.getValue(),entry.getKey());
                }
                email.setHtmlMsg(emailTemplate.getPatchedEmail());
          */
    } catch (Throwable t) {
        t.printStackTrace();
        //context.setRollbackOnly();
    }
}

From source file:com.itcs.commons.email.impl.RunnableSendHTMLEmail.java

public void run() {
    Logger.getLogger(RunnableSendHTMLEmail.class.getName()).log(Level.INFO,
            "executing Asynchronous task RunnableSendHTMLEmail");
    try {//ww  w  .ja  va  2s  .c o  m
        HtmlEmail email = new HtmlEmail();
        email.setCharset("utf-8");
        email.setMailSession(getSession());
        for (String dir : to) {
            email.addTo(dir);
        }
        if (cc != null) {
            for (String ccEmail : cc) {
                email.addCc(ccEmail);
            }
        }
        if (cco != null) {
            for (String ccoEmail : cco) {
                email.addBcc(ccoEmail);
            }
        }
        email.setSubject(subject);
        // set the html message
        email.setHtmlMsg(body);
        email.setFrom(getSession().getProperties().getProperty(Email.MAIL_SMTP_FROM, Email.MAIL_SMTP_USER),
                getSession().getProperties().getProperty(Email.MAIL_SMTP_FROMNAME, Email.MAIL_SMTP_USER));
        // set the alternative message
        email.setTextMsg("Si ve este mensaje, significa que su cliente de correo no permite mensajes HTML.");
        // send the email
        if (attachments != null) {
            addAttachments(email, attachments);
        }
        email.send();
        Logger.getLogger(RunnableSendHTMLEmail.class.getName()).log(Level.INFO,
                "Email sent successfully to:{0} cc:{1} bcc:{2}",
                new Object[] { Arrays.toString(to), Arrays.toString(cc), Arrays.toString(cco) });
    } catch (EmailException e) {
        Logger.getLogger(RunnableSendHTMLEmail.class.getName()).log(Level.SEVERE,
                "EmailException Error sending email... with properties:\n" + session.getProperties(), e);
    }
}

From source file:com.duroty.application.open.manager.OpenManager.java

/**
 * DOCUMENT ME!/*from   w w  w .j a  v a2s  .c  o  m*/
 *
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param from DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
private void sendData(Session msession, InternetAddress from, InternetAddress to, String username,
        String password, String signature) throws Exception {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setMailSession(msession);

        email.setFrom(from.getAddress(), from.getPersonal());
        email.addTo(to.getAddress(), to.getPersonal());

        email.setSubject("Duroty System");
        email.setHtmlMsg("<p>Username: <b>" + username + "</b></p><p>Password: " + password + "<b></b></p><p>"
                + signature + "</p>");

        email.setCharset(MimeUtility.javaCharset(Charset.defaultCharset().displayName()));

        email.send();
    } finally {
    }
}

From source file:com.duroty.application.open.manager.OpenManager.java

/**
 * DOCUMENT ME!/*from   www .j a va  2 s.  c  o m*/
 *
 * @param msession DOCUMENT ME!
 * @param from DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param username DOCUMENT ME!
 * @param password DOCUMENT ME!
 * @param signature DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
private void notifyToAdmins(Session msession, InternetAddress from, InternetAddress[] to, String user)
        throws Exception {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setMailSession(msession);

        email.setFrom(from.getAddress(), from.getPersonal());

        HashSet aux = new HashSet(to.length);
        Collections.addAll(aux, to);
        email.setTo(aux);

        email.setSubject("User register in Duroty System");
        email.setHtmlMsg(
                "<p>The user solicits register into the system</p><p>The user is: <b>" + user + "</b></p>");

        email.setCharset(MimeUtility.javaCharset(Charset.defaultCharset().displayName()));

        email.send();
    } finally {
    }
}

From source file:edu.wright.cs.fa15.ceg3120.concon.server.EmailManager.java

/**
 * Add an outgoing email to the queue./*from  w  w w  .j  a v  a2 s . c  o  m*/
 * @param to Array of email addresses.
 * @param subject Header
 * @param body Content
 * @param attachmentFile Attachment
 */
public void addEmail(String[] to, String subject, String body, File attachmentFile) {
    HtmlEmail mail = new HtmlEmail();
    Properties sysProps = System.getProperties();

    // Setup mail server
    sysProps.setProperty("mail.smtp.host", props.getProperty("mail_server_hostname"));
    Session session = Session.getDefaultInstance(sysProps);

    try {
        mail.setMailSession(session);
        mail.setFrom(props.getProperty("server_email_addr"), props.getProperty("server_title"));
        mail.addTo(to);
        mail.setSubject(subject);
        mail.setTextMsg(body);
        mail.setHtmlMsg(composeAsHtml(mail, body));
        if (attachmentFile.exists()) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(attachmentFile.getPath());
            mail.attach(attachment);
        }
    } catch (EmailException e) {
        LOG.warn("Email was not added. ", e);
    }
    mailQueue.add(mail);
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!//w w  w. jav  a  2  s .c  o m
 *
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param from DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void sendIdentity(Session session, String repositoryName, String from, String to, String subject,
        String body) throws MailException {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setMailSession(session);
        email.setFrom(from);
        email.addTo(to);
        email.setSubject(subject);
        email.setHtmlMsg(body);
        email.setCharset(Charset.defaultCharset().displayName());

        email.send();
    } catch (Exception e) {
        throw new MailException(e);
    } finally {
    }
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!/*ww w .j av  a2 s . c  om*/
 *
 * @param username DOCUMENT ME!
 * @param to DOCUMENT ME!
 */
private void sendVacationMessage(String username, String to) {
    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(smtpSessionFactory);

        Users user = getUser(hsession, username);

        Criteria crit = hsession.createCriteria(Identity.class);
        crit.add(Restrictions.eq("users", getUser(hsession, username)));
        crit.add(Restrictions.eq("ideActive", new Boolean(true)));
        crit.add(Restrictions.eq("ideDefault", new Boolean(true)));

        Identity identity = (Identity) crit.uniqueResult();

        if (identity != null) {
            InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
            InternetAddress _to = InternetAddress.parse(to)[0];

            if (_from.getAddress().equals(_to.getAddress())) {
                return;
            }

            HtmlEmail email = new HtmlEmail();
            email.setMailSession(msession);

            email.setFrom(_from.getAddress(), _from.getPersonal());
            email.addTo(_to.getAddress(), _to.getPersonal());

            Iterator it = user.getMailPreferenceses().iterator();
            MailPreferences mailPreferences = (MailPreferences) it.next();

            email.setSubject(mailPreferences.getMaprVacationSubject());
            email.setHtmlMsg("<p>" + mailPreferences.getMaprVacationBody() + "</p><p>"
                    + mailPreferences.getMaprSignature() + "</p>");

            email.setCharset(Charset.defaultCharset().displayName());

            email.send();
        }
    } catch (Exception e) {
    } finally {
    }
}

From source file:com.duroty.application.chat.manager.ChatManager.java

/**
 * DOCUMENT ME!//from   w  w w  .  j ava 2 s. co  m
 *
 * @param hsession DOCUMENT ME!
 * @param userSender DOCUMENT ME!
 * @param userRecipient DOCUMENT ME!
 */
private void sendMail(Session hsession, javax.mail.Session msession, Users userSender, Users userRecipient,
        String message) {
    try {
        String sender = userSender.getUseUsername();
        String recipient = userRecipient.getUseUsername();

        Identity identitySender = getIdentity(hsession, userSender);
        Identity identityRecipient = getIdentity(hsession, userRecipient);

        HtmlEmail email = new HtmlEmail();
        InternetAddress _from = new InternetAddress(identitySender.getIdeEmail(), identitySender.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identitySender.getIdeReplyTo(),
                identitySender.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(identityRecipient.getIdeEmail(), null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _from);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        email.setCharset(charset);
        email.setSubject("Chat " + sender + " >> " + recipient);
        email.setHtmlMsg(message);

        calendar.setTime(new Date());

        String minute = "30";

        if (calendar.get(Calendar.MINUTE) >= 30) {
            minute = "60";
        }

        String value = String.valueOf(calendar.get(Calendar.YEAR))
                + String.valueOf(calendar.get(Calendar.MONTH)) + String.valueOf(calendar.get(Calendar.DATE))
                + String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)) + minute
                + String.valueOf(userSender.getUseIdint() + userRecipient.getUseIdint());
        String reference = "<" + value + ".JavaMail.duroty@duroty" + ">";
        email.addHeader(RFC2822Headers.IN_REPLY_TO, reference);
        email.addHeader(RFC2822Headers.REFERENCES, reference);

        email.addHeader("X-DBox", "CHAT");

        Date now = new Date();
        email.setSentDate(now);

        email.setMailSession(msession);
        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();

        int size = MessageUtilities.getMessageSize(mime);

        if (controlQuota(hsession, userSender, size)) {
            //messageable.saveSentMessage(null, mime, userSender);
            Thread thread = new Thread(new SendMessageThread(email));
            thread.start();
        }
    } catch (UnsupportedEncodingException e) {
    } catch (MessagingException e) {
    } catch (EmailException e) {
    } catch (Exception e) {
    }
}

From source file:org.onehippo.forge.resetpassword.services.mail.MailServiceImpl.java

@Override
public void sendMail(final MailMessage mailMessage) throws EmailException {

    final HtmlEmail email = new HtmlEmail();

    final Session session = getSession();
    if (session == null) {
        throw new EmailException("Unable to send mail; no mail session available");
    }/*www .j a  v a 2s. c  o m*/

    email.setMailSession(session);
    email.addTo(mailMessage.getToMail(), mailMessage.getToName());
    email.setFrom(mailMessage.getFromMail(), mailMessage.getFromName());
    email.setSubject(mailMessage.getSubject());

    // set the html message
    email.setHtmlMsg(mailMessage.getHtmlTextBody());

    // set the alternative message
    email.setTextMsg(mailMessage.getPlainTextBody());

    // send the email
    email.send();
}