Example usage for org.springframework.mail.javamail JavaMailSenderImpl setHost

List of usage examples for org.springframework.mail.javamail JavaMailSenderImpl setHost

Introduction

In this page you can find the example usage for org.springframework.mail.javamail JavaMailSenderImpl setHost.

Prototype

public void setHost(@Nullable String host) 

Source Link

Document

Set the mail server host, typically an SMTP host.

Usage

From source file:com.glaf.mail.business.MailSendThread.java

public void run() {
    logger.debug("---------------send mail----------------------------");
    if (mailItem != null && MailTools.isMailAddress(mailItem.getMailTo())) {
        /**/*w  ww  . j a va2  s. c  o m*/
         * ?5????
         */
        if (mailItem.getRetryTimes() > 5) {
            return;
        }
        /**
         * ????????
         */
        if (mailItem.getSendStatus() == 1) {
            return;
        }
        /**
         * ????
         */
        if (mailItem.getLastModified() < (System.currentTimeMillis() - DateUtils.DAY * 30)) {
            return;
        }

        MailAccount mailAccount = null;
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        List<MailAccount> accounts = task.getAccounts();
        if (accounts.size() > 1) {
            java.util.Random r = new java.util.Random();
            mailAccount = accounts.get(Math.abs(r.nextInt(accounts.size())));
        } else {
            mailAccount = accounts.get(0);
        }

        logger.debug("send account:" + mailAccount);

        String content = task.getContent();

        if (StringUtils.isEmpty(task.getCallbackUrl())) {
            String serviceUrl = SystemConfig.getServiceUrl();
            String callbackUrl = serviceUrl + "/website/mail/receive/view";
            task.setCallbackUrl(callbackUrl);
        }

        if (StringUtils.isNotEmpty(task.getCallbackUrl())) {
            MxMailHelper mailHelper = new MxMailHelper();
            String messageId = "{taskId:\"" + task.getId() + "\",itemId:\"" + mailItem.getId() + "\"}";
            messageId = RequestUtils.encodeString(messageId);
            String url = task.getCallbackUrl() + "?messageId=" + messageId;
            content = mailHelper.embedCallbackScript(content, url);
        }

        MailMessage mailMessage = new MailMessage();
        mailMessage.setFrom(mailAccount.getMailAddress());
        mailMessage.setTo(mailItem.getMailTo());
        mailMessage.setContent(content);
        mailMessage.setSubject(task.getSubject());
        mailMessage.setSaveMessage(false);

        javaMailSender.setHost(mailAccount.getSmtpServer());
        javaMailSender.setPort(mailAccount.getSendPort() > 0 ? mailAccount.getSendPort() : 25);
        javaMailSender.setProtocol(JavaMailSenderImpl.DEFAULT_PROTOCOL);
        javaMailSender.setUsername(mailAccount.getUsername());
        if (StringUtils.isNotEmpty(mailAccount.getPassword())) {
            String pwd = RequestUtils.decodeString(mailAccount.getPassword());
            javaMailSender.setPassword(pwd);
            // logger.debug("send account pwd:"+pwd);
        }
        javaMailSender.setDefaultEncoding("GBK");

        try {
            mailItem.setSendDate(new Date());
            mailItem.setRetryTimes(mailItem.getRetryTimes() + 1);
            MailSender mailSender = ContextFactory.getBean("mailSender");
            mailSender.send(javaMailSender, mailMessage);
            mailItem.setSendStatus(1);
        } catch (Throwable ex) {
            mailItem.setSendStatus(-1);
            if (LogUtils.isDebug()) {
                logger.debug(ex);
                ex.printStackTrace();
            }
            if (ex instanceof javax.mail.internet.ParseException) {
                mailItem.setSendStatus(-10);
            } else if (ex instanceof javax.mail.AuthenticationFailedException) {
                mailItem.setSendStatus(-20);
            } else if (ex instanceof javax.mail.internet.AddressException) {
                mailItem.setSendStatus(-30);
            } else if (ex instanceof javax.mail.SendFailedException) {
                mailItem.setSendStatus(-40);
            } else if (ex instanceof java.net.UnknownHostException) {
                mailItem.setSendStatus(-50);
            } else if (ex instanceof java.net.SocketException) {
                mailItem.setSendStatus(-60);
            } else if (ex instanceof java.io.IOException) {
                mailItem.setSendStatus(-70);
            } else if (ex instanceof java.net.ConnectException) {
                mailItem.setSendStatus(-80);
            } else if (ex instanceof javax.mail.MessagingException) {
                mailItem.setSendStatus(-90);
                if (ex.getMessage().indexOf("response: 554") != -1) {
                    mailItem.setSendStatus(-99);
                }
            }
        } finally {
            mailDataFacede.updateMail(task.getId(), mailItem);
        }
    }
}

