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

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

Introduction

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

Prototype

public void setHostName(final String aHostName) 

Source Link

Document

Set the hostname of the outgoing mail server.

Usage

From source file:org.jwebsocket.plugins.mail.MailPlugInService.java

/**
 *
 * @param aToken/*from   w  w w.j  a v  a2s . c om*/
 * @return
 */
public Token sendMail(Token aToken) {
    String lFrom = aToken.getString("from", "[unknown]");
    String lTo = aToken.getString("to");
    String lCC = aToken.getString("cc");
    String lBCC = aToken.getString("bcc");
    String lSubject = aToken.getString("subject");
    String lBody = aToken.getString("body");
    Boolean lIsHTML = aToken.getBoolean("html", false);
    List<Object> lAttachedFiles = aToken.getList("attachments");
    String lMsg;

    // instantiate response token
    Token lResponse = TokenFactory.createToken();

    Map<String, String> lMap = new FastMap<String, String>();

    if (lFrom != null && lFrom.length() > 0) {
        lMap.put("from", lFrom);
    }
    if (lTo != null && lTo.length() > 0) {
        lMap.put("to", lTo);
    }
    if (lCC != null && lCC.length() > 0) {
        lMap.put("cc", lCC);
    }
    if (lBCC != null && lBCC.length() > 0) {
        lMap.put("bcc", lBCC);
    }
    if (lSubject != null && lSubject.length() > 0) {
        lMap.put("subject", lSubject);
    }
    if (lBody != null && lBody.length() > 0) {
        lMap.put("body", lBody);
    }

    // Create the attachment
    List<EmailAttachment> lEmailAttachments = new FastList<EmailAttachment>();

    if (lAttachedFiles != null) {
        for (Object lAttachedFile : lAttachedFiles) {
            EmailAttachment lAttachment = new EmailAttachment();
            lAttachment.setPath((String) lAttachedFile);
            lAttachment.setDisposition(EmailAttachment.ATTACHMENT);
            // lAttachment.setDescription( "Picture of John" );
            // lAttachment.setName( "John" );
            lEmailAttachments.add(lAttachment);
        }
    }

    // Create the lEmail message
    if (mLog.isDebugEnabled()) {
        mLog.debug("Sending e-mail to " + lTo + " with subject '" + lSubject + "'...");
    }
    try {
        Email lEmail;
        if (lIsHTML) {
            lEmail = new HtmlEmail();
        } else {
            lEmail = new MultiPartEmail();
        }

        lEmail.setHostName(mSettings.getSmtpHost());
        lEmail.setSmtpPort(mSettings.getSmtpPort());
        if (mSettings.getSmtpAuth()) {
            lEmail.setAuthentication(mSettings.getSmtpUser(), mSettings.getSmtpPassword());
        }
        if (mSettings.getSmtpPop3Before()) {
            lEmail.setPopBeforeSmtp(true, mSettings.getPop3Host(), mSettings.getPop3User(),
                    mSettings.getPop3Password());
        }
        if (lFrom != null && lFrom.length() > 0) {
            lEmail.setFrom(lFrom);
        }
        if (lTo != null && lTo.length() > 0) {
            String[] lToSplit = lTo.split(";");
            for (String lToSplit1 : lToSplit) {
                if (lToSplit1 != null && lToSplit1.length() > 0) {
                    lEmail.addTo(lToSplit1.trim());
                }
            }
        }
        if (lCC != null && lCC.length() > 0) {
            String[] lCCSplit = lCC.split(";");
            for (String lCCSplit1 : lCCSplit) {
                if (lCCSplit1 != null && lCCSplit1.length() > 0) {
                    lEmail.addCc(lCCSplit1.trim());
                }
            }
        }
        if (lBCC != null && lBCC.length() > 0) {
            String[] lBCCSplit = lBCC.split(";");
            for (String lBCCSplit1 : lBCCSplit) {
                if (lBCCSplit1 != null && lBCCSplit1.length() > 0) {
                    lEmail.addBcc(lBCCSplit1.trim());
                }
            }
        }
        if (lSubject != null && lSubject.length() > 0) {
            lEmail.setSubject(lSubject);
        }

        if (lBody != null && lBody.length() > 0) {
            if (lIsHTML) {
                HtmlEmail lHTML = ((HtmlEmail) lEmail);
                /*
                 * URL lURL = new
                 * URL("http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg");
                 * String lCID = ((HtmlEmail )lEmail).embed(lURL, "five feet
                 * further logo");
                 *
                 * //url = new URL(
                 * "http://five-feet-further.com/resources/css/IJX4FWDocu.css"
                 * ); // String css = ((HtmlEmail)lEmail).embed( url, "name
                 * of css" );
                 *
                 * ((HtmlEmail )lEmail).setHtmlMsg( "<html><body>" + "<style
                 * type=\"text/css\">" + "h1 { " + " font-family:arial,
                 * helvetica, sans-serif;" + " font-weight:bold;" + "
                 * font-size:18pt;" + "}" + "</style>" + // "<link
                 * href=\"cid:" + css + "\" type=\"text/css\"
                 * rel=\"stylesheet\">" + "<p><img src=\"cid:" + lCID +
                 * "\"></p>" + "<p><img
                 * src=\"http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg\"></p>"
                 * + lItem + "</body></html>");
                 */

                /*
                 * // Now the message body. Multipart mp = new
                 * MimeMultipart();
                 *
                 * BodyPart textPart = new MimeBodyPart(); // sets type to
                 * "text/plain" textPart.setText("Kann Ihr Browser keine
                 * HTML-Mails darstellen?");
                 *
                 * BodyPart pixPart = new MimeBodyPart();
                 * pixPart.setContent(lMsg, "text/html");
                 *
                 * // Collect the Parts into the MultiPart
                 * mp.addBodyPart(textPart); mp.addBodyPart(pixPart);
                 *
                 * // Put the MultiPart into the Message ((HtmlEmail)
                 * lEmail).setContent((MimeMultipart)mp); ((HtmlEmail)
                 * lEmail).buildMimeMessage();
                 *
                 * /*
                 * // ((HtmlEmail) lEmail).setContent(lMsg,
                 * Email.TEXT_HTML);
                 *
                 * // lHeaders.put("Innotrade-Id", "4711-0815"); //
                 * lHTML.setHeaders(lHeaders); // ((HtmlEmail)
                 * lEmail).setCharset("UTF-8"); // ((HtmlEmail)
                 * lEmail).setMsg(lMsg); lMM.setHeader("Innotrade-Id",
                 * "4711-0815");
                 *
                 * // ((HtmlEmail) lEmail).setContent(lTxtMsg,
                 * Email.TEXT_PLAIN);
                 */
                // String lTxtMsg = "Your Email-Client does not support HTML messages.";
                lHTML.setHtmlMsg(lBody);
                // lHTML.setTextMsg(lTxtMsg);
            } else {
                lEmail.setMsg(lBody);
            }
        }

        // add attachment(s), if such
        for (EmailAttachment lAttachment : lEmailAttachments) {
            ((MultiPartEmail) lEmail).attach(lAttachment);
        }

        // send the Email
        String lMsgId = lEmail.send();

        if (mLog.isInfoEnabled()) {
            lMsg = "Email successfully sent" + " from " + (lFrom != null ? lFrom : "(no sender)") + " to "
                    + (lTo != null ? lTo : "(no recipient)") + " cc " + (lCC != null ? lCC : "(no recipient)")
                    + ", subject " + (lSubject != null ? "'" + lSubject + "'" : "(no subject)") + ", msgId "
                    + lMsgId;
            mLog.info(lMsg);
        }
        lResponse.setInteger("code", 0);
        lResponse.setString("msg", "ok");
        lResponse.setString("msgId", lMsgId);
    } catch (EmailException lEx) {
        lMsg = lEx.getClass().getSimpleName() + " (" + lEx.getCause().getClass().getSimpleName() + "): "
                + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }
    return lResponse;
}

