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:au.edu.ausstage.utils.EmailManager.java

/**
 * A method for sending a simple email message
 *
 * @param subject the subject of the message
 * @param message the text of the message
 *
 * @return true, if and only if, the email is successfully sent
 *//*from   w w w . j a v  a 2  s. c om*/
public boolean sendSimpleMessage(String subject, String message) {

    // check the input parameters
    if (InputUtils.isValid(subject) == false || InputUtils.isValid(message) == false) {
        throw new IllegalArgumentException("The subject and message parameters cannot be null");
    }

    try {
        // define helper variables
        Email email = new SimpleEmail();

        // configure the instance of the email class
        email.setSmtpPort(options.getPortAsInt());

        // define authentication if required
        if (InputUtils.isValid(options.getUser()) == true) {
            email.setAuthenticator(new DefaultAuthenticator(options.getUser(), options.getPassword()));
        }

        // turn on / off debugging
        email.setDebug(DEBUG);

        // set the host name
        email.setHostName(options.getHost());

        // set the from email address
        email.setFrom(options.getFromAddress());

        // set the subject
        email.setSubject(subject);

        // set the message
        email.setMsg(message);

        // set the to address
        String[] addresses = options.getToAddress().split(":");

        for (int i = 0; i < addresses.length; i++) {
            email.addTo(addresses[i]);
        }

        // set the security options
        if (options.getTLS() == true) {
            email.setTLS(true);
        }

        if (options.getSSL() == true) {
            email.setSSL(true);
        }

        // send the email
        email.send();

    } catch (EmailException ex) {
        if (DEBUG) {
            System.err.println("ERROR: Sending of email failed.\n" + ex.toString());
        }

        return false;
    }
    return true;
}

From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java

/**
 * Send the actual email.//  w ww.  j av a  2 s. co m
 * 
 * @param oid
 * @param from
 * @param recipient
 * @param subject
 * @param body
 * @return
 */
public boolean email(String oid, String from, String recipient, String subject, String body) {
    try {
        Email email = new SimpleEmail();
        log.debug("Email host: " + host);
        log.debug("Email port: " + port);
        log.debug("Email username: " + username);
        log.debug("Email from: " + from);
        log.debug("Email to: " + recipient);
        log.debug("Email Subject is: " + subject);
        log.debug("Email Body is: " + body);
        email.setHostName(host);
        email.setSmtpPort(Integer.parseInt(port));
        email.setAuthenticator(new DefaultAuthenticator(username, password));
        // the method setSSL is deprecated on the newer versions of commons
        // email...
        email.setSSL("true".equalsIgnoreCase(ssl));
        email.setTLS("true".equalsIgnoreCase(tls));
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(body);
        if (recipient.indexOf(",") >= 0) {
            String[] recs = recipient.split(",");
            for (String rec : recs) {
                email.addTo(rec);
            }
        } else {
            email.addTo(recipient);
        }
        email.send();
    } catch (Exception ex) {
        log.debug("Error sending notification mail for oid:" + oid, ex);
        return false;
    }
    return true;
}

From source file:adams.core.net.SimpleApacheSendEmail.java

/**
 * Sends an email.//from w w  w .  j a  va2s.  c o  m
 *
 * @param email   the email to send
 * @return      true if successfully sent
 * @throws Exception   in case of invalid internet addresses or messaging problem
 */
