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

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

Introduction

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

Prototype

public void setSmtpPort(final int aPortNumber) 

Source Link

Document

Set the port number of the outgoing 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   www  . j  a  v  a2s .c om*/
        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.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(/*from  www. jav  a 2  s. c  o m*/
            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);
    try {//from  w ww  .  j a  va  2s . c  om
        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  www .j av a2s . 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  av a 2s  .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);
    }
}

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

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

    String host = processEngineConfiguration.getMailServerHost();
    if (host == null) {
        throw new RuntimeException("TaskSendExecutor:Could not send email: no SMTP host is configured");
    }/*from  www  .jav a2 s  .c o 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);
    }
}

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//w  w w .  j a  va 2 s. c o m
 */
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 {//ww w.  jav a  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
 * //from w w  w.j a va2 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.SMTPHandler.java

/**
 * use this server to send a mail/* ww  w .  j a va2s.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;
}