From source file:org.killbill.billing.plugin.notification.email.EmailSender.java

private void sendEmail(final List<String> to, final List<String> cc, final String subject, final Email email)
        throws EmailException {

    if (logOnly) {
        return;/*from  ww w .  j a  va 2  s . com*/
    }

    email.setSmtpPort(useSmtpPort);
    if (useSmtpAuth) {
        email.setAuthentication(smtpUserName, smtpUserPassword);
    }
    email.setHostName(smtpServerName);
    email.setFrom(from);

    email.setSubject(subject);

    if (to != null) {
        for (final String recipient : to) {
            email.addTo(recipient);
        }
    }

    if (cc != null) {
        for (final String recipient : cc) {
            email.addCc(recipient);
        }
    }

    email.setSSL(useSSL);

    logService.log(LogService.LOG_INFO,
            String.format("Sending email to %s, cc %s, subject %s", to, cc, subject));
    email.send();
}

From source file:org.killbill.billing.util.email.DefaultEmailSender.java

private void sendEmail(final List<String> to, final List<String> cc, final String subject, final Email email)
        throws EmailApiException {
    try {/*from  ww w. jav  a 2 s .c  o  m*/
        email.setSmtpPort(config.getSmtpPort());
        if (config.useSmtpAuth()) {
            email.setAuthentication(config.getSmtpUserName(), config.getSmtpPassword());
        }
        email.setHostName(config.getSmtpServerName());
        email.setFrom(config.getDefaultFrom());

        email.setSubject(subject);

        if (to != null) {
            for (final String recipient : to) {
                email.addTo(recipient);
            }
        }

        if (cc != null) {
            for (final String recipient : cc) {
                email.addCc(recipient);
            }
        }

        email.setSSL(config.useSSL());

        log.info("Sending email to='{}', cc='{}', subject='{}'", to, cc, subject);
        email.send();
    } catch (EmailException ee) {
        throw new EmailApiException(ee, ErrorCode.EMAIL_SENDING_FAILED);
    }
}

