Example usage for org.apache.commons.mail Email send

List of usage examples for org.apache.commons.mail Email send

Introduction

In this page you can find the example usage for org.apache.commons.mail Email send.

Prototype

public String send() throws EmailException 

Source Link

Document

Sends the email.

Usage

From source file:sce.Mail.java

public static void sendMail(String subject, String message, String recipient, String headerName,
        String headerValue) {/*www.ja  v a2s . c o m*/
    try {
        //load mail settings from quartz.properties
        Properties prop = new Properties();
        prop.load(Mail.class.getResourceAsStream("quartz.properties"));
        String smtp_hostname = prop.getProperty("smtp_hostname");
        int smtp_port = Integer.parseInt(prop.getProperty("smtp_port"));
        boolean smtp_ssl = prop.getProperty("smtp_ssl").equalsIgnoreCase("true");
        String smtp_username = prop.getProperty("smtp_username");
        String smtp_password = prop.getProperty("smtp_password");
        String smtp_mailfrom = prop.getProperty("smtp_mailfrom");

        Email email = new SimpleEmail();
        email.setHostName(smtp_hostname);
        email.setSmtpPort(smtp_port);
        email.setAuthenticator(new DefaultAuthenticator(smtp_username, smtp_password));
        email.setSSLOnConnect(smtp_ssl);
        email.setFrom(smtp_mailfrom);
        email.setSubject(subject);
        email.setMsg(message);
        String[] recipients = recipient.split(";"); //this is semicolon separated array of recipients
        for (String tmp : recipients) {
            email.addTo(tmp);
        }
        //email.addHeader(headerName, headerValue);
        email.send();
    } catch (EmailException e) {
    } catch (IOException e) {
    }
}

From source file:scouter.plugin.server.alert.email.EmailPlugin.java

/**
 * ? ? ??  <br>//from  w w  w.  j a  v a  2 s  . c  o  m
 *   ? ?? ?? <br>
 * @param pack ?? ?   pack
 */