From source file:nl.strohalm.cyclos.entities.settings.MailSettings.java

public JavaMailSender getMailSender() {
    if (mailSender == null) {
        final JavaMailSenderImpl impl = new JavaMailSenderImpl();
        impl.setHost(smtpServer);
        impl.setPort(smtpPort);//from   w w w  .  java2  s  .  co m
        final Properties properties = new Properties();
        if (StringUtils.isNotEmpty(smtpUsername)) {
            // Use authentication
            properties.setProperty("mail.smtp.auth", "true");
            impl.setUsername(smtpUsername);
            impl.setPassword(smtpPassword);
        }
        if (smtpUseTLS) {
            properties.setProperty("mail.smtp.starttls.enable", "true");
        }
        impl.setJavaMailProperties(properties);
        mailSender = impl;
    }
    return mailSender;
}

From source file:org.apache.syncope.core.logic.NotificationTest.java

@Before
public void setupSMTP() throws Exception {
    JavaMailSenderImpl sender = (JavaMailSenderImpl) mailSender;
    sender.setDefaultEncoding(SyncopeConstants.DEFAULT_ENCODING);
    sender.setHost(SMTP_HOST);
    sender.setPort(SMTP_PORT);/*from  w  w w .ja  v a  2 s.  com*/
}

From source file:org.apache.syncope.core.notification.NotificationTest.java

@Before
public void setupSMTP() throws Exception {
    JavaMailSenderImpl sender = (JavaMailSenderImpl) mailSender;
    sender.setDefaultEncoding(SyncopeConstants.DEFAULT_ENCODING);
    sender.setHost(smtpHost);
    sender.setPort(smtpPort);//from ww  w .  j ava  2  s.c  o m
    sender.setUsername(mailAddress);
    sender.setPassword(mailPassword);
}

From source file:org.craftercms.commons.mail.impl.EmailFactoryImplTest.java

private JavaMailSenderImpl createMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("localhost");
    mailSender.setPort(25);/*w w  w. ja v  a2  s. co m*/
    mailSender.setProtocol("smtp");
    mailSender.setDefaultEncoding(ENCODING);

    return mailSender;
}

From source file:org.haiku.haikudepotserver.config.AppConfig.java

@Bean
public MailSender mailSender(@Value("${smtp.host}") String host, @Value("${smtp.port:25}") Integer port,
        @Value("${smtp.auth:false}") Boolean smtpAuth, @Value("${smtp.starttls:false}") Boolean startTls,
        @Value("${smtp.username:}") String username, @Value("${smtp.password:}") String password) {

    Properties properties = new Properties();
    properties.put("mail.smtp.auth", smtpAuth);
    properties.put("mail.smtp.starttls.enable", startTls);

    JavaMailSenderImpl result = new JavaMailSenderImpl();

    result.setHost(host);
    result.setPort(port);// w  w  w .j  a  v  a 2s. c om
    result.setProtocol("smtp");
    result.setJavaMailProperties(properties);

    if (StringUtils.isNotBlank(username)) {
        result.setUsername(username);
    }

    if (StringUtils.isNotBlank(password)) {
        result.setPassword(password);
    }

    return result;
}

From source file:org.kuali.kra.service.impl.KcEmailServiceImpl.java

private JavaMailSender createSender() {
    Properties props = getConfigProperties();
    JavaMailSenderImpl sender = null;

    if (props != null && StringUtils.isNotBlank(props.getProperty("mail.smtp.host"))
            && StringUtils.isNotBlank(props.getProperty("mail.smtp.port"))
            && StringUtils.isNotBlank(props.getProperty("mail.smtp.user"))
            && StringUtils.isNotBlank(props.getProperty("mail.user.credentials"))) {
        try {//w w w  .j  a v  a 2s .  c om
            sender = new JavaMailSenderImpl();

            sender.setJavaMailProperties(props);
            sender.setHost(props.getProperty("mail.smtp.host"));
            sender.setPort(Integer.parseInt(props.getProperty("mail.smtp.port")));
            sender.setUsername(props.getProperty("mail.smtp.user"));
            sender.setPassword(props.getProperty("mail.user.credentials"));
        } catch (Exception e) {
            LOG.warn(
                    "Unable to create email sender due to invalid configuration. The properties [mail.smtp.host, "
                            + "mail.smtp.port, mail.smtp.user, mail.user.credentials] need to be set.");
            sender = null;
        }
    } else {
        LOG.warn("Unable to create email sender due to missing configuration.  The properties [mail.smtp.host, "
                + "mail.smtp.port, mail.smtp.user, mail.user.credentials] need to be set.");
    }

    return sender;
}

