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

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

Introduction

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

Prototype

public Session getMailSession() throws EmailException 

Source Link

Document

Determines the mail session used when sending this Email, creating the Session if necessary.

Usage

From source file:org.fao.geonet.util.MailUtil.java

/**
 * Create data information to compose the mail
 *
 * @param hostName//from   w  w  w .  j  a v  a  2s.  c  o m
 * @param smtpPort
 * @param from
 * @param username
 * @param password
 * @param email
 * @param ssl
 * @param tls
 * @param ignoreSslCertificateErrors
 */
private static void configureBasics(String hostName, Integer smtpPort, String from, String username,
        String password, Email email, Boolean ssl, Boolean tls, Boolean ignoreSslCertificateErrors) {
    if (hostName != null) {
        email.setHostName(hostName);
    } else {
        throw new IllegalArgumentException(
                "Missing settings in System Configuration (see Administration menu) - cannot send mail");
    }
    if (StringUtils.isNotBlank(smtpPort + "")) {
        email.setSmtpPort(smtpPort);
    } else {
        throw new IllegalArgumentException(
                "Missing settings in System Configuration (see Administration menu) - cannot send mail");
    }
    if (username != null) {
        email.setAuthenticator(new DefaultAuthenticator(username, password));
    }

    email.setDebug(true);

    if (tls != null && tls) {
        email.setStartTLSEnabled(tls);
        email.setStartTLSRequired(tls);
    }

    if (ssl != null && ssl) {
        email.setSSLOnConnect(ssl);
        if (StringUtils.isNotBlank(smtpPort + "")) {
            email.setSslSmtpPort(smtpPort + "");
        }
    }

    if (ignoreSslCertificateErrors != null && ignoreSslCertificateErrors) {
        try {
            Session mailSession = email.getMailSession();
            Properties p = mailSession.getProperties();
            p.setProperty("mail.smtp.ssl.trust", "*");

        } catch (EmailException e) {
            // Ignore the exception. Can't be reached because the host name is always set above or an
            // IllegalArgumentException is thrown.
        }
    }

    if (StringUtils.isNotBlank(from)) {
        try {
            email.setFrom(from);
        } catch (EmailException e) {
            throw new IllegalArgumentException(
                    "Invalid 'from' email setting in System Configuration (see Administration menu) - cannot send "
                            + "mail",
                    e);
        }
    } else {
        throw new IllegalArgumentException(
                "Missing settings in System Configuration (see Administration menu) - cannot send mail");
    }
}

From source file:org.mifosplatform.billing.message.service.MessageGmailBackedPlatformEmailService.java

@Override
public void sendToUserEmail() {
    Email email = new SimpleEmail();

    String authuserName = "info@hugotechnologies.com";
    //String authusername="hugotechnologies";

    String authuser = "ashokcse556@gmail.com";
    String authpwd = "9989720715";

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(true); // true if you want to debug
    email.setHostName("smtp.gmail.com");
    try {/*from w w  w  .  ja  va  2 s. co  m*/
        email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        email.setFrom(authuserName, authuser);
        List<BillingMessageDataForProcessing> billingMessageDataForProcessings = this.billingMesssageReadPlatformService
                .retrieveMessageDataForProcessing();
        for (BillingMessageDataForProcessing emailDetail : billingMessageDataForProcessings) {

            StringBuilder subjectBuilder = new StringBuilder().append(" ").append(emailDetail.getSubject())
                    .append("  ");

            email.setSubject(subjectBuilder.toString());

            String sendToEmail = emailDetail.getMessageTo();

            StringBuilder messageBuilder = new StringBuilder().append(emailDetail.getHeader()).append(".")
                    .append(emailDetail.getBody()).append(",").append(emailDetail.getFooter());

            email.setMsg(messageBuilder.toString());

            email.addTo(sendToEmail, emailDetail.getMessageFrom());
            email.setSmtpPort(587);
            email.send();
            BillingMessage billingMessage = this.messageDataRepository.findOne(emailDetail.getId());
            if (billingMessage.getStatus().contentEquals("N")) {
                billingMessage.updateStatus();
            }
            this.messageDataRepository.save(billingMessage);

        }
    } catch (EmailException e) {
        throw new MessagePlatformEmailSendException(e);
    }
}

From source file:org.mifosplatform.infrastructure.core.service.GmailBackedPlatformEmailService.java

