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: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.  j av a 2s. c o  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 {//from   w  ww.j a  v  a  2 s  . c om
        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.GmailPlatformEmailService.java

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

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(
            new DefaultAuthenticator(credentials.getAuthUsername(), credentials.getAuthPassword()));
    email.setDebug(false); // true if you want to debug
    email.setHostName("smtp.gmail.com");
    email.setSmtpPort(credentials.getSmtpPort());
    try {//from   w  w  w.j  av a 2s .c  o  m
        email.setStartTLSRequired(true);
        email.setStartTLSEnabled(credentials.isStartTls());
        email.setFrom(credentials.getAuthUsername(), credentials.getAuthUsername());

        final StringBuilder subjectBuilder = new StringBuilder().append("FINEM U Ltd.: ")
                .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("].")
                .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);// w ww.  j  a v  a2 s .  c o 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;//from   w  w w .  j a  v a2s.c om

    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.openhab.action.mail.internal.Mail.java

/**
 * Sends an email with attachment(s) via SMTP
 * //from w  w w  . j ava2s  .co  m
 * @param to the email address of the recipient
 * @param subject the subject of the email
 * @param message the body of the email
 * @param attachmentUrlList a list of URL strings of the contents to send as attachments
 * 
 * @return <code>true</code>, if sending the email has been successful and 
 * <code>false</code> in all other cases.
 */
@ActionDoc(text = "Sends an email with attachment via SMTP")
static public boolean sendMail(@ParamDoc(name = "to") String to, @ParamDoc(name = "subject") String subject,
        @ParamDoc(name = "message") String message,
        @ParamDoc(name = "attachmentUrlList") List<String> attachmentUrlList) {
    boolean success = false;
    if (MailActionService.isProperlyConfigured) {
        Email email = new SimpleEmail();
        if (attachmentUrlList != null && !attachmentUrlList.isEmpty()) {
            email = new MultiPartEmail();
            for (String attachmentUrl : attachmentUrlList) {
                // Create the attachment
                try {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setURL(new URL(attachmentUrl));
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    String fileName = attachmentUrl.replaceFirst(".*/([^/?]+).*", "$1");
                    attachment.setName(StringUtils.isNotBlank(fileName) ? fileName : "Attachment");
                    ((MultiPartEmail) email).attach(attachment);
                } catch (MalformedURLException e) {
                    logger.error("Invalid attachment url.", e);
                } catch (EmailException e) {
                    logger.error("Error adding attachment to email.", e);
                }
            }
        }

        email.setHostName(hostname);
        email.setSmtpPort(port);
        email.setTLS(tls);

        if (StringUtils.isNotBlank(username)) {
            if (popBeforeSmtp) {
                email.setPopBeforeSmtp(true, hostname, username, password);
            } else {
                email.setAuthenticator(new DefaultAuthenticator(username, password));
            }
        }

        try {
            if (StringUtils.isNotBlank(charset)) {
                email.setCharset(charset);
            }
            email.setFrom(from);
            String[] toList = to.split(";");
            for (String toAddress : toList) {
                email.addTo(toAddress);
            }
            if (!StringUtils.isEmpty(subject))
                email.setSubject(subject);
            if (!StringUtils.isEmpty(message))
                email.setMsg(message);
            email.send();
            logger.debug("Sent email to '{}' with subject '{}'.", to, subject);
            success = true;
        } catch (EmailException e) {
            logger.error("Could not send e-mail to '" + to + "'.", e);
        }
    } else {
        logger.error(
                "Cannot send e-mail because of missing configuration settings. The current settings are: "
                        + "Host: '{}', port '{}', from '{}', useTLS: {}, username: '{}', password '{}'",
                new Object[] { hostname, String.valueOf(port), from, String.valueOf(tls), username, password });
    }

    return success;
}

From source file:org.openhab.binding.mail.internal.SMTPHandler.java

/**
 * use this server to send a mail//from w  w w.j  a  v a  2s .  co  m
 *
 * @param mail the Email that needs to be sent
 * @return true if successful, false if failed
 */
public boolean sendMail(Email mail) {
    try {
        if (mail.getFromAddress() == null) {
            mail.setFrom(config.sender);
        }
        mail.setHostName(config.hostname);
        switch (config.security) {
        case SSL:
            mail.setSSLOnConnect(true);
            mail.setSslSmtpPort(config.port.toString());
            break;
        case TLS:
            mail.setStartTLSEnabled(true);
            mail.setStartTLSRequired(true);
            mail.setSmtpPort(config.port);
            break;
        case PLAIN:
            mail.setSmtpPort(config.port);
        }
        if (!config.username.isEmpty() && !config.password.isEmpty()) {
            mail.setAuthenticator(new DefaultAuthenticator(config.username, config.password));
        }
        mail.send();
    } catch (EmailException e) {
        logger.warn("Trying to send mail but exception occured: {} ", e.getMessage());
        return false;
    }
    return true;
}

From source file:org.openhab.io.net.actions.Mail.java

/**
 * Sends an email with attachment via SMTP
 * /*from ww w  .  j a v a2s  .  c o m*/
 * @param to the email address of the recipient
 * @param subject the subject of the email
 * @param message the body of the email
 * @param attachmentUrl a URL string of the content to send as an attachment
 * 
 * @return <code>true</code>, if sending the email has been successful and 
 * <code>false</code> in all other cases.
 */
static public boolean sendMail(String to, String subject, String message, String attachmentUrl) {
    boolean success = false;
    if (initialized) {
        Email email = new SimpleEmail();
        if (attachmentUrl != null) {
            // Create the attachment
            try {
                email = new MultiPartEmail();
                EmailAttachment attachment = new EmailAttachment();
                attachment.setURL(new URL(attachmentUrl));
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setName("Attachment");
                ((MultiPartEmail) email).attach(attachment);
            } catch (MalformedURLException e) {
                logger.error("Invalid attachment url.", e);
            } catch (EmailException e) {
                logger.error("Error adding attachment to email.", e);
            }
        }

        email.setHostName(hostname);
        email.setSmtpPort(port);
        email.setTLS(tls);

        if (StringUtils.isNotBlank(username)) {
            if (popBeforeSmtp) {
                email.setPopBeforeSmtp(true, hostname, username, password);
            } else {
                email.setAuthenticator(new DefaultAuthenticator(username, password));
            }
        }

        try {
            email.setFrom(from);
            email.addTo(to);
            if (!StringUtils.isEmpty(subject))
                email.setSubject(subject);
            if (!StringUtils.isEmpty(message))
                email.setMsg(message);
            email.send();
            logger.debug("Sent email to '{}' with subject '{}'.", to, subject);
            success = true;
        } catch (EmailException e) {
            logger.error("Could not send e-mail to '" + to + ".", e);
        }
    } else {
        logger.error(
                "Cannot send e-mail because of missing configuration settings. The current settings are: "
                        + "Host: '{}', port '{}', from '{}', useTLS: {}, username: '{}', password '{}'",
                new String[] { hostname, String.valueOf(port), from, String.valueOf(tls), username, password });
    }

    return success;
}

From source file:org.ow2.frascati.akka.fabric.peakforecast.lib.EmailImpl.java

@Override
public void send(String message) {

    try {/*from  w w  w  .  ja v a  2  s  .co m*/
        Email email = new SimpleEmail();
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        //email.setAuthenticator(new DefaultAuthenticator("username", "password"));
        email.setAuthenticator(new DefaultAuthenticator("fouomenedaniel@gmail.com", "motdepasse"));
        email.setSSLOnConnect(true);
        email.setFrom("fouomenedaniel@gmail.com");
        email.setSubject("Alert PeakForecast");
        email.setMsg(message);
        String listtabmail[] = listEmails.split(" ");
        for (int i = 0; i < listtabmail.length; i++) {

            email.addTo(listtabmail[i]);

        }
        email.send();
        System.out.println("Message Email envoy !!!");
    } catch (EmailException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.paxml.bean.EmailTag.java

private Email createEmail(Collection<String> to, Collection<String> cc, Collection<String> bcc)
        throws EmailException {
    Email email;
    if (attachment == null || attachment.isEmpty()) {
        email = new SimpleEmail();
    } else {/* w  w  w.  j  a  v a  2s  .  c o m*/
        MultiPartEmail mpemail = new MultiPartEmail();
        for (Object att : attachment) {
            mpemail.attach(makeAttachment(att.toString()));
        }
        email = mpemail;
    }

    if (StringUtils.isNotEmpty(username)) {
        String pwd = null;
        if (password instanceof Secret) {
            pwd = ((Secret) password).getDecrypted();
        } else if (password != null) {
            pwd = password.toString();
        }
        email.setAuthenticator(new DefaultAuthenticator(username, pwd));
    }

    email.setHostName(findHost());
    email.setSSLOnConnect(ssl);
    if (port > 0) {
        if (ssl) {
            email.setSslSmtpPort(port + "");
        } else {
            email.setSmtpPort(port);
        }
    }
    if (replyTo != null) {
        for (Object r : replyTo) {
            email.addReplyTo(r.toString());
        }
    }
    email.setFrom(from);
    email.setSubject(subject);
    email.setMsg(text);
    if (to != null) {
        for (String r : to) {
            email.addTo(r);
        }
    }
    if (cc != null) {
        for (String r : cc) {
            email.addCc(r);
        }
    }
    if (bcc != null) {
        for (String r : bcc) {
            email.addBcc(r);
        }
    }
    email.setSSLCheckServerIdentity(sslCheckServerIdentity);
    email.setStartTLSEnabled(tls);
    email.setStartTLSRequired(tls);
    return email;
}