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

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

Introduction

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

Prototype

public Email setFrom(final String email) throws EmailException 

Source Link

Document

Set the FROM field of the email to use the specified address.

Usage

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.ja  va 2 s.  c  om*/
        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();
    }

}

From source file:com.day.cq.wcm.foundation.forms.impl.MailServlet.java

/**
 * @see org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
 *//*from   w  w  w.j a v  a 2 s .  c  om*/
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    final MailService localService = this.mailService;
    if (ResourceUtil.isNonExistingResource(request.getResource())) {
        logger.debug("Received fake request!");
        response.setStatus(500);
        return;
    }
    final ResourceBundle resBundle = request.getResourceBundle(null);

    final ValueMap values = ResourceUtil.getValueMap(request.getResource());
    final String[] mailTo = values.get(MAILTO_PROPERTY, String[].class);
    int status = 200;
    if (mailTo == null || mailTo.length == 0 || mailTo[0].length() == 0) {
        // this is a sanity check
        logger.error(
                "The mailto configuration is missing in the form begin at " + request.getResource().getPath());

        status = 500;
    } else if (localService == null) {
        logger.error("The mail service is currently not available! Unable to send form mail.");

        status = 500;
    } else {
        try {
            final StringBuilder builder = new StringBuilder();
            builder.append(request.getScheme());
            builder.append("://");
            builder.append(request.getServerName());
            if ((request.getScheme().equals("https") && request.getServerPort() != 443)
                    || (request.getScheme().equals("http") && request.getServerPort() != 80)) {
                builder.append(':');
                builder.append(request.getServerPort());
            }
            builder.append(request.getRequestURI());

            // construct msg
            final StringBuilder buffer = new StringBuilder();
            String text = resBundle.getString("You've received a new form based mail from {0}.");
            text = text.replace("{0}", builder.toString());
            buffer.append(text);
            buffer.append("\n\n");
            buffer.append(resBundle.getString("Values"));
            buffer.append(":\n\n");
            // we sort the names first - we use the order of the form field and
            // append all others at the end (for compatibility)

            // let's get all parameters first and sort them alphabetically!
            final List<String> contentNamesList = new ArrayList<String>();
            final Iterator<String> names = FormsHelper.getContentRequestParameterNames(request);
            while (names.hasNext()) {
                final String name = names.next();
                contentNamesList.add(name);
            }
            Collections.sort(contentNamesList);

            final List<String> namesList = new ArrayList<String>();
            final Iterator<Resource> fields = FormsHelper.getFormElements(request.getResource());
            while (fields.hasNext()) {
                final Resource field = fields.next();
                final FieldDescription[] descs = FieldHelper.getFieldDescriptions(request, field);
                for (final FieldDescription desc : descs) {
                    // remove from content names list
                    contentNamesList.remove(desc.getName());
                    if (!desc.isPrivate()) {
                        namesList.add(desc.getName());
                    }
                }
            }
            namesList.addAll(contentNamesList);

            // now add form fields to message
            // and uploads as attachments
            final List<RequestParameter> attachments = new ArrayList<RequestParameter>();
            for (final String name : namesList) {
                final RequestParameter rp = request.getRequestParameter(name);
                if (rp == null) {
                    //see Bug https://bugs.day.com/bugzilla/show_bug.cgi?id=35744
                    logger.debug("skipping form element {} from mail content because it's not in the request",
                            name);
                } else if (rp.isFormField()) {
                    buffer.append(name);
                    buffer.append(" : \n");
                    final String[] pValues = request.getParameterValues(name);
                    for (final String v : pValues) {
                        buffer.append(v);
                        buffer.append("\n");
                    }
                    buffer.append("\n");
                } else if (rp.getSize() > 0) {
                    attachments.add(rp);

                } else {
                    //ignore
                }
            }
            // if we have attachments we send a multi part, otherwise a simple email
            final Email email;
            if (attachments.size() > 0) {
                buffer.append("\n");
                buffer.append(resBundle.getString("Attachments"));
                buffer.append(":\n");
                final MultiPartEmail mpEmail = new MultiPartEmail();
                email = mpEmail;
                for (final RequestParameter rp : attachments) {
                    final ByteArrayDataSource ea = new ByteArrayDataSource(rp.getInputStream(),
                            rp.getContentType());
                    mpEmail.attach(ea, rp.getFileName(), rp.getFileName());

                    buffer.append("- ");
                    buffer.append(rp.getFileName());
                    buffer.append("\n");
                }
            } else {
                email = new SimpleEmail();
            }

            email.setMsg(buffer.toString());
            // mailto
            for (final String rec : mailTo) {
                email.addTo(rec);
            }
            // cc
            final String[] ccRecs = values.get(CC_PROPERTY, String[].class);
            if (ccRecs != null) {
                for (final String rec : ccRecs) {
                    email.addCc(rec);
                }
            }
            // bcc
            final String[] bccRecs = values.get(BCC_PROPERTY, String[].class);
            if (bccRecs != null) {
                for (final String rec : bccRecs) {
                    email.addBcc(rec);
                }
            }

            // subject and from address
            final String subject = values.get(SUBJECT_PROPERTY, resBundle.getString("Form Mail"));
            email.setSubject(subject);
            final String fromAddress = values.get(FROM_PROPERTY, "");
            if (fromAddress.length() > 0) {
                email.setFrom(fromAddress);
            }
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Sending form activated mail: fromAddress={}, to={}, subject={}, text={}.",
                        new Object[] { fromAddress, mailTo, subject, buffer });
            }
            localService.sendEmail(email);

        } catch (EmailException e) {
            logger.error("Error sending email: " + e.getMessage(), e);
            status = 500;
        }
    }
    // check for redirect
    String redirectTo = request.getParameter(":redirect");
    if (redirectTo != null) {
        int pos = redirectTo.indexOf('?');
        redirectTo = redirectTo + (pos == -1 ? '?' : '&') + "status=" + status;
        response.sendRedirect(redirectTo);
        return;
    }
    if (FormsHelper.isRedirectToReferrer(request)) {
        FormsHelper.redirectToReferrer(request, response,
                Collections.singletonMap("stats", new String[] { String.valueOf(status) }));
        return;
    }
    response.setStatus(status);
}