@Override
public boolean sendMail(Email email) throws Exception {
    org.apache.commons.mail.Email mail;
    String id;
    MultiPartEmail mpemail;
    EmailAttachment attachment;

    if (email.getAttachments().length > 0) {
        mail = new MultiPartEmail();
        mpemail = (MultiPartEmail) mail;
        for (File file : email.getAttachments()) {
            attachment = new EmailAttachment();
            attachment.setPath(file.getAbsolutePath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setName(file.getName());
            mpemail.attach(attachment);
        }
    } else {
        mail = new SimpleEmail();
    }
    mail.setFrom(email.getFrom().getValue());
    for (EmailAddress address : email.getTo())
        mail.addTo(address.getValue());
    for (EmailAddress address : email.getCC())
        mail.addCc(address.getValue());
    for (EmailAddress address : email.getBCC())
        mail.addBcc(address.getValue());
    mail.setSubject(email.getSubject());
    mail.setMsg(email.getBody());
    mail.setHostName(m_Server);
    mail.setSmtpPort(m_Port);
    mail.setStartTLSEnabled(m_UseTLS);
    mail.setSSLOnConnect(m_UseSSL);
    if (m_RequiresAuth)
        mail.setAuthentication(m_User, m_Password.getValue());
    mail.setSocketTimeout(m_Timeout);
    try {
        id = mail.send();
        if (isLoggingEnabled())
            getLogger().info("Message sent: " + id);
    } catch (Exception e) {
        getLogger().log(Level.SEVERE, "Failed to send email: " + mail, e);
        return false;
    }

    return true;
}

From source file:net.scran24.user.server.services.HelpServiceImpl.java

@Override
public void reportUncaughtException(String strongName, List<String> classNames, List<String> messages,
        List<StackTraceElement[]> stackTraces, String surveyState) {
    Subject subject = SecurityUtils.getSubject();
    ScranUserId userId = (ScranUserId) subject.getPrincipal();

    if (userId == null)
        throw new RuntimeException("User must be logged in");

    String rateKey = userId.survey + "#" + userId.username;
    RateInfo rateInfo = rateMap.get(rateKey);

    boolean rateExceeded = false;

    long time = System.currentTimeMillis();

    if (rateInfo == null) {
        rateMap.put(rateKey, new RateInfo(1, time));
    } else {/*from   w ww  . j  ava 2s .  co  m*/
        long timeSinceLastRequest = time - rateInfo.lastRequestTime;

        if (timeSinceLastRequest > 10000) {
            rateMap.put(rateKey, new RateInfo(1, time));
        } else if (rateInfo.requestCount >= 10) {
            rateExceeded = true;
        } else {
            rateMap.put(rateKey, new RateInfo(rateInfo.requestCount + 1, time));
        }
    }

    if (!rateExceeded) {
        System.out.println(String.format("Sending email", userId.survey, userId.username));

        Email email = new SimpleEmail();

        email.setHostName(smtpHostName);
        email.setSmtpPort(smtpPort);
        email.setCharset(EmailConstants.UTF_8);
        email.setAuthenticator(new DefaultAuthenticator(smtpUserName, smtpPassword));
        email.setSSLOnConnect(true);

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < classNames.size(); i++) {
            sb.append(String.format("%s: %s\n", classNames.get(i), messages.get(i)));

            StackTraceElement[] deobfStackTrace = deobfuscator.resymbolize(stackTraces.get(i), strongName);

            for (StackTraceElement ste : deobfStackTrace) {
                sb.append(String.format("  %s\n", ste.toString()));
            }
            sb.append("\n");
        }

        sb.append("Survey state:\n");
        sb.append(surveyState);
        sb.append("\n");

        try {
            email.setFrom("no-reply@intake24.co.uk", "Intake24");
            email.setSubject(String.format("Client exception (%s/%s): %s", userId.survey, userId.username,
                    messages.get(0)));

            email.setMsg(sb.toString());

            email.addTo("bugs@intake24.co.uk");

            email.send();
        } catch (EmailException ee) {
            log.error("Failed to send e-mail notification", ee);
        }
    }

}

From source file:com.pkrete.locationservice.endpoint.mailer.impl.EmailServiceImpl.java

/**
 * Sends the given EmailMessage to the recipients defined in the message.
 * Returns true if and only if the message was successfully sent to all the
 * recipients; otherwise false.//from ww w  .jav a 2  s. c o  m
 *
 * @param message email message to be sent
 * @return true if and only if the message was successfully sent to all the
 * recipients; otherwise false
 */
