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

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

Introduction

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

Prototype

public Email setSSLOnConnect(final boolean ssl) 

Source Link

Document

Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS).

Usage

From source file:com.northernwall.hadrian.workItem.email.EmailWorkItemSender.java

private void emailWorkItem(String subject, String body) {
    try {//from  ww w.j av  a  2s.c o m
        if (emailTos.isEmpty()) {
            return;
        }
        Email email = new SimpleEmail();
        if (smtpHostname != null) {
            email.setHostName(smtpHostname);
        }
        email.setSmtpPort(smtpPort);
        if (smtpUsername != null && smtpPassword != null) {
            email.setAuthenticator(new DefaultAuthenticator(smtpUsername, smtpPassword));
        }
        email.setSSLOnConnect(smtpSsl);
        email.setFrom(emailFrom);
        email.setSubject(subject);
        email.setMsg(body);
        for (String emailTo : emailTos) {
            email.addTo(emailTo);
        }
        email.send();

        if (emailTos.size() == 1) {
            logger.info("Emailing work item to {} with subject {}", emailTos.get(0), subject);
        } else {
            logger.info("Emailing work item to {} and {} other email addresses with subject {}",
                    emailTos.get(0), (emailTos.size() - 1), subject);
        }
    } catch (EmailException ex) {
        throw new RuntimeException("Failure emailing work item, {}", ex);
    }
}

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

    }/* w w w  .j  av 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: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  .j av  a  2s  . c om
        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.neu.controller.MessageController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource");

    String action = request.getParameter("action");
    ModelAndView mv = new ModelAndView();

    HttpSession session = request.getSession();
    String userName = (String) session.getAttribute("userName");

    if (action.equalsIgnoreCase("reply")) {

        try {//from ww w.  ja  v a2s . c o m

            String receiver = request.getParameter("to");
            System.out.println("Printing receiver in reply case: " + receiver);

            QueryRunner run = new QueryRunner(ds);
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            UsersBean ub = run.query("select * from userstable where userName =?", user, receiver);
            if (ub != null) {
                System.out.println("printing userEmail received from DB: " + ub.getUserEmail());

                mv.addObject("toEmail", ub.getUserEmail());
                mv.addObject("to", receiver);
            }

            mv.setViewName("reply");

        } catch (SQLException e) {
            System.out.println(e);

        }

    } else if (action.equalsIgnoreCase("sent")) {
        System.out.println("In sent case");

        try {
            String receiver = request.getParameter("to");
            String receiverEmail = request.getParameter("toEmail");

            System.out.println("printing receiver email: " + receiverEmail);

            QueryRunner run = new QueryRunner(ds);
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            UsersBean ub = run.query("select * from userstable where userName =?", user, userName);
            if (ub != null) {
                String senderEmail = ub.getUserEmail();
                System.out.println("printing senderemail: " + senderEmail);

                ResultSetHandler<MessageBean> msg = new BeanHandler<MessageBean>(MessageBean.class);
                Object[] params = new Object[4];
                params[0] = userName;
                params[1] = request.getParameter("message");
                Date d = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                String messageDate = format.format(d);
                params[2] = messageDate;
                params[3] = receiver;
                int inserts = run.update(
                        "Insert into messages (fromUser,message,messageDate,userName) values(?,?,?,?)", params);//Logic to send the email

                try {
                    Email email = new SimpleEmail();
                    email.setHostName("smtp.googlemail.com");//If a server is capable of sending email, then you don't need the authentication. In this case, an email server needs to be running on that machine. Since we are running this application on the localhost and we don't have a email server, we are simply asking gmail to relay this email.
                    email.setSmtpPort(465);
                    email.setAuthenticator(
                            new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc"));
                    email.setSSLOnConnect(true);
                    email.setFrom(senderEmail);//This email will appear in the from field of the sending email. It doesn't have to be a real email address.This could be used for phishing/spoofing!
                    email.setSubject("Thanks for Signing Up!");
                    email.setMsg("Welcome to Web tools Lab 5 Spring Application sign up email test!");
                    email.addTo(receiverEmail);//Will come from the database
                    email.send();
                } catch (Exception e) {
                    System.out.println("Email Exception" + e.getMessage());
                    e.printStackTrace();
                }
                mv.setViewName("messageSent");
            } else {
                mv.addObject("error", "true");
                mv.setViewName("index");

            }

        } catch (Exception ex) {
            System.out.println("Error Message" + ex.getMessage());
            ex.printStackTrace();

        }

    }

    return mv;
}

From source file:com.neu.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource");

    String action = request.getParameter("action");
    ModelAndView mv = new ModelAndView();

    HttpSession session = request.getSession();

    if (action.equalsIgnoreCase("login")) {
        try {/* w  w  w .  j  a v a  2  s  . c om*/
            String userName = request.getParameter("user");
            String password = request.getParameter("password");
            QueryRunner run = new QueryRunner(ds);
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            Object[] params = new Object[2];
            params[0] = userName;
            params[1] = password;
            UsersBean ub = run.query("select * from userstable where userName =? and userPassword=?", user,
                    params);
            if (ub != null) {
                ResultSetHandler<List<MessageBean>> messages = new BeanListHandler<MessageBean>(
                        MessageBean.class);
                List<MessageBean> msg = run.query("select * from messages where userName =?", messages,
                        userName);
                session.setAttribute("userName", userName);
                session.setAttribute("messageList", msg);
                mv.setViewName("userhome");
            } else {
                mv.addObject("error", "true");
                mv.setViewName("index");

            }

        } catch (Exception ex) {
            System.out.println("Error Message" + ex.getMessage());

        }

    } else if (action.equalsIgnoreCase("logout")) {

        session.invalidate();
        mv.setViewName("index");
    } else if (action.equalsIgnoreCase("signup")) {

        System.out.println("sign up");
        //                
        //                String userName = request.getParameter("user");
        //                String password = request.getParameter("password");
        //                String emailObj = request.getParameter("emailObj");
        //                
        // System.out.println("printing details: " + userName + " " +password + " "+emailObj);
        mv.setViewName("signup");
    } else if (action.equalsIgnoreCase("signupsubmit")) {

        System.out.println("sign up submit");

        String userName = request.getParameter("user");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        System.out.println("printing details: " + userName + " " + password + " " + email);

        if (userName.equals("") || (password.equals("")) || (email.equals(""))) {
            System.out.println("empty values");
            mv.addObject("error", "true");
        }

        else {
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            Object[] params = new Object[3];
            params[0] = userName;
            params[1] = password;
            params[2] = email;
            QueryRunner run = new QueryRunner(ds);
            int inserts = run.update("insert into userstable (UserName,UserPassword,UserEmail) values (?,?,?)",
                    params);//Logic to insert into table
            System.out.println("inserts value " + inserts);

            if (inserts > 0) {
                mv.addObject("success", "true");
                Email emailObj = new SimpleEmail();
                emailObj.setHostName("smtp.googlemail.com");//If a server is capable of sending emailObj, then you don't need the authentication. In this case, an emailObj server needs to be running on that machine. Since we are running this application on the localhost and we don't have a emailObj server, we are simply asking gmail to relay this emailObj.
                emailObj.setSmtpPort(465);
                emailObj.setAuthenticator(
                        new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc"));
                emailObj.setSSLOnConnect(true);
                emailObj.setFrom("webtools@hello.com");//This emailObj will appear in the from field of the sending emailObj. It doesn't have to be a real emailObj address.This could be used for phishing/spoofing!
                emailObj.setSubject("TestMail");
                emailObj.setMsg("This is spring MVC Contact Application sending you the email");
                emailObj.addTo(email);//Will come from the sign up details
                emailObj.send();
            }

        }

        mv.setViewName("signup");
    }

    return mv;
}

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);//  ww w . j  a  va 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:adams.core.net.SimpleApacheSendEmail.java