From source file:com.mirth.connect.connectors.smtp.SmtpMessageDispatcher.java

@Override
public void doDispatch(UMOEvent event) throws Exception {
    monitoringController.updateStatus(connector, connectorType, Event.BUSY);
    MessageObject mo = messageObjectController.getMessageObjectFromEvent(event);

    if (mo == null) {
        return;//from w ww.j  av a  2  s.c  o m
    }

    try {
        Email email = null;

        if (connector.isHtml()) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(connector.getCharsetEncoding());

        email.setHostName(replacer.replaceValues(connector.getSmtpHost(), mo));

        try {
            email.setSmtpPort(Integer.parseInt(replacer.replaceValues(connector.getSmtpPort(), mo)));
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        try {
            email.setSocketConnectionTimeout(
                    Integer.parseInt(replacer.replaceValues(connector.getTimeout(), mo)));
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        if ("SSL".equalsIgnoreCase(connector.getEncryption())) {
            email.setSSL(true);
        } else if ("TLS".equalsIgnoreCase(connector.getEncryption())) {
            email.setTLS(true);
        }

        if (connector.isAuthentication()) {
            email.setAuthentication(replacer.replaceValues(connector.getUsername(), mo),
                    replacer.replaceValues(connector.getPassword(), mo));
        }

        /*
         * NOTE: There seems to be a bug when calling setTo with a List
         * (throws a java.lang.ArrayStoreException), so we are using addTo
         * instead.
         */

        for (String to : replaceValuesAndSplit(connector.getTo(), mo)) {
            email.addTo(to);
        }

        // Currently unused
        for (String cc : replaceValuesAndSplit(connector.cc(), mo)) {
            email.addCc(cc);
        }

        // Currently unused
        for (String bcc : replaceValuesAndSplit(connector.getBcc(), mo)) {
            email.addBcc(bcc);
        }

        // Currently unused
        for (String replyTo : replaceValuesAndSplit(connector.getReplyTo(), mo)) {
            email.addReplyTo(replyTo);
        }

        for (Entry<String, String> header : connector.getHeaders().entrySet()) {
            email.addHeader(replacer.replaceValues(header.getKey(), mo),
                    replacer.replaceValues(header.getValue(), mo));
        }

        email.setFrom(replacer.replaceValues(connector.getFrom(), mo));
        email.setSubject(replacer.replaceValues(connector.getSubject(), mo));

        String body = replacer.replaceValues(connector.getBody(), mo);

        if (connector.isHtml()) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        /*
         * If the MIME type for the attachment is missing, we display a
         * warning and set the content anyway. If the MIME type is of type
         * "text" or "application/xml", then we add the content. If it is
         * anything else, we assume it should be Base64 decoded first.
         */
        for (Attachment attachment : connector.getAttachments()) {
            String name = replacer.replaceValues(attachment.getName(), mo);
            String mimeType = replacer.replaceValues(attachment.getMimeType(), mo);
            String content = replacer.replaceValues(attachment.getContent(), mo);

            byte[] bytes;

            if (StringUtils.indexOf(mimeType, "/") < 0) {
                logger.warn("valid MIME type is missing for email attachment: \"" + name
                        + "\", using default of text/plain");
                attachment.setMimeType("text/plain");
                bytes = content.getBytes();
            } else if ("application/xml".equalsIgnoreCase(mimeType)
                    || StringUtils.startsWith(mimeType, "text/")) {
                logger.debug("text or XML MIME type detected for attachment \"" + name + "\"");
                bytes = content.getBytes();
            } else {
                logger.debug("binary MIME type detected for attachment \"" + name
                        + "\", performing Base64 decoding");
                bytes = Base64.decodeBase64(content);
            }

            ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null);
        }

        /*
         * From the Commons Email JavaDoc: send returns
         * "the message id of the underlying MimeMessage".
         */
        String response = email.send();
        messageObjectController.setSuccess(mo, response, null);
    } catch (EmailException e) {
        alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_402,
                "Error sending email message.", e);
        messageObjectController.setError(mo, Constants.ERROR_402, "Error sending email message.", e, null);
        connector.handleException(new Exception(e));
    } finally {
        monitoringController.updateStatus(connector, connectorType, Event.DONE);
    }
}