@Override
public boolean send(EmailMessage message) {
    if (message == null) {
        logger.warn("Message cannot be null.");
        return false;
    }
    logger.debug("Create new \"{}\" email message.", message.getType().toString());

    if (message.getRecipients().isEmpty()) {
        logger.info("No recipients defined. Nothing to do -> exit.");
        return false;
    }
    Email email = new SimpleEmail();
    email.setHostName(PropertiesUtil.getProperty("mail.host"));
    email.setSmtpPort(this.converterService.strToInt(PropertiesUtil.getProperty("mail.port")));
    email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getProperty("mail.user"),
            PropertiesUtil.getProperty("mail.password")));
    email.setTLS(true);
    try {
        // Set from address
        email.setFrom(message.getFrom());
        // Set subject
        email.setSubject(message.getSubject());

        // Build message body
        StringBuilder body = new StringBuilder();
        if (!message.getHeader().isEmpty()) {
            body.append(message.getHeader()).append("\n\n");
        }
        if (!message.getMessage().isEmpty()) {
            body.append(message.getMessage()).append("\n\n");
        }
        if (!message.getFooter().isEmpty()) {
            body.append(message.getFooter()).append("\n\n");
        }
        if (!message.getSignature().isEmpty()) {
            body.append(message.getSignature()).append("\n\n");
        }

        // Set message contents
        email.setMsg(body.toString());

        // Add message receivers
        for (String recipient : message.getRecipients()) {
            logger.info("Add recipient \"{}\".", recipient);
            email.addTo(recipient);
        }

        // Send message
        email.send();

        logger.info("Email was succesfully sent to {} recipients.", message.getRecipients().size());
    } catch (Exception e) {
        logger.error("Failed to send \"{}\" email message.", message.getType().toString());
        logger.error(e.getMessage());
        return false;
    }
    return true;
}

From source file:com.cws.esolutions.security.quartz.PasswordExpirationNotifier.java

/**
 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
 *//*from  w w w .j  a va  2 s. c  om*/
public void execute(final JobExecutionContext context) {
    final String methodName = PasswordExpirationNotifier.CNAME
            + "#execute(final JobExecutionContext jobContext)";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("JobExecutionContext: {}", context);
    }

    final Map<String, Object> jobData = context.getJobDetail().getJobDataMap();

    if (DEBUG) {
        DEBUGGER.debug("jobData: {}", jobData);
    }

    try {
        UserManager manager = UserManagerFactory
                .getUserManager(bean.getConfigData().getSecurityConfig().getUserManager());

        if (DEBUG) {
            DEBUGGER.debug("UserManager: {}", manager);
        }

        List<String[]> accounts = manager.listUserAccounts();

        if (DEBUG) {
            DEBUGGER.debug("accounts: {}", accounts);
        }

        if ((accounts == null) || (accounts.size() == 0)) {
            return;
        }

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 30);
        Long expiryTime = cal.getTimeInMillis();

        if (DEBUG) {
            DEBUGGER.debug("Calendar: {}", cal);
            DEBUGGER.debug("expiryTime: {}", expiryTime);
        }

        for (String[] account : accounts) {
            if (DEBUG) {
                DEBUGGER.debug("Account: {}", (Object) account);
            }

            List<Object> accountDetail = manager.loadUserAccount(account[0]);

            if (DEBUG) {
                DEBUGGER.debug("List<Object>: {}", accountDetail);
            }

            try {
                Email email = new SimpleEmail();
                email.setHostName((String) jobData.get("mailHost"));
                email.setSmtpPort(Integer.parseInt((String) jobData.get("portNumber")));

                if ((Boolean) jobData.get("isSecure")) {
                    email.setSSLOnConnect(true);
                }

                if ((Boolean) jobData.get("isAuthenticated")) {
                    email.setAuthenticator(new DefaultAuthenticator((String) jobData.get("username"),
                            PasswordUtils.decryptText((String) (String) jobData.get("password"),
                                    (String) jobData.get("salt"), secConfig.getSecretAlgorithm(),
                                    secConfig.getIterations(), secConfig.getKeyBits(),
                                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                                    systemConfig.getEncoding())));
                }

                email.setFrom((String) jobData.get("emailAddr"));
                email.addTo((String) accountDetail.get(6));
                email.setSubject((String) jobData.get("messageSubject"));
                email.setMsg(String.format((String) jobData.get("messageBody"), (String) accountDetail.get(4)));

                if (DEBUG) {
                    DEBUGGER.debug("SimpleEmail: {}", email);
                }

                email.send();
            } catch (EmailException ex) {
                ERROR_RECORDER.error(ex.getMessage(), ex);
            } catch (SecurityException sx) {
                ERROR_RECORDER.error(sx.getMessage(), sx);
            }
        }
    } catch (UserManagementException umx) {
        ERROR_RECORDER.error(umx.getMessage(), umx);
    }
}

From source file:com.mirth.connect.server.util.ServerSMTPConnection.java

