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

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

Introduction

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

Prototype

public abstract Email setMsg(String msg) throws EmailException;

Source Link

Document

Define the content of the mail.

Usage

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  .ja v  a2 s . 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.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(//w w  w .j  a  v  a 2 s .  com
            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 {
        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);/*from   ww w.ja  v  a 2s . 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;/* ww w . j a v a2s . co  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.openepics.discs.calib.ejb.ReminderSvc.java

private void sendMail(String from, String[] to, String subject, String message) {
    try {/*from  w w w.j  ava2 s. c o  m*/
        Email email = new SimpleEmail();

        logger.info("sending email ...");
        email.setHostName("exchange.nscl.msu.edu");
        email.setSmtpPort(25);
        // email.setSmtpPort(465);
        // email.setAuthenticator(new DefaultAuthenticator("iser", "xxxxxx"));
        // email.setSSLOnConnect(true);
        email.setTLS(true);
        // email.setDebug(true);
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(message);
        email.addTo(to);
        email.send();
    } catch (Exception e) {
        logger.severe("error while sending email");
    }
}

From source file:org.openhab.action.mail.internal.Mail.java

/**
 * Sends an email with attachment(s) via SMTP
 * /*from   www.j av  a2s  .c  om*/
 * @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.MailBuilder.java

/**
 * Build the Mail/*from ww  w  .  j a v a 2s . com*/
 *
 * @return instance of Email
 * @throws EmailException if something goes wrong
 */
public Email build() throws EmailException {
    Email mail;

    if (attachmentURLs.isEmpty() && attachmentFiles.isEmpty() && html.isEmpty()) {
        // text mail without attachments
        mail = new SimpleEmail();
        if (!text.isEmpty()) {
            mail.setMsg(text);
        }
    } else if (html.isEmpty()) {
        // text mail with attachments
        MultiPartEmail multipartMail = new MultiPartEmail();
        if (!text.isEmpty()) {
            multipartMail.setMsg(text);
        }
        for (File file : attachmentFiles) {
            multipartMail.attach(file);
        }
        for (URL url : attachmentURLs) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setURL(url);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            multipartMail.attach(attachment);
        }
        mail = multipartMail;
    } else {
        // html email
        HtmlEmail htmlMail = new HtmlEmail();
        if (!text.isEmpty()) {
            // alternate text supplied
            htmlMail.setTextMsg(text);
            htmlMail.setHtmlMsg(html);
        } else {
            htmlMail.setMsg(html);
        }
        for (File file : attachmentFiles) {
            htmlMail.attach(new FileDataSource(file), "", "");
        }
        for (URL url : attachmentURLs) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setURL(url);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            htmlMail.attach(attachment);
        }
        mail = htmlMail;
    }

    mail.setTo(recipients);
    mail.setSubject(subject);

    if (!sender.isEmpty()) {
        mail.setFrom(sender);
    }

    return mail;
}

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

/**
 * Sends an email with attachment via SMTP
 * /*from w  w w  .j a va2 s  . 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 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  ww .  ja  v  a2s  .  c  o  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 {/*www.java 2  s . com*/
        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;
}