From source file:com.mirth.connect.connectors.smtp.SmtpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    SmtpDispatcherProperties smtpDispatcherProperties = (SmtpDispatcherProperties) connectorProperties;
    String responseData = null;//from   w w w . j a  va  2s  . c  o  m
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;

    String info = "From: " + smtpDispatcherProperties.getFrom() + " To: " + smtpDispatcherProperties.getTo()
            + " SMTP Info: " + smtpDispatcherProperties.getSmtpHost() + ":"
            + smtpDispatcherProperties.getSmtpPort();
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING, info));

    try {
        Email email = null;

        if (smtpDispatcherProperties.isHtml()) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charsetEncoding);

        email.setHostName(smtpDispatcherProperties.getSmtpHost());

        try {
            email.setSmtpPort(Integer.parseInt(smtpDispatcherProperties.getSmtpPort()));
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

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

        // This has to be set before the authenticator because a session shouldn't be created yet
        configuration.configureEncryption(connectorProperties, email);

        if (smtpDispatcherProperties.isAuthentication()) {
            email.setAuthentication(smtpDispatcherProperties.getUsername(),
                    smtpDispatcherProperties.getPassword());
        }

        Properties mailProperties = email.getMailSession().getProperties();
        // These have to be set after the authenticator, so that a new mail session isn't created
        configuration.configureMailProperties(mailProperties);

        if (smtpDispatcherProperties.isOverrideLocalBinding()) {
            mailProperties.setProperty("mail.smtp.localaddress", smtpDispatcherProperties.getLocalAddress());
            mailProperties.setProperty("mail.smtp.localport", smtpDispatcherProperties.getLocalPort());
        }
        /*
         * NOTE: There seems to be a bug when calling setTo with a List (throws a
         * java.lang.ArrayStoreException), so we are using addTo instead.
         */

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

        // Currently unused
        for (String cc : StringUtils.split(smtpDispatcherProperties.getCc(), ",")) {
            email.addCc(cc);
        }

        // Currently unused
        for (String bcc : StringUtils.split(smtpDispatcherProperties.getBcc(), ",")) {
            email.addBcc(bcc);
        }

        // Currently unused
        for (String replyTo : StringUtils.split(smtpDispatcherProperties.getReplyTo(), ",")) {
            email.addReplyTo(replyTo);
        }

        for (Entry<String, String> header : smtpDispatcherProperties.getHeaders().entrySet()) {
            email.addHeader(header.getKey(), header.getValue());
        }

        email.setFrom(smtpDispatcherProperties.getFrom());
        email.setSubject(smtpDispatcherProperties.getSubject());

        AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider();

        String body = attachmentHandlerProvider.reAttachMessage(smtpDispatcherProperties.getBody(),
                connectorMessage);

        if (StringUtils.isNotEmpty(body)) {
            if (smtpDispatcherProperties.isHtml()) {
                ((HtmlEmail) email).setHtmlMsg(body);
            } else {
                email.setMsg(body);
            }
        }

        /*
         * If the MIME type for the attachment is missing, we display a warning and set the
         * content anyway. If the MIME type is of type "text" or "application/xml", then we add
         * the content. If it is anything else, we assume it should be Base64 decoded first.
         */
        for (Attachment attachment : smtpDispatcherProperties.getAttachments()) {
            String name = attachment.getName();
            String mimeType = attachment.getMimeType();
            String content = attachment.getContent();

            byte[] bytes;

            if (StringUtils.indexOf(mimeType, "/") < 0) {
                logger.warn("valid MIME type is missing for email attachment: \"" + name
                        + "\", using default of text/plain");
                attachment.setMimeType("text/plain");
                bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding,
                        false);
            } else if ("application/xml".equalsIgnoreCase(mimeType)
                    || StringUtils.startsWith(mimeType, "text/")) {
                logger.debug("text or XML MIME type detected for attachment \"" + name + "\"");
                bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding,
                        false);
            } else {
                logger.debug("binary MIME type detected for attachment \"" + name
                        + "\", performing Base64 decoding");
                bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, null, true);
            }

            ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null);
        }

        /*
         * From the Commons Email JavaDoc: send returns
         * "the message id of the underlying MimeMessage".
         */
        responseData = email.send();
        responseStatus = Status.SENT;
        responseStatusMessage = "Email sent successfully.";
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error sending email message", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error sending email message", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error sending email message", e);

        // TODO: Exception handling
        //            connector.handleException(new Exception(e));
    } finally {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError);
}

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 w  ww.jav a2s .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:easycar.controller.BookingListController.java