public void send(String toList, String ccList, String from, String subject, String body, String charset)
        throws EmailException {
    Email email = new SimpleEmail();

    // Set the charset if it was specified. Otherwise use the system's default.
    if (StringUtils.isNotBlank(charset)) {
        email.setCharset(charset);//from   ww w  .  j av  a 2 s  .  com
    }

    email.setHostName(host);
    email.setSmtpPort(Integer.parseInt(port));
    email.setSocketConnectionTimeout(socketTimeout);
    email.setDebug(true);

    if (useAuthentication) {
        email.setAuthentication(username, password);
    }

    if (StringUtils.equalsIgnoreCase(secure, "TLS")) {
        email.setStartTLSEnabled(true);
    } else if (StringUtils.equalsIgnoreCase(secure, "SSL")) {
        email.setSSLOnConnect(true);
        email.setSslSmtpPort(port);
    }

    // These have to be set after the authenticator, so that a new mail session isn't created
    ConfigurationController configurationController = ControllerFactory.getFactory()
            .createConfigurationController();
    email.getMailSession().getProperties().setProperty("mail.smtp.ssl.protocols", StringUtils.join(
            MirthSSLUtil.getEnabledHttpsProtocols(configurationController.getHttpsClientProtocols()), ' '));
    email.getMailSession().getProperties().setProperty("mail.smtp.ssl.ciphersuites", StringUtils.join(
            MirthSSLUtil.getEnabledHttpsCipherSuites(configurationController.getHttpsCipherSuites()), ' '));

    for (String to : StringUtils.split(toList, ",")) {
        email.addTo(to);
    }

    if (StringUtils.isNotEmpty(ccList)) {
        for (String cc : StringUtils.split(ccList, ",")) {
            email.addCc(cc);
        }
    }

    email.setFrom(from);
    email.setSubject(subject);
    email.setMsg(body);
    email.send();
}

From source file:com.gst.infrastructure.core.service.GmailBackedPlatformEmailService.java

@Override
public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) {
    final Email email = new SimpleEmail();
    final SMTPCredentialsData smtpCredentialsData = this.externalServicesReadPlatformService
            .getSMTPCredentials();/*from  w ww  .  j a  va2 s.c  o m*/
    final String authuserName = smtpCredentialsData.getUsername();

    final String authuser = smtpCredentialsData.getUsername();
    final String authpwd = smtpCredentialsData.getPassword();

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(false); // true if you want to debug
    email.setHostName(smtpCredentialsData.getHost());
    try {
        if (smtpCredentialsData.isUseTLS()) {
            email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        }
        email.setFrom(authuser, authuserName);

        final StringBuilder subjectBuilder = new StringBuilder().append("Welcome ")
                .append(emailDetail.getContactName()).append(" to ").append(emailDetail.getOrganisationName());

        email.setSubject(subjectBuilder.toString());

        final String sendToEmail = emailDetail.getAddress();

        final StringBuilder messageBuilder = new StringBuilder()
                .append("You are receiving this email as your email account: ").append(sendToEmail)
                .append(" has being used to create a user account for an organisation named [")
                .append(emailDetail.getOrganisationName()).append("] on Mifos.\n")
                .append("You can login using the following credentials:\nusername: ")
                .append(emailDetail.getUsername()).append("\n").append("password: ").append(unencodedPassword)
                .append("\n")
                .append("You must change this password upon first log in using Uppercase, Lowercase, number and character.\n")
                .append("Thank you and welcome to the organisation.");

        email.setMsg(messageBuilder.toString());

        email.addTo(sendToEmail, emailDetail.getContactName());
        email.send();
    } catch (final EmailException e) {
        throw new PlatformEmailSendException(e);
    }
}

From source file:FacultyAdvisement.SignupBean.java