From source file:org.kuali.rice.core.mail.MailSenderFactoryBean.java

@Override
protected Object createInstance() throws Exception {
    // Retrieve "mail.*" properties from the configuration system and construct a Properties object
    Properties properties = new Properties();
    Properties configProps = ConfigContext.getCurrentContextConfig().getProperties();
    LOG.debug("createInstance(): collecting mail properties.");
    for (Object keyObj : configProps.keySet()) {
        if (keyObj instanceof String) {
            String key = (String) keyObj;
            if (key.startsWith(MAIL_PREFIX)) {
                properties.put(key, configProps.get(key));
            }// w ww . j  a v a2s .  c  om
        }
    }

    // Construct an appropriate Java Mail Session
    // If username and password properties are found, construct a Session with SMTP authentication
    String username = properties.getProperty(USERNAME_PROPERTY);
    String password = properties.getProperty(PASSWORD_PROPERTY);
    if (username != null && password != null) {
        mailSession = Session.getInstance(properties, new SimpleAuthenticator(username, password));
        LOG.info("createInstance(): Initializing mail session using SMTP authentication.");
    } else {
        mailSession = Session.getInstance(properties);
        LOG.info("createInstance(): Initializing mail session. No SMTP authentication.");
    }

    // Construct and return a Spring Java Mail Sender
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    LOG.debug("createInstance(): setting SMTP host.");
    mailSender.setHost(properties.getProperty(HOST_PROPERTY));
    if (properties.getProperty(PORT_PROPERTY) != null) {
        LOG.debug("createInstance(): setting SMTP port.");
        int smtpPort = Integer.parseInt(properties.getProperty(PORT_PROPERTY).trim());
        mailSender.setPort(smtpPort);
    }
    String protocol = properties.getProperty(PROTOCOL_PROPERTY);
    if (StringUtils.isNotBlank(protocol)) {
        LOG.debug("createInstance(): setting mail transport protocol = " + protocol);
        mailSender.setProtocol(protocol);
    }
    mailSender.setSession(mailSession);

    LOG.info("createInstance(): Mail Sender Factory Bean initialized.");
    return mailSender;
}

From source file:org.mifosplatform.infrastructure.reportmailingjob.service.ReportMailingJobEmailServiceImpl.java

@Override
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
    try {//from   w ww.  j  ava  2 s .  com
        // get all ReportMailingJobConfiguration objects from the database
        this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService
                .retrieveAllReportMailingJobConfigurations();

        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setHost(this.getReportSmtpServer());
        javaMailSenderImpl.setPort(this.getRerportSmtpPort());
        javaMailSenderImpl.setUsername(this.getReportSmtpUsername());
        javaMailSenderImpl.setPassword(this.getReportSmtpPassword());
        javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties());

        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setTo(reportMailingJobEmailData.getTo());
        mimeMessageHelper.setFrom(this.getReportSmtpFromAddress());
        mimeMessageHelper.setText(reportMailingJobEmailData.getText());
        mimeMessageHelper.setSubject(reportMailingJobEmailData.getSubject());

        if (reportMailingJobEmailData.getAttachment() != null) {
            mimeMessageHelper.addAttachment(reportMailingJobEmailData.getAttachment().getName(),
                    reportMailingJobEmailData.getAttachment());
        }

        javaMailSenderImpl.send(mimeMessage);
    }

    catch (MessagingException e) {
        // handle the exception
        e.printStackTrace();
    }
}

From source file:org.openhie.openempi.webapp.action.BaseActionTestCase.java

@Override
protected void onSetUpBeforeTransaction() throws Exception {
    smtpPort = smtpPort + (int) (Math.random() * 100);

    LocalizedTextUtil.addDefaultResourceBundle(Constants.BUNDLE_KEY);
    ActionContext.getContext().setSession(new HashMap());

    // change the port on the mailSender so it doesn't conflict with an 
    // existing SMTP server on localhost
    JavaMailSenderImpl mailSender = (JavaMailSenderImpl) applicationContext.getBean("mailSender");
    mailSender.setPort(getSmtpPort());//from  w w  w.  j a  v a  2 s .  c o  m
    mailSender.setHost("localhost");

    // populate the request so getRequest().getSession() doesn't fail in BaseAction.java
    ServletActionContext.setRequest(new MockHttpServletRequest());
}