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

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

Introduction

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

Prototype

public String getSubject() 

Source Link

Document

Gets the subject of the email.

Usage

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  va 2s  .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();/*from w ww  .  j a va  2  s. c  om*/
    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.fao.geonet.util.MailUtil.java

private static Boolean send(final Email email) {
    try {// w ww. j a v  a2  s .c  om
        email.send();

    } catch (EmailException e) {
        Log.error(LOG_MODULE_NAME, "Error sending email \"" + email.getSubject() + "\"", e);
        return false;
    }

    return true;
}

From source file:org.fao.geonet.util.MailUtil.java

private static void sendWithThread(@Nonnull final Email email) {
    try {//from  w  ww  . j ava 2s . c o m
        Thread t = new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    email.send();
                } catch (EmailException e) {
                    Log.error(LOG_MODULE_NAME,
                            "Error sending email \"" + email.getSubject() + "\" unsing other " + "thread", e);
                }
            }
        };

        t.start();
    } catch (Exception e) {
        Log.error(LOG_MODULE_NAME,
                "Error sending email \"" + email.getSubject() + "\" unsing other " + "thread", e);
    }
}

From source file:org.polymap.rhei.um.email.EmailService.java

public void send(Email email) throws EmailException {
    String env = System.getProperty("org.polymap.rhei.um.SMTP");
    if (env == null) {
        throw new IllegalStateException(
                "Environment variable missing: org.polymap.rhei.um.SMTP. Format: <host>|<login>|<passwd>|<from>");
    }/*ww  w .  ja  va  2s  . c  om*/
    String[] parts = StringUtils.split(env, "|");
    if (parts.length < 3 || parts.length > 4) {
        throw new IllegalStateException(
                "Environment variable wrong: org.polymap.rhei.um.SMTP. Format: <host>|<login>|<passwd>|<from> : "
                        + env);
    }

    email.setDebug(true);
    email.setHostName(parts[0]);
    //email.setSmtpPort( 465 );
    //email.setSSLOnConnect( true );
    email.setAuthenticator(new DefaultAuthenticator(parts[1], parts[2]));
    if (email.getFromAddress() == null && parts.length == 4) {
        email.setFrom(parts[3]);
    }
    if (email.getSubject() == null) {
        throw new EmailException("Missing subject.");
    }
    email.send();
}

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

@Override
public void send(Email email) throws EmailException {
    if (email == null || ArrayUtils.isEmpty(email.getToAddresses())) {
        // does nothing.
        throw new EmailException("Email object null or invalid.");
    }/*from  w w w  . ja v a 2  s . co m*/

    Assert.assertNotNull(email.getFromAddress());
    Assert.assertFalse(email.getFromAddress().trim().isEmpty());

    Assert.assertNotNull(email.getSubject());
    Assert.assertFalse(email.getSubject().isEmpty());

    Assert.assertNotNull(email.getContent());
    Assert.assertFalse(email.getContent().isEmpty());

    Assert.assertNotNull(email.getContentType());
    Assert.assertFalse(email.getContentType().isEmpty());

    Assert.assertNotNull(email.getEncoding());
    Assert.assertFalse(email.getEncoding().isEmpty());

    // Building the output
    System.out.println("From: \"" + email.getFromName() + "\" <" + email.getFromAddress() + '>');

    final StringBuilder toAddressesBuilder = new StringBuilder();
    for (final String address : email.getToAddresses()) {
        toAddressesBuilder.append(address).append(", ");
    }
    toAddressesBuilder.setLength(toAddressesBuilder.length() - 2);
    System.out.println("To: " + toAddressesBuilder);

    if (ArrayUtils.isNotEmpty(email.getCcAddresses())) {
        final StringBuilder ccAddressesBuilder = new StringBuilder();
        for (final String address : email.getCcAddresses()) {
            ccAddressesBuilder.append(address).append(", ");
        }
        ccAddressesBuilder.setLength(toAddressesBuilder.length() - 2);
        System.out.println("Cc: " + ccAddressesBuilder);
    }

    System.out.println("Subject: " + email.getSubject());
    final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
    System.out.println("Date: " + dateFormat.format(new Date()));
    System.out.println("Content-Type: " + email.getContentType() + ";charset=" + email.getEncoding());

    System.out.println();
    System.out.println(email.getContent());
}

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

/**
 * {@inheritDoc}//  www  . ja v  a2s.c  om
 */
@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 ww  .  j av  a  2 s .  co 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);
    }
}

From source file:org.sonatype.nexus.internal.email.EmailManagerImpl.java

/**
 * Apply server configuration to email./*w  w w  . j a v  a  2 s  . c  o  m*/
 */
@VisibleForTesting
Email apply(final EmailConfiguration configuration, final Email mail) throws EmailException {
    mail.setHostName(configuration.getHost());
    mail.setSmtpPort(configuration.getPort());
    mail.setAuthentication(configuration.getUsername(), configuration.getPassword());

    mail.setStartTLSEnabled(configuration.isStartTlsEnabled());
    mail.setStartTLSRequired(configuration.isStartTlsRequired());
    mail.setSSLOnConnect(configuration.isSslOnConnectEnabled());
    mail.setSSLCheckServerIdentity(configuration.isSslCheckServerIdentityEnabled());
    mail.setSslSmtpPort(Integer.toString(configuration.getPort()));

    // default from address
    if (mail.getFromAddress() == null) {
        mail.setFrom(configuration.getFromAddress());
    }

    // apply subject prefix if configured
    String subjectPrefix = configuration.getSubjectPrefix();
    if (subjectPrefix != null) {
        String subject = mail.getSubject();
        mail.setSubject(String.format("%s %s", subjectPrefix, subject));
    }

    // do this last (mail properties are set up from the email fields when you get the mail session)
    if (configuration.isNexusTrustStoreEnabled()) {
        SSLContext context = trustStore.getSSLContext();
        Session session = mail.getMailSession();
        Properties properties = session.getProperties();
        properties.remove(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_CLASS);
        properties.put(EmailConstants.MAIL_SMTP_SSL_ENABLE, true);
        properties.put("mail.smtp.ssl.socketFactory", context.getSocketFactory());
    }

    return mail;
}

From source file:velo.tools.EmailSender.java

public void send() {//throws MessagingException {
    log.debug("Sending messages in queue, list now contains: '" + emails.size() + "' emails");

    int failures = 0;
    //List<String> errorMessages = new ArrayList<String>();
    StringBuffer errorMsg = new StringBuffer();

    for (Email currEmail : emails) {
        log.trace("Currently Sending email with subject '" + currEmail.getSubject() + "', please wait...");
        try {/*  w  w  w .  j  a  v  a 2  s  . co  m*/
            currEmail.send();
            //Transport.send(currMsg);
        } catch (EmailException ee) {
            failures++;
            //errorMessages.add(me.getMessage());
            errorMsg.append(ee.getMessage() + " | ");
        }

        if (failures > 0) {
            //throw new MessagingException("Failed to send '" + failures + "' messages out of '" + emails.size() + "', dumping failure messages: " + errorMsg);
            //TODO: Handle! (Jboss does not know what is MesagingException)
        }
        break;
    }

    if (errorMsg.length() > 0) {
        log.error("An error has occured while trying to send one or more emails: " + errorMsg.toString());
    }
}