@Override
public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) {
    final Email email = new SimpleEmail();

    final String authuserName = "support@cloudmicrofinance.com";

    final String authuser = "support@cloudmicrofinance.com";
    final String authpwd = "support80";

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(false); // true if you want to debug
    email.setHostName("smtp.gmail.com");
    try {// w w w . j  a v  a2s  . c o  m
        email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        email.setFrom(authuser, authuserName);

        final StringBuilder subjectBuilder = new StringBuilder().append("MifosX Prototype Demo: ")
                .append(emailDetail.getContactName()).append(" user account creation.");

        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 MifosX Prototype Demo.")
                .append("You can login using the following credentials: username: ")
                .append(emailDetail.getUsername()).append(" password: ").append(unencodedPassword);

        email.setMsg(messageBuilder.toString());

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

From source file:org.mifosplatform.infrastructure.core.service.GmailSendingNotificationToClients.java

public void sendToUserAccount(final String mailAddress, final String approviedDate, final String type,
        final String money) {
    final Email email = new SimpleEmail();
    final String authuserName = "raghuchiluka111@gmail.com";
    final String authuser = "raghuchiluka111@gmail.com";
    final String authpwd = "raghuAkhila";
    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(false); // true if you want to debug
    email.setHostName("smtp.gmail.com");
    email.setSmtpPort(587);/*from   w w w  .j  a v  a2s .  co  m*/
    try {
        email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        email.setFrom(authuser, authuserName);
        final StringBuilder subjectBuilder = new StringBuilder().append(type + ": ");
        email.setSubject(subjectBuilder.toString());
        StringBuilder messageBuilder = null;
        if (money != null)
            messageBuilder = new StringBuilder().append(type + ": ").append(approviedDate)
                    .append("Amount Disbursed:").append(money);
        else
            messageBuilder = new StringBuilder().append(type + ": ").append(approviedDate);
        email.setMsg(messageBuilder.toString());
        email.addTo(mailAddress, mailAddress);
        email.send();
    } catch (final EmailException e) {
        throw new PlatformEmailSendException(e);
    }
}

From source file:org.mifosplatform.infrastructure.security.service.JpaPlatformUserLoginFailureService.java

private void notify(String username, Integer failures) {
    GlobalConfigurationProperty property = globalConfigurationRepository.findOneByName("login-failure-limit");

    Long limit = 3l;/*w  w w  .j  a  va2  s .c o m*/

    if (property != null && property.isEnabled() && property.getValue() != null) {
        limit = property.getValue();
    }

    // NOTE: only send the email once
    if (failures == limit.intValue()) {
        lock(username);
        try {
            StringBuilder message = new StringBuilder();
            message.append(String.format(template, limit));

            final Email email = new SimpleEmail();
            EmailCredentialsData credentials = getCredentials();
            email.setAuthenticator(
                    new DefaultAuthenticator(credentials.getAuthUsername(), credentials.getAuthPassword()));
            email.setDebug(credentials.isDebug());
            email.setHostName(credentials.getHost());
            email.setSmtpPort(credentials.getSmtpPort());
            email.setStartTLSRequired(true);
            email.setStartTLSEnabled(credentials.isStartTls());
            email.getMailSession().getProperties().put("mail.smtp.auth", true);
            email.setFrom(credentials.getAuthUsername(), credentials.getSenderName());
            email.setSubject(subject);
            email.setMsg(message.toString());
            email.addTo(appUserRepository.getEmailByUsername(username));
            email.send();
        } catch (Exception e) {
            logger.warn(e.toString(), e);
        }

        throw new LockedException(
                "User " + username + " has been locked after " + limit + " failed login attempts.");
    }
}

From source file:org.sonatype.nexus.internal.email.EmailManagerImpl.java

/**
 * Apply server configuration to email.//from  w w w.  ja v  a  2s .  co m
 */
@VisibleForTesting
Email apply(final EmailConfiguration configuration, final Email mail) throws EmailException {
    mail.setHostName(configuration.getHost());
    mail.setSmtpPort(configuration.getPort());
    mail.setAuthentication(configuration.getUsername(), configuration.getPassword());

    mail.setStartTLSEnabled(configuration.isStartTlsEnabled());
    mail.setStartTLSRequired(configuration.isStartTlsRequired());
    mail.setSSLOnConnect(configuration.isSslOnConnectEnabled());
    mail.setSSLCheckServerIdentity(configuration.isSslCheckServerIdentityEnabled());
    mail.setSslSmtpPort(Integer.toString(configuration.getPort()));

    // default from address
    if (mail.getFromAddress() == null) {
        mail.setFrom(configuration.getFromAddress());
    }

    // apply subject prefix if configured
    String subjectPrefix = configuration.getSubjectPrefix();
    if (subjectPrefix != null) {
        String subject = mail.getSubject();
        mail.setSubject(String.format("%s %s", subjectPrefix, subject));
    }

    // do this last (mail properties are set up from the email fields when you get the mail session)
    if (configuration.isNexusTrustStoreEnabled()) {
        SSLContext context = trustStore.getSSLContext();
        Session session = mail.getMailSession();
        Properties properties = session.getProperties();
        properties.remove(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_CLASS);
        properties.put(EmailConstants.MAIL_SMTP_SSL_ENABLE, true);
        properties.put("mail.smtp.ssl.socketFactory", context.getSocketFactory());
    }

    return mail;
}