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

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

Introduction

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

Prototype

public JavaMailSenderImpl() 

Source Link

Document

Create a new instance of the JavaMailSenderImpl class.

Usage

From source file:gr.abiss.calipso.mail.MailSender.java

private void initMailSenderFromConfig(Map<String, String> config) {
    String host = config.get("mail.server.host");
    if (host == null) {
        logger.warn("'mail.server.host' config is null, mail sender not initialized");
        return;/*w w w .  j  a v a 2  s .  c o  m*/
    }
    String port = config.get("mail.server.port");
    String tempUrl = config.get("calipso.url.base");
    from = config.get("mail.from");
    prefix = config.get("mail.subject.prefix");
    String userName = config.get("mail.server.username");
    String password = config.get("mail.server.password");
    String startTls = config.get("mail.server.starttls.enable");
    logger.info("initializing email adapter: host = '" + host + "', port = '" + port + "', url = '" + url
            + "', from = '" + from + "', prefix = '" + prefix + "'");
    this.prefix = prefix == null ? "[calipso]" : prefix;
    this.from = from == null ? "calipsoService" : from;
    this.url = tempUrl == null ? "http://localhost/calipso/" : tempUrl;
    if (!this.url.endsWith("/")) {
        this.url = url + "/";
    }
    int p = 25;
    if (port != null) {
        try {
            p = Integer.parseInt(port);
        } catch (NumberFormatException e) {
            logger.warn("mail.server.port not an integer : '" + port + "', defaulting to 25");
        }
    }
    sender = new JavaMailSenderImpl();
    sender.setHost(host);
    sender.setPort(p);
    if (userName != null) {
        // authentication requested
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        if (startTls != null && startTls.toLowerCase().equals("true")) {
            props.put("mail.smtp.starttls.enable", "true");
        }
        sender.setJavaMailProperties(props);
        sender.setUsername(userName);
        sender.setPassword(password);
    }
    logger.info("email sender initialized from config: host = '" + host + "', port = '" + p + "'");
}

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

public JavaMailSender getMailSender() {
    if (mailSender == null) {
        final JavaMailSenderImpl impl = new JavaMailSenderImpl();
        impl.setHost(smtpServer);//w  w w .  j a v  a  2s .c o m
        impl.setPort(smtpPort);
        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.craftercms.commons.mail.impl.EmailFactoryImplTest.java

private JavaMailSenderImpl createMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("localhost");
    mailSender.setPort(25);/*from ww  w .  ja va2s . c  o m*/
    mailSender.setProtocol("smtp");
    mailSender.setDefaultEncoding(ENCODING);

    return mailSender;
}

From source file:org.emonocot.service.impl.JavaMailSenderImplFactory.java

/**
 * @return the instantiate JavaMailSender
 *///from   w  w  w.  j av  a 2s . c o  m
private void instantiate() {
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
    if (StringUtils.isNotBlank(username)) {
        javaMailSender.setUsername(username);
    }
    if (StringUtils.isNotBlank(password)) {
        javaMailSender.setPassword(password);
    }
    javaMailSender.setJavaMailProperties(javaMailProperties);
    sender = javaMailSender;
}

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);//from   www .j  a  v a2  s  .c o m
    result.setPort(port);
    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;/*from   w  w w  .  j av  a  2s . c  o m*/

    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 {
            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));
            }//from  w  ww  .j av  a  2s. c o  m
        }
    }

    // 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 .  ja v  a 2s  . c o  m*/
        // 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.springframework.integration.samples.mailattachments.MimeMessageParsingTest.java

/**
 * This test will create a Mime Message that contains an Attachment, send it
 * to an SMTP Server (Using Wiser) and retrieve and process the Mime Message.
 *
 * This test verifies that the parsing of the retrieved Mime Message is
 * successful and that the correct number of {@link EmailFragment}s is created.
 *///from  w  ww. j av a2s.com
