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:org.ms123.common.workflow.tasks.TaskMailExecutor.java

protected void setFrom(Email email, String from) {
    String fromAddres = null;//from   w  ww .  ja v  a2  s . c o m

    if (from != null) {
        fromAddres = from;
    } else { // use default configured from address in process engine config
        fromAddres = Context.getProcessEngineConfiguration().getMailServerDefaultFrom();
    }

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

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

protected void setFrom(Email email, String from) {
    String fromAddres = null;//from  w  w w .  j a va  2s  .c  o  m

    if (from != null) {
        fromAddres = from;
    } else { // use default configured from address in process engine config
        fromAddres = Context.getProcessEngineConfiguration().getMailServerDefaultFrom();
    }

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

From source file:org.opencms.mail.CmsMailUtil.java

/**
 * Configures the mail from the given mail host configuration data.<p>
 *
 * @param host the mail host configuration
 * @param mail the email instance//from  w  ww .j  av a  2  s  . com
 */
public static void configureMail(CmsMailHost host, Email mail) {

    // set the host to the default mail host
    mail.setHostName(host.getHostname());
    mail.setSmtpPort(host.getPort());

    // check if username and password are provided
    String userName = host.getUsername();
    if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(userName)) {
        // authentication needed, set user name and password
        mail.setAuthentication(userName, host.getPassword());
    }
    String security = host.getSecurity() != null ? host.getSecurity().trim() : null;
    if (SECURITY_SSL.equalsIgnoreCase(security)) {
        mail.setSslSmtpPort("" + host.getPort());
        mail.setSSLOnConnect(true);
    } else if (SECURITY_STARTTLS.equalsIgnoreCase(security)) {
        mail.setStartTLSEnabled(true);
    }

    try {
        // set default mail from address
        mail.setFrom(OpenCms.getSystemInfo().getMailSettings().getMailFromDefault());
    } catch (EmailException e) {
        // default email address is not valid, log error
        LOG.error(Messages.get().getBundle().key(Messages.LOG_INVALID_SENDER_ADDRESS_0), e);
    }
}

From source file:org.openepics.discs.calib.ejb.ReminderSvc.java

private void sendMail(String from, String[] to, String subject, String message) {
    try {//w ww  . ja v  a2s .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 ww w. j a va  2 s. 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.MailBuilder.java

/**
 * Build the Mail//from w ww .ja v a  2s .c o  m
 *
 * @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.binding.mail.internal.SMTPHandler.java

/**
 * use this server to send a mail/*  w w w  .  j a  va2  s  . 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  w  ww .  j  a v a  2 s .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 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  ww  w . ja va2s .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 {/*from w ww.ja va2 s .  c om*/
        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;
}