/**
 * Sends an email.//from   w  w w  .  ja  va 2  s .  co 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:com.aurel.track.util.emailHandling.MailSender.java

private Email setSecurityMode(Email email) {
    Integer smtpSecurity = smtpMailSettings.getSecurity();
    String oldTrustStore = (String) System.clearProperty("javax.net.ssl.trustStore");
    LOGGER.debug("oldTrustStore=" + oldTrustStore);
    switch (smtpSecurity) {
    case TSiteBean.SECURITY_CONNECTIONS_MODES.NEVER:
        LOGGER.debug("SMTP security connection mode is NEVER");
        break;/*from w  ww .j  a v  a 2 s  .c  o  m*/
    case TSiteBean.SECURITY_CONNECTIONS_MODES.TLS_IF_AVAILABLE:
        LOGGER.debug("SMTP security connection mode is TLS_IF_AVAILABLE");
        email.setStartTLSEnabled(true);
        MailBL.setTrustKeyStore(smtpMailSettings.getHost());
        break;
    case TSiteBean.SECURITY_CONNECTIONS_MODES.TLS:
        LOGGER.debug("SMTP security connection mode is TLS");
        email.setStartTLSEnabled(true);
        email.setStartTLSRequired(true);
        MailBL.setTrustKeyStore(smtpMailSettings.getHost());
        break;
    case TSiteBean.SECURITY_CONNECTIONS_MODES.SSL: {
        LOGGER.debug("SMTP security connection mode is SSL");
        MailBL.setTrustKeyStore(smtpMailSettings.getHost());
        email.setSSLOnConnect(true);
        break;
    }
    default:
        break;
    }
    return email;
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