From source file:org.kuali.mobility.email.service.EmailServiceImpl.java

@Override
public boolean sendEmail(String body, String subject, String emailAddressTo, String emailAddressFrom) {
    boolean emailSent = false;

    if (emailAddressFrom == null || StringUtils.isEmpty(emailAddressFrom)) {
        emailAddressFrom = kmeProperties.getProperty("email.from");
        if (emailAddressFrom == null) {
            return emailSent;
        }/*from w w  w  .  ja  va  2 s  . co  m*/
    }

    if (emailAddressTo == null || StringUtils.isEmpty(emailAddressTo)) {
        return emailSent;
    }

    if (subject == null || StringUtils.isEmpty(subject)) {
        return emailSent;
    }

    if (body == null || StringUtils.isEmpty(body)) {
        return emailSent;
    }

    try {
        Email email = new SimpleEmail();
        email.setHostName(kmeProperties.getProperty("email.host"));
        email.setSmtpPort(Integer.parseInt(kmeProperties.getProperty("email.port")));
        email.setAuthenticator(new DefaultAuthenticator(kmeProperties.getProperty("email.username"),
                kmeProperties.getProperty("email.passsword")));
        email.setSSLOnConnect(true);
        email.setFrom(emailAddressFrom);
        email.setSubject(subject);
        email.setMsg(body);
        email.addTo(emailAddressTo);
        email.send();
        emailSent = true;
        LOG.debug("Mail Sent...");
    } catch (EmailException e) {
        LOG.error("Mail send failed...", e);
    }
    return emailSent;
}

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 {//  w w  w. j a va2  s.  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  ww w.  j  ava 2  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.jav a 2s  .  c om*/
            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  w ww .j  a v  a  2  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   ww w.jav a  2  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.ms123.common.workflow.tasks.TaskMailExecutor.java

protected void setMailServerProperties(Email email) {
    ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();

    String host = processEngineConfiguration.getMailServerHost();
    if (host == null) {
        throw new RuntimeException("TaskMailExecutor:Could not send email: no SMTP host is configured");
    }//from w  w w  .  j ava2 s .  co  m
    email.setHostName(host);

    int port = processEngineConfiguration.getMailServerPort();
    email.setSmtpPort(port);

    email.setSSL(processEngineConfiguration.getMailServerUseSSL());
    email.setTLS(processEngineConfiguration.getMailServerUseTLS());

    String user = processEngineConfiguration.getMailServerUsername();
    String password = processEngineConfiguration.getMailServerPassword();
    if (user != null && password != null) {
        email.setAuthentication(user, password);
    }
}