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

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

Introduction

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

Prototype

public String send() throws EmailException 

Source Link

Document

Sends the email.

Usage

From source file:org.ms123.common.workflow.TaskSendExecutor.java

public void execute(DelegateExecution execution) {
    TaskContext tc = new TaskContext();
    tc.setExecution(execution);//ww w  .  j  av  a  2  s  .  co m
    setCategory(tc);
    showVariablenNames(tc);
    String toStr = getStringFromField(to, execution);
    String fromStr = getStringFromField(from, execution);
    String ccStr = getStringFromField(cc, execution);
    String bccStr = getStringFromField(bcc, execution);
    String subjectStr = getStringFromField(subject, execution);
    String textStr = getStringFromField(text, execution);
    String htmlStr = getStringFromField(html, execution);
    String attachmentStr = getStringFromField(attachment, execution);
    String charSetStr = getStringFromField(charset, execution);

    Email email = createEmail(execution, textStr, htmlStr, attachmentStr);

    addTo(email, toStr);
    setFrom(email, fromStr);
    addCc(email, ccStr);
    addBcc(email, bccStr);
    setSubject(email, subjectStr);
    setMailServerProperties(email);
    //setCharset(email, charSetStr);

    try {
        email.setCharset("utf-8");
        email.send();
    } catch (EmailException e) {
        throw new RuntimeException("TaskSendExecutor.Could not send e-mail", e);
    }
}

From source file:org.opencms.newsletter.CmsNewsletterDistributor.java

/**
 * Sends a {@link I_CmsNewsletter} to a list of {@link I_CmsNewsletterRecipient} objects.<p>
 * //from  ww  w .j av a  2 s . com
 * @param recipients a list of CmsNewsletterRecipient objects
 * @param newsletter the newsletter to be distributed
 * @param cms the CmsObject
 */
public void distribute(CmsObject cms, List recipients, I_CmsNewsletter newsletter) {

    Iterator recipientsIterator = recipients.iterator();
    while (recipientsIterator.hasNext()) {
        I_CmsNewsletterRecipient recipient = (I_CmsNewsletterRecipient) recipientsIterator.next();
        try {
            Email mail = newsletter.getEmail(cms, recipient);
            mail.addTo(recipient.getEmail(), recipient.getFullName());
            mail.send();
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }
}

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  a  va 2  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
 * /* ww  w.  j av  a 2s  .  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 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   www .  j av  a  2s .  c  o  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 w  w  w.j  a  v  a  2s  .  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 {/*  w w  w  . j a  va 2  s  . 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

@Override
protected Object doInvoke(Context context) throws Exception {

    if (isolate) {
        Set<String> all = new LinkedHashSet<String>();
        if (to != null) {
            all.addAll(to);/*from  w  ww  .j  av  a  2s.co  m*/
        }
        if (cc != null) {
            all.addAll(cc);
        }
        if (bcc != null) {
            all.addAll(bcc);
        }
        List<String> ids = new ArrayList<String>(all.size());
        for (String r : all) {
            Email email = createEmail(Arrays.asList(r), null, null);
            String id = email.send();
            if (log.isDebugEnabled()) {
                log.debug("Isolated email sent to: " + r + ", from: " + from + ", replyTo: " + replyTo);
            }
            ids.add(id);
        }
        return ids;
    } else {
        Email email = createEmail(to, cc, bcc);
        String id = email.send();
        if (log.isDebugEnabled()) {
            log.debug("Email sent to: " + to + ", cc: " + cc + ", bcc: " + bcc + ", from: " + from
                    + ", replyTo: " + replyTo);
        }
        return id;
    }

}

From source file:org.pepstock.jem.notify.engine.EmailNotifier.java

/**
 * This method sends an <code>Email</code>. <br>
 * It sets in the parameter <code>Email</code> the properties of the
 * parameter <code>JemEmail</code>: From User Email Address, From User Name,
 * subject, text, email destination addresses. <br>
 * It sets in the parameter <code>Email</code> the Email Server property and
 * the optional <code>SMTP</code> port, the properties that indicates if it
 * must use <code>SSL</code> and <code>TLS</code> protocol, the useirid and
 * password for <code>SMTP</code> server authentication if needed, the
 * optional bounce address, the subject, the text, and the recipients of the
 * email./*from   w ww. ja  v  a  2s . c  o m*/
 * 
 * @param email the <code>JemEmail</code> with the properties of the email
 *            to be sent.
 * @param sendingEmail the real <code>Email</code> that will be sent.
 * @see JemEmail
 * @see Email
 * @throws SendMailException if an error occurs.
 */
private void sendEmail(JemEmail email, Email sendingEmail) throws SendMailException {
    try {
        sendingEmail.setHostName(this.emailServer);
        if (this.smtpPort != NO_SMTP_PORT) {
            sendingEmail.setSmtpPort(this.smtpPort);
        }
        sendingEmail.setFrom(email.getFromUserEmailAddress(), email.getFromUserName());
        if (email.hasSubject()) {
            sendingEmail.setSubject(email.getSubject());
        } else {
            // log no subject
            LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Subject");
        }
        if (email.hasText()) {
            sendingEmail.setMsg(email.getText());
        } else {
            // log no text message
            LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Text Message");
        }
        sendingEmail.setTo(email.getAllToEmailAddresses());
        if (null != this.bounceAddress) {
            sendingEmail.setBounceAddress(this.bounceAddress);
        }
        sendingEmail.setSentDate(new Date());
        sendingEmail.setSSL(this.isSSL);
        sendingEmail.setTLS(this.isTLS);
        if (null != this.authenticationUserId && null != this.authenticationPassword) {
            sendingEmail.setAuthenticator(
                    new DefaultAuthenticator(this.authenticationUserId, this.authenticationPassword));
        }
        sendingEmail.send();
        LogAppl.getInstance().emit(NotifyMessage.JEMN015I, email);
    } catch (EmailException eEx) {
        LogAppl.getInstance().emit(NotifyMessage.JEMN016E, eEx, email);
        throw new SendMailException(NotifyMessage.JEMN016E.toMessage().getFormattedMessage(email), eEx);
    }
}

From source file:org.polymap.rhei.um.email.EmailService.java

public void send(Email email) throws EmailException {
    String env = System.getProperty("org.polymap.rhei.um.SMTP");
    if (env == null) {
        throw new IllegalStateException(
                "Environment variable missing: org.polymap.rhei.um.SMTP. Format: <host>|<login>|<passwd>|<from>");
    }/*from  w w w.j  ava 2 s  . c  om*/
    String[] parts = StringUtils.split(env, "|");
    if (parts.length < 3 || parts.length > 4) {
        throw new IllegalStateException(
                "Environment variable wrong: org.polymap.rhei.um.SMTP. Format: <host>|<login>|<passwd>|<from> : "
                        + env);
    }

    email.setDebug(true);
    email.setHostName(parts[0]);
    //email.setSmtpPort( 465 );
    //email.setSSLOnConnect( true );
    email.setAuthenticator(new DefaultAuthenticator(parts[1], parts[2]));
    if (email.getFromAddress() == null && parts.length == 4) {
        email.setFrom(parts[3]);
    }
    if (email.getSubject() == null) {
        throw new EmailException("Missing subject.");
    }
    email.send();
}