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

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

Introduction

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

Prototype

public String getHostName() 

Source Link

Document

Gets the host name of the SMTP server,

Usage

From source file:de.hybris.platform.test.MailUtilsTest.java

@Test
public void testPreConfiguredEmail() throws EmailException {
    //read out original values
    final String orgSMTPServer = Config.getString(Config.Params.MAIL_SMTP_SERVER, null);
    final String orgFrom = Config.getString(Config.Params.MAIL_FROM, null);
    final String orgUseTLS = Config.getString(Config.Params.MAIL_USE_TLS, Boolean.FALSE.toString());
    final String orgSMTPPort = Config.getString(Config.Params.MAIL_SMTP_PORT, "-1");

    //define test values
    String smtpPort = "42";
    String smtpServer = "smtp.hybris.de";
    String from = "from@hybris.de";
    String useTLS = Boolean.FALSE.toString();
    //test test values
    Config.setParameter(Config.Params.MAIL_SMTP_SERVER, smtpServer);
    Config.setParameter(Config.Params.MAIL_SMTP_PORT, smtpPort);
    Config.setParameter(Config.Params.MAIL_FROM, from);
    Config.setParameter(Config.Params.MAIL_USE_TLS, useTLS);
    //check test values
    Email email = MailUtils.getPreConfiguredEmail();
    assertEquals(email.getSmtpPort(), smtpPort);
    assertEquals(email.getHostName(), smtpServer);
    assertEquals(email.getFromAddress().getAddress(), from);
    assertEquals(Boolean.toString(email.isTLS()), useTLS);

    email = null;//from w  w  w . j a  v  a 2s  .co  m

    //define new test values
    smtpPort = "43";
    smtpServer = "smtp2.hybris.de";
    from = "from2@hybris.de";
    useTLS = Boolean.TRUE.toString();
    //set new test values
    Config.setParameter(Config.Params.MAIL_SMTP_SERVER, smtpServer);
    Config.setParameter(Config.Params.MAIL_SMTP_PORT, smtpPort);
    Config.setParameter(Config.Params.MAIL_FROM, from);
    Config.setParameter(Config.Params.MAIL_USE_TLS, useTLS);
    //check changed test values
    email = MailUtils.getPreConfiguredEmail();
    assertEquals(email.getSmtpPort(), smtpPort);
    assertEquals(email.getHostName(), smtpServer);
    assertEquals(email.getFromAddress().getAddress(), from);
    assertEquals(Boolean.toString(email.isTLS()), useTLS);

    //restore old values
    Config.setParameter(Config.Params.MAIL_SMTP_SERVER, orgSMTPServer);
    Config.setParameter(Config.Params.MAIL_SMTP_PORT, orgSMTPPort);
    Config.setParameter(Config.Params.MAIL_FROM, orgFrom);
    Config.setParameter(Config.Params.MAIL_USE_TLS, orgUseTLS);
}

From source file:com.github.triceo.robozonky.notifications.email.AbstractEmailingListener.java

@Override
public void handle(final T event) {
    if (!this.shouldSendEmail(event)) {
        LOGGER.debug("Will not send e-mail.");
        return;//  ww w.  ja va2 s  . c o m
    } else
        try {
            final Email email = AbstractEmailingListener.createNewEmail(properties);
            email.setSubject(this.getSubject(event));
            email.setMsg(TemplateProcessor.INSTANCE.process(this.getTemplateFileName(), this.getData(event)));
            LOGGER.debug("Will send '{}' from {} to {} through {}:{} as {}.", email.getSubject(),
                    email.getFromAddress(), email.getToAddresses(), email.getHostName(), email.getSmtpPort(),
                    properties.getSmtpUsername());
            email.send();
            emailsOfThisType.increase();
            this.properties.getGlobalCounter().increase();
        } catch (final Exception ex) {
            throw new RuntimeException("Failed processing event.", ex);
        }

}

From source file:org.apache.sling.commons.messaging.mail.internal.SimpleMailBuilderIT.java

@Test
public void testBuildWithDefaults() throws Exception {
    final MailBuilder mailBuilder = getService(MailBuilder.class);
    final Email email = mailBuilder.build("Stop your messing around, Better think of your future...",
            "rudy@ghosttown", Collections.emptyMap());
    email.buildMimeMessage();/*from   www. j  a v  a 2  s  .c  o  m*/
    final byte[] bytes = MailUtil.toByteArray(email);
    final String mail = new String(bytes, StandardCharsets.UTF_8);
    logger.debug("mail: " + mail);
    assertEquals("rudy@ghosttown", email.getToAddresses().get(0).getAddress());
    assertEquals("Rudy, A Message to You", email.getSubject());
    assertEquals("dandy.livingstone@kingston.jamaica", email.getFromAddress().getAddress());
    assertEquals("localhost", email.getHostName());
    logger.debug(email.getMimeMessage().getContent().toString());
}

