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

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

Introduction

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

Prototype

public void setAuthenticator(final Authenticator newAuthenticator) 

Source Link

Document

Sets the Authenticator to be used when authentication is requested from the mail server.

Usage

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));

    }/*www  .ja v  a2  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:egovframework.rte.tex.com.service.impl.EgovMailServiceImpl.java

/**
 * ?   ?? ?? ./*from w ww.  j  av  a2 s  .  c  o m*/
 * @param vo ?
 * @return ? 
 */
@Override
@SuppressWarnings("deprecation")
public boolean sendEmailTo(MemberVO vo) {
    boolean result = false;

    Email email = new SimpleEmail();

    email.setCharset("utf-8"); //  ?

    // setHostName?  ?
    // email.setHostName(mailInfoService.getString("hostName"));  // SpEL?  properties ? 
    email.setHostName(hostName); // SMTP 
    email.setSmtpPort(port);
    email.setAuthenticator(new DefaultAuthenticator(mailId, mailPass));
    email.setTLS(true);
    try {
        email.addTo(vo.getEmail(), vo.getId()); // ? 
    } catch (EmailException e) {
        e.printStackTrace();
    }
    try {
        email.setFrom(mailId, mailName); //  
    } catch (EmailException e) {
        e.printStackTrace();
    }
    email.setSubject(subject); // ? 
    email.setContent("ID: " + vo.getId() + "<br>" + "PASSWORD: " + vo.getPassword(),
            "text/plain; charset=utf-8");
    try {
        email.send();
        result = true;
    } catch (EmailException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:json.JsonUI.java

public void enviandoEmail() {
    Properties login = new Properties();
    String properties = "json/login.properties";
    try {//from  w ww .java2s.c o m
        InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(properties);
        login.load(stream);
    } catch (IOException ex) {
        System.out.println("Erro: " + ex.getMessage());
    }
    String username = login.getProperty("hotmail.username");
    String password = login.getProperty("hotmail.password");

    try {
        Email email = new SimpleEmail();
        email.setHostName("smtp.live.com");
        email.setSmtpPort(587);
        email.setStartTLSRequired(true);
        email.setAuthenticator(new DefaultAuthenticator(username, password));
        email.setFrom(username);
        email.setSubject(assuntoEmail.getText());
        email.setMsg(jTextAreaMsgEmail.getText());
        email.addTo(emailDestino.getText());
        email.setDebug(true);
        email.send();
        aviso.setText("Mensagem enviada.");
    } catch (EmailException ex) {
        System.out.println("Erro: " + ex.getMessage());
    }

}

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  va  2s  .co  m
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.patrolpro.beans.ContactUsBean.java

public String sendEmail() {
    try {/*from  ww  w .  j a  v  a2s . c om*/
        StringBuilder emailMessage = new StringBuilder();
        emailMessage.append("From: " + this.name + "\r\n");
        emailMessage.append("Email: " + this.email + "\r\n");
        emailMessage.append("Phone: " + this.phone + "\r\n");
        emailMessage.append(message);

        Email htmlEmail = new SimpleEmail();
        htmlEmail.setMsg(message);
        htmlEmail.setFrom("contact@patrolpro.com");
        htmlEmail.setSubject("Contact Us Email");
        htmlEmail.addTo("rharris@ainteractivesolution.com");
        htmlEmail.addCc("ijuneau@ainteractivesolution.com");
        htmlEmail.addCc("jc@champ.net");
        htmlEmail.setMsg(emailMessage.toString());

        htmlEmail.setAuthenticator(new MailAuthenticator("schedfox", "Sch3dF0x4m3"));
        htmlEmail.setHostName("mail2.champ.net");
        htmlEmail.setSmtpPort(587);
        htmlEmail.send();
        return "sentContactEmail";
    } catch (Exception exe) {

    }
    return "invalid";
}

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 {// w w w  .ja  va2 s  .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.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  w  w. ja  v a2 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:iddb.core.util.MailManager.java

private void setEmailProps(Email email) throws EmailException {
    email.setFrom(props.getProperty("from"), "IPDB");
    if (props.containsKey("bounce"))
        email.setBounceAddress(props.getProperty("bounce"));
    if (props.containsKey("host"))
        email.setHostName(props.getProperty("host"));
    if (props.containsKey("port"))
        email.setSmtpPort(Integer.parseInt(props.getProperty("port")));
    if (props.containsKey("username"))
        email.setAuthenticator(
                new DefaultAuthenticator(props.getProperty("username"), props.getProperty("password")));
    if (props.containsKey("ssl") && props.getProperty("ssl").equalsIgnoreCase("true"))
        email.setSSL(true);/* w  ww .j  a  v a 2  s  .  com*/
    if (props.containsKey("tls") && props.getProperty("tls").equalsIgnoreCase("true"))
        email.setTLS(true);
    if (props.containsKey("debug") && props.getProperty("debug").equalsIgnoreCase("true"))
        email.setDebug(true);
}

From source file:com.irurueta.server.commons.email.ApacheMailSender.java

/**
 * Internal method to send email using Apache Mail.
 * @param m email message./*  w w w  . j  a v a  2 s .  c om*/
 * @param email apache email message.
 * @throws NotSupportedException if feature is not supported.
 * @throws EmailException if Apache Mail cannot send email.
 * @throws com.irurueta.server.commons.email.EmailException if sending
 * email fails.
 */
private void internalSendApacheEmail(EmailMessage m, Email email)
        throws NotSupportedException, EmailException, com.irurueta.server.commons.email.EmailException {
    email.setHostName(mMailHost);
    email.setSmtpPort(mMailPort);
    if (mMailId != null && !mMailId.isEmpty() && mMailPassword != null && !mMailPassword.isEmpty()) {
        email.setAuthenticator(new DefaultAuthenticator(mMailId, mMailPassword));
    }
    email.setStartTLSEnabled(true);
    email.setFrom(mMailFromAddress);
    if (m.getSubject() != null) {
        email.setSubject(m.getSubject());
    }
    m.buildContent(email);

    //add destinatoins
    for (String s : (List<String>) m.getTo()) {
        email.addTo(s);
    }

    for (String s : (List<String>) m.getCC()) {
        email.addCc(s);
    }

    for (String s : (List<String>) m.getBCC()) {
        email.addBcc(s);
    }

    email.send();
}

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

/**
 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
 *//*from w  ww.jav a2 s .c o m*/
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);
    }
}