public void emailRemind() {
    Email email = new SimpleEmail();
    email.setHostName("smtp.googlemail.com");
    email.setSmtpPort(465);//  www  . j  a va2  s. c  om
    email.setAuthenticator(new DefaultAuthenticator("easycarremind", "easycartest"));
    email.setSSLOnConnect(true);
    try {
        email.setFrom("easycarremind@gmail.com");
        email.setSubject("Reminder to return car");
        email.setMsg("Dear " + selectedBooking.getCustomerName()
                + ",\n\nPlease note that you are supposed to return the car with id "
                + selectedBooking.getCarId() + " to us on " + selectedBooking.getEndDateToDisplay()
                + "\n\nBest regards,\nEasy Car Team.");
        email.addTo(selectedBooking.getCustomerEmail());
        email.send();
    } catch (EmailException e) {
        e.printStackTrace();
    }

    selectedBooking.setLastEmailRemindDate(getZeroTimeDate(new Date()));
    try {
        bookingService.editBooking(selectedBooking);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FacesContext.getCurrentInstance().addMessage("messageDetailDialog", new FacesMessage(
            FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("REMINDER_SENT"), null));
}

From source file:easycar.controller.BookingListController.java

public void emailRemindAll() {
    FullBookingDto currentFullBookingDto;
    for (int i = 0; i < baseFullBookingList.size(); i++) {
        currentFullBookingDto = baseFullBookingList.get(i);

        if (!currentFullBookingDto.isRemindButtonOn()) {
            continue;
        }//from  w w  w . ja v a 2 s . com

        Email email = new SimpleEmail();
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("easycarremind", "easycartest"));
        email.setSSLOnConnect(true);

        try {
            email.setFrom("easycarremind@gmail.com");
            email.setSubject("Reminder to return car");
            email.setMsg("Dear " + currentFullBookingDto.getCustomerName()
                    + ",\n\nPlease note that you are supposed to return the car with id "
                    + currentFullBookingDto.getCarId() + " to us on "
                    + currentFullBookingDto.getEndDateToDisplay() + "\n\nBest regards,\nEasy Car Team.");
            email.addTo(currentFullBookingDto.getCustomerEmail());
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }

        currentFullBookingDto.setLastEmailRemindDate(getZeroTimeDate(new Date()));
        try {
            bookingService.editBooking(currentFullBookingDto);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    FacesContext.getCurrentInstance().addMessage("messageEmailRemindAll", new FacesMessage(
            FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("REMINDER_SENT"), null));
}

From source file:net.wikiadmin.clientnotification.SendMain.java

/** sendMainText. */
void sendMainText(String cMail, String cName, String cCredit) {

    /* i need your data!!! :D */
    XmlProp readData = new XmlProp("mailsettings.xml");
    readData.readData();/* ww w.j  av  a2 s .  c  o m*/

    userS = readData.getUser();
    passS = readData.getpass();
    hostS = readData.gethost();
    portS = readData.getport();
    sslS = readData.getssl();
    fromS = readData.getfrom();
    toS = cMail;
    intPortS = Integer.parseInt(portS);
    sslBoolean = Boolean.parseBoolean(sslS);
    themeText = readData.getTheme();
    bodyText = readData.getBody() + cName + ".\n" + readData.getBodyP2() + cCredit + readData.getBodyP3() + "\n"
            + readData.getBodyContacts();

    try {
        Email email = new SimpleEmail();
        email.setHostName(hostS);
        email.setAuthenticator(new DefaultAuthenticator(userS, passS));
        email.setSSLOnConnect(sslBoolean);
        email.setSmtpPort(intPortS);
        email.setFrom(fromS);
        email.setSubject(themeText);
        email.setMsg(bodyText);
        email.addTo(toS);
        email.send();
    } catch (EmailException ex) {
        ex.printStackTrace();
        System.out.println("");
    }
}

From source file:org.activiti5.engine.impl.bpmn.behavior.MailActivityBehavior.java

protected void setFrom(Email email, String from, String tenantId) {
    String fromAddress = null;/*from   w w  w.j av a 2  s.c  om*/

    if (from != null) {
        fromAddress = from;
    } else { // use default configured from address in process engine config
        if (tenantId != null && tenantId.length() > 0) {
            Map<String, MailServerInfo> mailServers = Context.getProcessEngineConfiguration().getMailServers();
            if (mailServers != null && mailServers.containsKey(tenantId)) {
                MailServerInfo mailServerInfo = mailServers.get(tenantId);
                fromAddress = mailServerInfo.getMailServerDefaultFrom();
            }
        }

        if (fromAddress == null) {
            fromAddress = Context.getProcessEngineConfiguration().getMailServerDefaultFrom();
        }
    }

    try {
        email.setFrom(fromAddress);
    } catch (EmailException e) {
        throw new ActivitiException("Could not set " + from + " as from address in email", e);
    }
}

From source file:org.apache.airavata.credential.store.notifier.impl.EmailNotifier.java

public void notifyMessage(NotificationMessage message) throws CredentialStoreException {
    try {/*from w  ww. j av a 2s  .c om*/
        Email email = new SimpleEmail();
        email.setHostName(this.emailNotifierConfiguration.getEmailServer());
        email.setSmtpPort(this.emailNotifierConfiguration.getEmailServerPort());
        email.setAuthenticator(new DefaultAuthenticator(this.emailNotifierConfiguration.getEmailUserName(),
                this.emailNotifierConfiguration.getEmailPassword()));
        email.setSSLOnConnect(this.emailNotifierConfiguration.isSslConnect());
        email.setFrom(this.emailNotifierConfiguration.getFromAddress());

        EmailNotificationMessage emailMessage = (EmailNotificationMessage) message;

        email.setSubject(emailMessage.getSubject());
        email.setMsg(emailMessage.getMessage());
        email.addTo(emailMessage.getSenderEmail());
        email.send();

    } catch (EmailException e) {
        log.error("[CredentialStore]Error sending email notification message.");
        throw new CredentialStoreException("Error sending email notification message", e);
    }

}