public String validateSignUp(ArrayList<Course> list, Appointment appointment)
        throws SQLException, IOException, EmailException {

    if (this.desiredCoureses == null || this.desiredCoureses.size() < 1) {
        FacesContext.getCurrentInstance().addMessage("desiredCourses:Submit",
                new FacesMessage(FacesMessage.SEVERITY_FATAL,
                        "Please select some courses before confirming an appointment.", null));

    }/* ww w . j  a  va2  s  . c o  m*/
    for (int i = 0; i < list.size(); i++) {
        if (!this.checkRequsites(CourseRepository.readCourseWithRequisites(ds, list.get(i)))) {
            return null;

        }
    }

    try {
        DesiredCourseRepository.deleteFromAppointment(ds, this.appointment.aID);
    } catch (SQLException ex) {
        Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
    }

    DesiredCourseRepository.createDesiredCourses(ds, desiredCoureses, Long.toString(appointment.aID));

    if (!this.edit) {
        try {
            Email email = new HtmlEmail();
            email.setHostName("smtp.googlemail.com");
            email.setSmtpPort(465);
            email.setAuthenticator(new DefaultAuthenticator("uco.faculty.advisement", "!@#$1234"));
            email.setSSLOnConnect(true);
            email.setFrom("uco.faculty.advisement@gmail.com");
            email.setSubject("UCO Faculty Advisement Appointmen Confirmation");

            StringBuilder table = new StringBuilder();
            table.append("<style>" + "td" + "{border-left:1px solid black;" + "border-top:1px solid black;}"
                    + "table" + "{border-right:1px solid black;" + "border-bottom:1px solid black;}"
                    + "</style>");
            table.append(
                    "<table><tr><td  width=\"350\">Course Name</td><td  width=\"350\">Course Subject</td><td  width=\"350\">Course Number</td><td  width=\"350\">Course Credits</td></tr> </table>");
            for (int i = 0; i < this.desiredCoureses.size(); i++) {
                table.append("<tr><td   width=\"350\">" + this.desiredCoureses.get(i).getName() + "</td>"
                        + "<td   width=\"350\">" + this.desiredCoureses.get(i).getSubject() + "</td>"
                        + "<td   width=\"350\">" + this.desiredCoureses.get(i).getNumber() + "</td>"
                        + "<td   width=\"350\">" + this.desiredCoureses.get(i).getCredits() + "</td></tr>"

                );

            }

            email.setMsg("<p>Your appointment with your faculty advisor is at " + appointment.datetime + " on "
                    + appointment.date + " . </p>" + "<p align=\"center\">Desired Courses</p>"
                    + table.toString() + "<p align=\"center\">UCO Faculty Advisement</p></font>"

            );
            email.addTo(username);
            email.send();
        } catch (EmailException ex) {
            Logger.getLogger(VerificationBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return "/customerFolder/profile.xhtml";
}

From source file:JavaMail.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {/*  w w w. j av  a  2  s .com*/
        String from = jTextField1.getText();
        String to = jTextField2.getText();
        String subject = jTextField3.getText();
        String content = jTextArea1.getText();
        Email email = new SimpleEmail();
        String provi = prov.getSelectedItem().toString();
        if (provi.equals("Gmail")) {
            email.setHostName("smtp.gmail.com");
            email.setSmtpPort(465);
            serverlink = "smtp.gmail.com";
            serverport = 465;
        }
        if (provi.equals("Outlook")) {
            email.setHostName("smtp-mail.outlook.com");
            serverlink = "smtp-mail.outlook.com";
            email.setSmtpPort(25);
            serverport = 25;
        }
        if (provi.equals("Yahoo")) {
            email.setHostName("smtp.mail.yahoo.com");
            serverlink = "smtp.mail.yahoo.com";
            email.setSmtpPort(465);
            serverport = 465;
        }
        System.out.println("Initializing email sending sequence");
        System.out.println("Connecting to " + serverlink + " at port " + serverport);
        JPanel panel = new JPanel();
        JLabel label = new JLabel(
                "Enter the password of your email ID to connect with your Email provider." + "\n");
        JPasswordField pass = new JPasswordField(10);
        panel.add(label);
        panel.add(pass);
        String[] options = new String[] { "OK", "Cancel" };
        int option = JOptionPane.showOptionDialog(null, panel, "Enter Email ID Password", JOptionPane.NO_OPTION,
                JOptionPane.PLAIN_MESSAGE, null, options, options[1]);
        if (option == 0) // pressing OK button
        {
            char[] password = pass.getPassword();
            emailpass = new String(password);
        }
        email.setAuthenticator(new DefaultAuthenticator(from, emailpass));
        email.setSSLOnConnect(true);
        if (email.isSSLOnConnect() == true) {
            System.out.println("This server requires SSL/TLS authentication.");
        }
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(content);
        email.addTo(to);
        email.send();
        JOptionPane.showMessageDialog(null, "Message sent successfully.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}