From source file:org.apache.sling.commons.messaging.mail.internal.SimpleMailBuilderIT.java

@Test
public void testBuildWithData() throws Exception {
    final MailBuilder mailBuilder = getService(MailBuilder.class);
    final Map<String, String> configuration = new HashMap<>();
    configuration.put("mail.subject", "Rudy, A Message to You");
    configuration.put("mail.from", "specials@thespecials.com");
    final Map data = Collections.singletonMap("mail", configuration);
    final Email email = mailBuilder.build("A Message to You, Rudy", "rudy@ghosttown", data);
    email.buildMimeMessage();/*w w w.j  av  a2  s.  c o  m*/
    final byte[] bytes = MailUtil.toByteArray(email);
    final String mail = new String(bytes, StandardCharsets.UTF_8);
    logger.debug("mail: " + mail);
    assertEquals("rudy@ghosttown", email.getToAddresses().get(0).getAddress());
    assertEquals("Rudy, A Message to You", email.getSubject());
    assertEquals("specials@thespecials.com", email.getFromAddress().getAddress());
    assertEquals("localhost", email.getHostName());
    logger.debug(email.getMimeMessage().getContent().toString());
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

/**
 * {@inheritDoc}//from   w ww .j  a  v  a  2s .  c o m
 */
@Override
public void send(final Email email) throws EmailException {

    if (email == null || ArrayUtils.isEmpty(email.getToAddresses())) {
        // does nothing.
        throw new EmailException("Email object null or invalid.");
    }

    // Simple email.
    final SimpleEmail simpleEmail = new SimpleEmail();

    // Mail content parameters.
    simpleEmail.setFrom(email.getFromAddress(), email.getFromName());
    for (final String address : email.getToAddresses()) {
        simpleEmail.addTo(address);
    }
    if (ArrayUtils.isNotEmpty(email.getCcAddresses())) {
        for (final String address : email.getCcAddresses()) {
            simpleEmail.addCc(address);
        }
    }
    simpleEmail.setSubject(email.getSubject());
    simpleEmail.setContent(email.getContent(), email.getContentType());

    // Mail sending parameters.
    simpleEmail.setCharset(email.getEncoding());
    simpleEmail.setHostName(email.getHostName());
    simpleEmail.setSmtpPort(email.getSmtpPort());

    // Authentication is needed.
    final String userName = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();
    if (userName != null && password != null) {
        simpleEmail.setAuthentication(userName, password);
    }

    // Sends the mail.
    simpleEmail.send();
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

@Override
public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException {
    final String user = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();

    final Properties properties = new Properties();
    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL);
    properties.setProperty(MAIL_SMTP_HOST, email.getHostName());
    properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort()));

    final StringBuilder toBuilder = new StringBuilder();
    for (final String to : email.getToAddresses()) {
        if (toBuilder.length() > 0) {
            toBuilder.append(',');
        }/*  w w w.j  a  v a2s .  c o m*/
        toBuilder.append(to);
    }

    final StringBuilder ccBuilder = new StringBuilder();
    if (email.getCcAddresses().length > 0) {
        for (final String cc : email.getCcAddresses()) {
            if (ccBuilder.length() > 0) {
                ccBuilder.append(',');
            }
            ccBuilder.append(cc);
        }
    }

    final Session session = javax.mail.Session.getInstance(properties);
    try {
        final DataSource attachment = new ByteArrayDataSource(fileStream,
                FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType());

        final Transport transport = session.getTransport();

        if (password != null) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }

        final MimeMessage message = new MimeMessage(session);

        // Configures the headers.
        message.setFrom(new InternetAddress(email.getFromAddress(), false));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false));
        if (email.getCcAddresses().length > 0) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false));
        }

        message.setSubject(email.getSubject(), email.getEncoding());

        // Html body part.
        final MimeMultipart textMultipart = new MimeMultipart("alternative");

        final MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\"");
        textMultipart.addBodyPart(htmlBodyPart);

        final MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(textMultipart);

        // Attachment body part.
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(attachment));
        attachmentPart.setFileName(fileName);
        attachmentPart.setDescription(fileName);

        // Mail multipart content.
        final MimeMultipart contentMultipart = new MimeMultipart("related");
        contentMultipart.addBodyPart(textBodyPart);
        contentMultipart.addBodyPart(attachmentPart);

        message.setContent(contentMultipart);
        message.saveChanges();

        // Sends the mail.
        transport.sendMessage(message, message.getAllRecipients());

    } catch (UnsupportedEncodingException ex) {
        throw new EmailException(
                "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex);

    } catch (IOException ex) {
        throw new EmailException("An error occured while reading the attachment of an email.", ex);

    } catch (MessagingException ex) {
        throw new EmailException("An error occured while sending an email.", ex);
    }
}