@Override
public ConnectionTestResponse sendTestEmail(Properties properties) throws Exception {
    String portString = properties.getProperty("port");
    String encryption = properties.getProperty("encryption");
    String host = properties.getProperty("host");
    String timeoutString = properties.getProperty("timeout");
    Boolean authentication = Boolean.parseBoolean(properties.getProperty("authentication"));
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");
    String to = properties.getProperty("toAddress");
    String from = properties.getProperty("fromAddress");

    int port = -1;
    try {//from  ww w.  ja v a2 s  .  co m
        port = Integer.parseInt(portString);
    } catch (NumberFormatException e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                "Invalid port: \"" + portString + "\"");
    }

    Email email = new SimpleEmail();
    email.setDebug(true);
    email.setHostName(host);
    email.setSmtpPort(port);

    try {
        int timeout = Integer.parseInt(timeoutString);
        email.setSocketTimeout(timeout);
        email.setSocketConnectionTimeout(timeout);
    } catch (NumberFormatException e) {
        // Don't set if the value is invalid
    }

    if ("SSL".equalsIgnoreCase(encryption)) {
        email.setSSLOnConnect(true);
        email.setSslSmtpPort(portString);
    } else if ("TLS".equalsIgnoreCase(encryption)) {
        email.setStartTLSEnabled(true);
    }

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

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

    SSLSocketFactory socketFactory = (SSLSocketFactory) properties.get("socketFactory");
    if (socketFactory != null) {
        email.getMailSession().getProperties().put("mail.smtp.ssl.socketFactory", socketFactory);
        if ("SSL".equalsIgnoreCase(encryption)) {
            email.getMailSession().getProperties().put("mail.smtp.socketFactory", socketFactory);
        }
    }

    email.setSubject("Mirth Connect Test Email");

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

        email.setFrom(from);
        email.setMsg(
                "Receipt of this email confirms that mail originating from this Mirth Connect Server is capable of reaching its intended destination.\n\nSMTP Configuration:\n- Host: "
                        + host + "\n- Port: " + port);

        email.send();
        return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS,
                "Sucessfully sent test email to: " + to);
    } catch (EmailException e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, e.getMessage());
    }
}

From source file:JavaMail.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {/*from   w w  w  . j  a v  a 2 s  .  c o m*/
        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();
    }

}