@ServerPlugin(PluginConstants.PLUGIN_SERVER_ALERT)
public void alert(final AlertPack pack) {
    /* Email    */
    if (conf.getBoolean("ext_plugin_email_send_alert", true)) {

        /* 
         * Get log level (0 : INFO, 1 : WARN, 2 : ERROR, 3 : FATAL)
         * 0   ??  ??  ?.
         */
        int level = conf.getInt("ext_plugin_email_level", 0);

        /* ?  level   ? ? ?  */
        if (level <= pack.level) {
            new Thread() {
                public void run() {
                    try {

                        // Get server configurations for email
                        String hostname = conf.getValue("ext_plugin_email_smtp_hostname", "smtp.gmail.com"); // smtp 
                        int port = conf.getInt("ext_plugin_email_smtp_port", 587); // smtp ?

                        String username = conf.getValue("ext_plugin_email_username", "haniumscouter@gmail.com"); // ? ?? 
                        String password = conf.getValue("ext_plugin_email_password", "dkqorhvk!@#$"); // ? ?? 

                        boolean tlsEnabled = conf.getBoolean("ext_plugin_email_tls_enabled", true); // tls (gamil? true)

                        String from = conf.getValue("ext_plugin_email_from_address", "haniumscouter@gmail.com"); // ?? ? ?? 
                        String to = conf.getValue("ext_plugin_email_to_address", "occidere@naver.com"); // ? ??(? , )
                        String cc = conf.getValue("ext_plugin_email_cc_address"); // cc ??

                        assert hostname != null;
                        assert port > 0;
                        assert username != null;
                        assert password != null;
                        assert from != null;
                        assert to != null;

                        // Get agent Name.  ??.
                        String name = AgentManager.getAgentName(pack.objHash) == null ? "N/A"
                                : AgentManager.getAgentName(pack.objHash);

                        if (name.equals("N/A") && pack.message.endsWith("connected.")) {
                            int idx = pack.message.indexOf("connected");
                            if (pack.message.indexOf("reconnected") > -1)
                                name = pack.message.substring(0, idx - 6);
                            else
                                name = pack.message.substring(0, idx - 4);
                        }

                        // Make email subject
                        String subject = "[" + AlertLevel.getName(pack.level) + "] "
                                + pack.objType.toUpperCase() + "(" + name + ") : " + pack.title;

                        String title = pack.title;
                        String msg = pack.message;

                        /* 
                         * Agent ? (inactivate) ? ? .
                         * ?  ,  ? ? Agent  ?  ?
                         * Agent ?  title? ?    .
                         */
                        if (title.equals("INACTIVE_OBJECT")) {
                            title = name + "  (Inactivated) ?!";
                            msg = pack.message.substring(0, pack.message.indexOf("OBJECT") - 1);
                        }

                        //? ? ? ?  ?
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd? HH mm ss");

                        // Make email message
                        String message = "[??   ?   ver.20170815]"
                                + Util.NEW_LINE + "[ ] : " + title + Util.NEW_LINE + "[ ] : "
                                + sdf.format(new Date(pack.time)) + Util.NEW_LINE + "[ ] : "
                                + pack.objType.toUpperCase() + Util.NEW_LINE + "[? ] : " + name
                                + Util.NEW_LINE + "[ ] : " + AlertLevel.getName(pack.level)
                                + Util.NEW_LINE + "[ ] : " + msg + Util.NEW_LINE;

                        // Create an Email instance
                        Email email = new SimpleEmail();

                        email.setHostName(hostname);
                        email.setSmtpPort(port);
                        email.setAuthenticator(new DefaultAuthenticator(username, password));
                        email.setStartTLSEnabled(tlsEnabled);
                        email.setFrom(from);
                        email.setSubject(subject);
                        email.setMsg(message);

                        //? ,   
                        for (String addr : to.split(",")) {
                            email.addTo(addr);
                        }

                        //cc  ,   
                        if (cc != null) {
                            for (String addr : cc.split(","))
                                email.addCc(addr);
                        }

                        // Send the email
                        email.send();

                        println("Email about " + name + " sent to [" + to + "] successfully.");
                        Logger.println("Email about " + name + " sent to [" + to + "] successfully.");
                    } catch (Exception e) {
                        println("[? ] : " + e.getMessage());
                        Logger.printStackTrace(e);

                        if (conf._trace) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }
    }
}

From source file:servlets.ConfirmOrderServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  w  w. ja va2 s. com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws org.apache.commons.mail.EmailException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, EmailException {

    HttpSession session = request.getSession();
    Order order = (Order) session.getAttribute("order");
    OrderJdbcDAO dao = new OrderJdbcDAO();
    dao.save(order);

    Customer cust = (Customer) session.getAttribute("customer");

    List<OrderItem> orderItems = order.getItems();

    String customerHeader = "Dear " + cust.getName() + "\n" + "\n";

    String confirm = "This is a confirmation of your order #" + order.getOrderId() + ", processed "
            + order.getDate() + ".\n\n\n";

    String items = "\tYour order contains: \n";
    for (OrderItem orderitems : orderItems) {
        Product product = orderitems.getaProduct();
        items += "\t\t" + product.getName() + ", $" + product.getPrice() + ", quantity: "
                + orderitems.getQuantityPurchased() + ", total: $" + orderitems.getItemTotal() + ".\n";
    }

    String total = "\n\tOrder total: $" + order.getTotal() + "\n\n\n";

    String goodbye = "If you have any questions contact us or send an email to BeautyBox@gmail.com \n"
            + "Beauty Box Crew!";

    String message = customerHeader + confirm + items + total + goodbye;

    String subject = "Beauty Box Order #" + order.getOrderId() + " Confirmation";

    Email email = new SimpleEmail();
    email.setHostName("localhost");
    email.setSmtpPort(2525);
    email.setFrom("BeautyBox@gmail.com");
    email.setSubject(subject);
    email.setMsg(message);
    email.addTo(cust.getEmail());
    email.send();

    session.setAttribute("order", new Order(cust));
    response.sendRedirect("/shopping/restricted/Thanks.jsp");
}

From source file:shnakkydoodle.notifying.endpoints.EmailEndpoint.java

/**
 * Send the notification// w ww  .  j av a2s .co  m
 * 
 * @param recipient
 * @param subject
 * @param message
 * @throws Exception
 */
@Override
public void send(String recipient, String subject, String message) throws Exception {

    Email email = null;

    if (!this.properties.getProperties().containsKey("notification.email.server")
            || !this.properties.getProperties().containsKey("notification.email.port")
            || !this.properties.getProperties().containsKey("notification.email.username")
            || !this.properties.getProperties().containsKey("notification.email.password")
            || !this.properties.getProperties().containsKey("notification.email.fromemail")) {
        throw new Exception("Notification email settings incomplete");
    }

    // Determine if we need to send an html or simple email
    if (message.trim().startsWith("<")) {
        email = new HtmlEmail();
    } else {
        email = new SimpleEmail();
    }

    email.setHostName(this.properties.getProperties().get("notification.email.server").toString());
    email.setSmtpPort(
            Integer.parseInt(this.properties.getProperties().get("notification.email.port").toString()));
    email.setAuthentication(this.properties.getProperties().get("notification.email.username").toString(),
            this.properties.getProperties().get("notification.email.password").toString());
    email.setFrom(this.properties.getProperties().get("notification.email.fromemail").toString());
    email.setSubject(subject);
    email.setMsg(message);
    email.addTo(recipient);
    email.send();
}

From source file:uap.workflow.engine.bpmn.behavior.MailActivityBehavior.java

public void execute(IActivityInstance execution) {
    String toStr = getStringFromField(to, execution);
    String fromStr = getStringFromField(from, execution);
    String ccStr = getStringFromField(cc, execution);
    String bccStr = getStringFromField(bcc, execution);
    String subjectStr = getStringFromField(subject, execution);
    String textStr = getStringFromField(text, execution);
    String htmlStr = getStringFromField(html, execution);
    String charSetStr = getStringFromField(charset, execution);

    Email email = createEmail(textStr, htmlStr);

    addTo(email, toStr);/*from w w  w  . ja va 2  s .c o m*/
    setFrom(email, fromStr);
    addCc(email, ccStr);
    addBcc(email, bccStr);
    setSubject(email, subjectStr);
    setMailServerProperties(email);
    setCharset(email, charSetStr);

    try {
        email.send();
    } catch (EmailException e) {
        throw new WorkflowException("Could not send e-mail", e);
    }
    leave(execution);
}

From source file:velo.ejb.impl.EmailBean.java

public void sendEmailsToApproversGroup(String agUniqueName, String emailTemplateName,
        Map<String, Object> varsMap) throws EmailNotificationException {
    ApproversGroup ag = approversGroupManager.findApproversGroup(agUniqueName);

    if (ag == null) {
        throw new EmailNotificationException("Could not find Approvers Group with name '" + agUniqueName + "'");
    }//from  www  .  j  av  a  2  s . c om

    EmailTemplate et = findEmailTemplate(emailTemplateName);
    if (et == null) {
        throw new EmailNotificationException(
                "Could not find Email Template with name '" + emailTemplateName + "'");
    }

    InitialContext ctx = null;
    TransactionManager tm = null;
    try {
        ctx = new InitialContext();
        tm = (TransactionManager) ctx.lookup("java:/TransactionManager");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
    }

    /*
    try {
      System.out.println("!!!!!!!!!!!!!!!zzzzzzzzzzZ2: " + tm.getStatus());
      System.out.println("!!!!!!!!!!!!!!!Zzzzzzzzzz2: " + tm.getTransaction().getStatus());
    }catch(SystemException e) {
      e.printStackTrace();
    }
    */

    //throw new EmailNotificationException("ERROR ERROR ERROR!");

    et.setContentVars(varsMap);

    EdmEmailSender es = new EdmEmailSender();

    Email email = null;
    try {
        email = es.factoryEmail(et.getSubject(), et.getParsedContent());
        //email.addTo("asaf@mydomain.com");
        //email.send();
    } catch (EmailException e) {
        log.error("Could not factory email objecT: " + e.getMessage());
        throw new EmailNotificationException(e);
    } catch (ExpressionCreationException e) {
        log.error("Could parsing email content: " + e.getMessage());
        throw new EmailNotificationException(e);
    }

    for (User currUser : ag.getApprovers()) {
        try {
            if (Generic.isEmailValid(currUser.getEmail())) {
                email.addTo(currUser.getEmail());
            } else {
                log.warn("The specified email address is not valid, skipping email: " + currUser.getEmail());
            }
        } catch (EmailException e) {
            log.error("Could not send email to user: " + currUser.getName() + " (email address: '"
                    + currUser.getEmail() + "'), part of ApproversGroup '" + ag.getDescription() + "' due to: "
                    + e.getMessage());
        }
    }

    try {
        email.send();
    } catch (EmailException e) {
        throw new EmailNotificationException(e);
    }
}

From source file:velo.ejb.impl.EmailBean.java

public void sendEmailToUser(String userName, String emailTemplateName, Map<String, Object> varsMap)
        throws EmailNotificationException {
    EmailTemplate et = findEmailTemplate(emailTemplateName);
    if (et == null) {
        throw new EmailNotificationException(
                "Could not find Email Template with name '" + emailTemplateName + "'");
    }/*  w w w .  ja  v  a  2  s . c  om*/

    et.setContentVars(varsMap);

    User user = userManager.findUser(userName);

    if (user == null) {
        throw new EmailNotificationException("Could not find User name '" + emailTemplateName + "'");
    }

    EdmEmailSender es = new EdmEmailSender();
    Email email = null;
    try {
        email = es.factoryEmail(et.getSubject(), et.getParsedContent());
    } catch (EmailException e) {
        log.error("Could not factory email objecT: " + e.getMessage());
        throw new EmailNotificationException(e);
    } catch (ExpressionCreationException e) {
        log.error("Could parsing email content: " + e.getMessage());
        throw new EmailNotificationException(e);
    }

    try {
        email.addTo(user.getEmail());
    } catch (EmailException e) {
        log.error("Could not send email to user: " + user.getName() + " (email address: '" + user.getEmail()
                + "')" + "' due to: " + e.getMessage());
    }

    try {
        email.send();
    } catch (EmailException e) {
        throw new EmailNotificationException(e);
    }
}

From source file:velo.tools.EmailSender.java

public void send() {//throws MessagingException {
    log.debug("Sending messages in queue, list now contains: '" + emails.size() + "' emails");

    int failures = 0;
    //List<String> errorMessages = new ArrayList<String>();
    StringBuffer errorMsg = new StringBuffer();

    for (Email currEmail : emails) {
        log.trace("Currently Sending email with subject '" + currEmail.getSubject() + "', please wait...");
        try {//ww w.ja v  a  2 s .c  o  m
            currEmail.send();
            //Transport.send(currMsg);
        } catch (EmailException ee) {
            failures++;
            //errorMessages.add(me.getMessage());
            errorMsg.append(ee.getMessage() + " | ");
        }

        if (failures > 0) {
            //throw new MessagingException("Failed to send '" + failures + "' messages out of '" + emails.size() + "', dumping failure messages: " + errorMsg);
            //TODO: Handle! (Jboss does not know what is MesagingException)
        }
        break;
    }

    if (errorMsg.length() > 0) {
        log.error("An error has occured while trying to send one or more emails: " + errorMsg.toString());
    }
}