@Test
public void testProcessingOfEmailAttachments() {

    final JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setPort(this.wiserPort);

    final MimeMessage message = mailSender.createMimeMessage();
    final String pictureName = "picture.png";

    final ByteArrayResource byteArrayResource = getFileData(pictureName);

    try {

        final MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom("testfrom@springintegration.org");
        helper.setTo("testto@springintegration.org");
        helper.setSubject("Parsing of Attachments");
        helper.setText("Spring Integration Rocks!");

        helper.addAttachment(pictureName, byteArrayResource, "image/png");

    } catch (MessagingException e) {
        throw new MailParseException(e);
    }

    mailSender.send(message);

    final List<WiserMessage> wiserMessages = wiser.getMessages();

    Assert.assertTrue(wiserMessages.size() == 1);

    boolean foundTextMessage = false;
    boolean foundPicture = false;

    for (WiserMessage wiserMessage : wiserMessages) {

        final List<EmailFragment> emailFragments = new ArrayList<EmailFragment>();

        try {
            final MimeMessage mailMessage = wiserMessage.getMimeMessage();
            EmailParserUtils.handleMessage(null, mailMessage, emailFragments);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving Mime Message.");
        }

        Assert.assertTrue(emailFragments.size() == 2);

        for (EmailFragment emailFragment : emailFragments) {
            if ("picture.png".equals(emailFragment.getFilename())) {
                foundPicture = true;
            }

            if ("message.txt".equals(emailFragment.getFilename())) {
                foundTextMessage = true;
            }
        }

        Assert.assertTrue(foundPicture);
        Assert.assertTrue(foundTextMessage);

    }
}

From source file:org.springframework.integration.samples.mailattachments.MimeMessageParsingTest.java

/**
 * This test will create a Mime Message that in return contains another
 * mime message. The nested mime message contains an attachment.
 *
 * The root message consist of both HTML and Text message.
 *
 */// w  ww .j  a  v  a 2s. c o  m
@Test
public void testProcessingOfNestedEmailAttachments() {

    final JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setPort(this.wiserPort);

    final MimeMessage rootMessage = mailSender.createMimeMessage();

    try {

        final MimeMessageHelper messageHelper = new MimeMessageHelper(rootMessage, true);

        messageHelper.setFrom("testfrom@springintegration.org");
        messageHelper.setTo("testto@springintegration.org");
        messageHelper.setSubject("Parsing of Attachments");
        messageHelper.setText("Spring Integration Rocks!", "Spring Integration <b>Rocks</b>!");

        final String pictureName = "picture.png";

        final ByteArrayResource byteArrayResource = getFileData(pictureName);

        messageHelper.addInline("picture12345", byteArrayResource, "image/png");

    } catch (MessagingException e) {
        throw new MailParseException(e);
    }

    mailSender.send(rootMessage);

    final List<WiserMessage> wiserMessages = wiser.getMessages();

    Assert.assertTrue(wiserMessages.size() == 1);

    boolean foundTextMessage = false;
    boolean foundPicture = false;
    boolean foundHtmlMessage = false;

    for (WiserMessage wiserMessage : wiserMessages) {

        List<EmailFragment> emailFragments = new ArrayList<EmailFragment>();

        try {

            final MimeMessage mailMessage = wiserMessage.getMimeMessage();
            EmailParserUtils.handleMessage(null, mailMessage, emailFragments);

        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving Mime Message.");
        }

        Assert.assertTrue(emailFragments.size() == 3);

        for (EmailFragment emailFragment : emailFragments) {
            if ("<picture12345>".equals(emailFragment.getFilename())) {
                foundPicture = true;
            }

            if ("message.txt".equals(emailFragment.getFilename())) {
                foundTextMessage = true;
            }

            if ("message.html".equals(emailFragment.getFilename())) {
                foundHtmlMessage = true;
            }
        }

        Assert.assertTrue(foundPicture);
        Assert.assertTrue(foundTextMessage);
        Assert.assertTrue(foundHtmlMessage);

    }
}