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

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

Introduction

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

Prototype

public String getSubject() 

Source Link

Document

Gets the subject of the email.

Usage

From source file:io.marto.aem.utils.email.FreemarkerTemplatedMailerTest.java

@Test
public void testGatewayFormatsAndSendsMessage() throws EmailException, IOException, MessagingException {
    Map<String, Object> model = createModel();

    String recipients[] = new String[] { "joe@me.com", "jack@test.com" };
    String subject = "Test Email";
    String sender = "admin@marto.io";
    String template = "/templates/helloworld.ftl";

    mailer.sendEmail(recipients, sender, subject, template, model);
    mailer.clear();/* ww w .ja v  a2 s  .c  o  m*/

    HtmlEmail htmlMail = sentEmail.get();

    assertEquals(subject, htmlMail.getSubject());
    assertEquals(sender, htmlMail.getFromAddress().getAddress());
    assertEquals(recipients.length, htmlMail.getToAddresses().size());
    assertEquals(recipients[0], ((InternetAddress) htmlMail.getToAddresses().get(0)).getAddress());
    assertEquals(recipients[1], ((InternetAddress) htmlMail.getToAddresses().get(1)).getAddress());

    String msg = getEmail(htmlMail);

    assertThat(msg, containsString("FreeMarker Template example: Hello World!"));
    assertThat(msg, containsString("1. India"));
    assertThat(msg, containsString("2. United States"));
    assertThat(msg, containsString("3. Germany"));
    assertThat(msg, containsString("4. France"));

    assertThat(msg, containsString("To: \"joe@me.com\" <joe@me.com>, \"jack@test.com\" <jack@test.com>"));
    assertThat(msg, containsString("From: \"admin@marto.io\" <admin@marto.io>"));
    assertThat(msg, containsString("Subject: Test Email"));
}

From source file:com.github.robozonky.notifications.EmailHandler.java

@Override
public void send(final SessionInfo sessionInfo, final String subject, final String message,
        final String fallbackMessage) throws Exception {
    final HtmlEmail email = createNewEmail(sessionInfo);
    email.setSubject(subject);/*  w ww.  ja  v  a2  s . c om*/
    email.setHtmlMsg(message);
    email.setTextMsg(fallbackMessage);
    LOGGER.debug("Will send '{}' from {} to {} through {}:{} as {}.", email.getSubject(),
            email.getFromAddress(), email.getToAddresses(), email.getHostName(), email.getSmtpPort(),
            getSmtpUsername());
    email.send();
}

From source file:mailbox.EmailHandler.java

private static void reply(IMAPMessage origin, String username, String emailAddress, String msg) {
    final HtmlEmail email = new HtmlEmail();

    try {/*from   w  ww  .  j  a  v a  2s.c o m*/
        email.setFrom(Config.getEmailFromSmtp(), Config.getSiteName());
        email.addTo(emailAddress, username);
        String subject;
        if (!origin.getSubject().toLowerCase().startsWith("re:")) {
            subject = "Re: " + origin.getSubject();
        } else {
            subject = origin.getSubject();
        }
        email.setSubject(subject);
        email.setTextMsg(msg);
        email.setCharset("utf-8");
        email.setSentDate(new Date());
        email.addHeader("In-Reply-To", origin.getMessageID());
        email.addHeader("References", origin.getMessageID());
        Mailer.send(email);
        String escapedTitle = email.getSubject().replace("\"", "\\\"");
        String logEntry = String.format("\"%s\" %s", escapedTitle, email.getToAddresses());
        play.Logger.of("mail").info(logEntry);
    } catch (Exception e) {
        Logger.warn("Failed to send an email: " + email + "\n" + ExceptionUtils.getStackTrace(e));
    }
}

From source file:actors.ValidationEmailSender.java

@Override
public void onReceive(Object object) {
    if (!(object instanceof Email)) {
        return;/*from  w w  w .  ja  v a2s . c  o  m*/
    }

    Email email = (Email) object;

    final HtmlEmail htmlEmail = new HtmlEmail();

    try {
        htmlEmail.setFrom(Config.getEmailFromSmtp(), utils.Config.getSiteName());
        htmlEmail.addTo(email.email, email.user.name);
        htmlEmail.setSubject(Messages.get("emails.validation.email.title", utils.Config.getSiteName()));
        htmlEmail.setHtmlMsg(getMessage(email.confirmUrl));
        htmlEmail.setCharset("utf-8");
        Mailer.send(htmlEmail);
        String escapedTitle = htmlEmail.getSubject().replace("\"", "\\\"");
        String logEntry = String.format("\"%s\" %s", escapedTitle, htmlEmail.getToAddresses());
        play.Logger.of("mail").info(logEntry);
    } catch (Exception e) {
        Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e));
    }
}

From source file:controllers.ProjectApp.java

private static void sendTransferRequestMail(ProjectTransfer pt) {
    HtmlEmail email = new HtmlEmail();
    try {/*w ww .  j  a v  a2 s . co m*/
        String acceptUrl = pt.getAcceptUrl();
        String message = Messages.get("transfer.message.hello", pt.destination) + "\n\n"
                + Messages.get("transfer.message.detail", pt.project.name, pt.newProjectName, pt.project.owner,
                        pt.destination)
                + "\n" + Messages.get("transfer.message.link") + "\n\n" + acceptUrl + "\n\n"
                + Messages.get("transfer.message.deadline") + "\n\n" + Messages.get("transfer.message.thank");

        email.setFrom(Config.getEmailFromSmtp(), pt.sender.name);
        email.addTo(Config.getEmailFromSmtp(), "Yobi");

        User to = User.findByLoginId(pt.destination);
        if (!to.isAnonymous()) {
            email.addBcc(to.email, to.name);
        }

        Organization org = Organization.findByName(pt.destination);
        if (org != null) {
            List<OrganizationUser> admins = OrganizationUser.findAdminsOf(org);
            for (OrganizationUser admin : admins) {
                email.addBcc(admin.user.email, admin.user.name);
            }
        }

        email.setSubject(
                String.format("[%s] @%s wants to transfer project", pt.project.name, pt.sender.loginId));
        email.setHtmlMsg(Markdown.render(message));
        email.setTextMsg(message);
        email.setCharset("utf-8");
        email.addHeader("References", "<" + acceptUrl + "@" + Config.getHostname() + ">");
        email.setSentDate(pt.requested);
        Mailer.send(email);
        String escapedTitle = email.getSubject().replace("\"", "\\\"");
        String logEntry = String.format("\"%s\" %s", escapedTitle, email.getBccAddresses());
        play.Logger.of("mail").info(logEntry);
    } catch (Exception e) {
        Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e));
    }
}

From source file:de.hybris.platform.lichextendtrail.emailservice.DefaultLichEmailService.java

@Override
public boolean send(EmailMessageModel message) {
    if (message == null) {
        throw new IllegalArgumentException("message must not be null");
    }/*from   w  ww.  j av a2 s  .c om*/

    final boolean sendEnabled = getConfigurationService().getConfiguration()
            .getBoolean(EMAILSERVICE_SEND_ENABLED_CONFIG_KEY, true);
    if (sendEnabled) {
        try {
            final HtmlEmail email = getPerConfiguredEmail();
            email.setCharset("UTF-8");

            final List<EmailAddressModel> toAddresses = message.getToAddresses();
            setAddresses(message, email, toAddresses);

            final EmailAddressModel fromAddress = message.getFromAddress();
            email.setFrom(fromAddress.getEmailAddress(), nullifyEmpty(fromAddress.getDisplayName()));
            addReplyTo(message, email);
            email.setSubject(message.getSubject());
            //???
            if (message.getSubject().equals("?Customer Registration\n")) {
                email.setSubject("?");
                //??
                String emailToAddress = email.getToAddresses().get(0).toString();
                emailToAddress = emailToAddress.substring(emailToAddress.indexOf('<') + 1,
                        emailToAddress.indexOf('>'));
                //
                email.setHtmlMsg(LichValue.getEmailContent(emailToAddress));
            }
            //??? 
            else {
                email.setHtmlMsg(getBody(message));
            }
            // To support plain text parts use email.setTextMsg()

            final List<EmailAttachmentModel> attachments = message.getAttachments();
            if (!processAttachmentsSuccessful(email, attachments)) {
                return false;
            }

            // Important to log all emails sent out
            LOG.info("Sending Email [" + message.getPk() + "] To [" + convertToStrings(toAddresses) + "] From ["
                    + fromAddress.getEmailAddress() + "] Subject [" + email.getSubject() + "]");

            // Send the email and capture the message ID
            final String messageID = email.send();

            message.setSent(true);
            message.setSentMessageID(messageID);
            message.setSentDate(new Date());
            getModelService().save(message);

            return true;
        } catch (final EmailException e) {
            logInfo(message, e);
        }
    } else {
        LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "]");
        LOG.info("Email sending has been disabled. Check the config property 'emailservice.send.enabled'");
        return true;
    }

    return false;
}

From source file:de.hybris.platform.acceleratorservices.email.impl.DefaultEmailService.java

@Override
public boolean send(final EmailMessageModel message) {
    if (message == null) {
        throw new IllegalArgumentException("message must not be null");
    }/*  w  w  w . j  a  v a 2 s . co  m*/

    final boolean sendEnabled = getConfigurationService().getConfiguration()
            .getBoolean(EMAILSERVICE_SEND_ENABLED_CONFIG_KEY, true);
    if (sendEnabled) {
        try {
            final HtmlEmail email = getPerConfiguredEmail();
            email.setCharset("UTF-8");

            final List<EmailAddressModel> toAddresses = message.getToAddresses();
            if (CollectionUtils.isNotEmpty(toAddresses)) {
                email.setTo(getAddresses(toAddresses));
            } else {
                throw new IllegalArgumentException("message has no To addresses");
            }

            final List<EmailAddressModel> ccAddresses = message.getCcAddresses();
            if (ccAddresses != null && !ccAddresses.isEmpty()) {
                email.setCc(getAddresses(ccAddresses));
            }

            final List<EmailAddressModel> bccAddresses = message.getBccAddresses();
            if (bccAddresses != null && !bccAddresses.isEmpty()) {
                email.setBcc(getAddresses(bccAddresses));
            }

            final EmailAddressModel fromAddress = message.getFromAddress();
            email.setFrom(fromAddress.getEmailAddress(), nullifyEmpty(fromAddress.getDisplayName()));

            // Add the reply to if specified
            final String replyToAddress = message.getReplyToAddress();
            if (replyToAddress != null && !replyToAddress.isEmpty()) {
                email.setReplyTo(Collections.singletonList(createInternetAddress(replyToAddress, null)));
            }

            email.setSubject(message.getSubject());
            email.setHtmlMsg(getBody(message));

            // To support plain text parts use email.setTextMsg()

            final List<EmailAttachmentModel> attachments = message.getAttachments();
            if (attachments != null && !attachments.isEmpty()) {
                for (final EmailAttachmentModel attachment : attachments) {
                    try {
                        final DataSource dataSource = new ByteArrayDataSource(
                                getMediaService().getDataFromMedia(attachment), attachment.getMime());
                        email.attach(dataSource, attachment.getRealFileName(), attachment.getAltText());
                    } catch (final EmailException ex) {
                        LOG.error("Failed to load attachment data into data source [" + attachment + "]", ex);
                        return false;
                    }
                }
            }

            // Important to log all emails sent out
            LOG.info("Sending Email [" + message.getPk() + "] To [" + convertToStrings(toAddresses) + "] From ["
                    + fromAddress.getEmailAddress() + "] Subject [" + email.getSubject() + "]");

            // Send the email and capture the message ID
            final String messageID = email.send();

            message.setSent(true);
            message.setSentMessageID(messageID);
            message.setSentDate(new Date());
            getModelService().save(message);

            return true;
        } catch (final EmailException e) {
            LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject()
                    + "] cause: " + e.getMessage());
            if (LOG.isDebugEnabled()) {
                LOG.debug(e);
            }
        }
    } else {
        LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "]");
        LOG.info("Email sending has been disabled. Check the config property 'emailservice.send.enabled'");
        return true;
    }

    return false;
}

From source file:com.baasbox.service.user.UserService.java

public static void sendResetPwdMail(String appCode, ODocument user) throws Exception {
    final String errorString = "Cannot send mail to reset the password: ";

    //check method input
    if (!user.getSchemaClass().getName().equalsIgnoreCase(UserDao.MODEL_NAME))
        throw new PasswordRecoveryException(errorString + " invalid user object");

    //initialization
    String siteUrl = Application.NETWORK_HTTP_URL.getValueAsString();
    int sitePort = Application.NETWORK_HTTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(siteUrl))
        throw new PasswordRecoveryException(errorString + " invalid site url (is empty)");

    String textEmail = PasswordRecovery.EMAIL_TEMPLATE_TEXT.getValueAsString();
    String htmlEmail = PasswordRecovery.EMAIL_TEMPLATE_HTML.getValueAsString();
    if (StringUtils.isEmpty(htmlEmail))
        htmlEmail = textEmail;/*from   w w  w . ja v  a 2s  . c o  m*/
    if (StringUtils.isEmpty(htmlEmail))
        throw new PasswordRecoveryException(errorString + " text to send is not configured");

    boolean useSSL = PasswordRecovery.NETWORK_SMTP_SSL.getValueAsBoolean();
    boolean useTLS = PasswordRecovery.NETWORK_SMTP_TLS.getValueAsBoolean();
    String smtpHost = PasswordRecovery.NETWORK_SMTP_HOST.getValueAsString();
    int smtpPort = PasswordRecovery.NETWORK_SMTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(smtpHost))
        throw new PasswordRecoveryException(errorString + " SMTP host is not configured");

    String username_smtp = null;
    String password_smtp = null;
    if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
        username_smtp = PasswordRecovery.NETWORK_SMTP_USER.getValueAsString();
        password_smtp = PasswordRecovery.NETWORK_SMTP_PASSWORD.getValueAsString();
        if (StringUtils.isEmpty(username_smtp))
            throw new PasswordRecoveryException(errorString + " SMTP username is not configured");
    }
    String emailFrom = PasswordRecovery.EMAIL_FROM.getValueAsString();
    String emailSubject = PasswordRecovery.EMAIL_SUBJECT.getValueAsString();
    if (StringUtils.isEmpty(emailFrom))
        throw new PasswordRecoveryException(errorString + " sender email is not configured");

    try {
        String userEmail = ((ODocument) user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER)).field("email")
                .toString();

        String username = (String) ((ODocument) user.field("user")).field("name");

        //Random
        String sRandom = appCode + "%%%%" + username + "%%%%" + UUID.randomUUID();
        String sBase64Random = new String(Base64.encodeBase64(sRandom.getBytes()));

        //Save on DB
        ResetPwdDao.getInstance().create(new Date(), sBase64Random, user);

        //Send mail
        HtmlEmail email = null;

        URL resetUrl = new URL(Application.NETWORK_HTTP_SSL.getValueAsBoolean() ? "https" : "http", siteUrl,
                sitePort, "/user/password/reset/" + sBase64Random);

        //HTML Email Text
        ST htmlMailTemplate = new ST(htmlEmail, '$', '$');
        htmlMailTemplate.add("link", resetUrl);
        htmlMailTemplate.add("user_name", username);
        htmlMailTemplate.add("token", sBase64Random);

        //Plain text Email Text
        ST textMailTemplate = new ST(textEmail, '$', '$');
        textMailTemplate.add("link", resetUrl);
        textMailTemplate.add("user_name", username);
        textMailTemplate.add("token", sBase64Random);

        email = new HtmlEmail();

        email.setHtmlMsg(htmlMailTemplate.render());
        email.setTextMsg(textMailTemplate.render());

        //Email Configuration
        email.setSSL(useSSL);
        email.setSSLOnConnect(useSSL);
        email.setTLS(useTLS);
        email.setStartTLSEnabled(useTLS);
        email.setStartTLSRequired(useTLS);
        email.setSSLCheckServerIdentity(false);
        email.setSslSmtpPort(String.valueOf(smtpPort));
        email.setHostName(smtpHost);
        email.setSmtpPort(smtpPort);
        email.setCharset("utf-8");

        if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
            email.setAuthenticator(new DefaultAuthenticator(username_smtp, password_smtp));
        }
        email.setFrom(emailFrom);
        email.addTo(userEmail);

        email.setSubject(emailSubject);
        if (BaasBoxLogger.isDebugEnabled()) {
            StringBuilder logEmail = new StringBuilder().append("HostName: ").append(email.getHostName())
                    .append("\n").append("SmtpPort: ").append(email.getSmtpPort()).append("\n")
                    .append("SslSmtpPort: ").append(email.getSslSmtpPort()).append("\n")

                    .append("SSL: ").append(email.isSSL()).append("\n").append("TLS: ").append(email.isTLS())
                    .append("\n").append("SSLCheckServerIdentity: ").append(email.isSSLCheckServerIdentity())
                    .append("\n").append("SSLOnConnect: ").append(email.isSSLOnConnect()).append("\n")
                    .append("StartTLSEnabled: ").append(email.isStartTLSEnabled()).append("\n")
                    .append("StartTLSRequired: ").append(email.isStartTLSRequired()).append("\n")

                    .append("SubType: ").append(email.getSubType()).append("\n")
                    .append("SocketConnectionTimeout: ").append(email.getSocketConnectionTimeout()).append("\n")
                    .append("SocketTimeout: ").append(email.getSocketTimeout()).append("\n")

                    .append("FromAddress: ").append(email.getFromAddress()).append("\n").append("ReplyTo: ")
                    .append(email.getReplyToAddresses()).append("\n").append("BCC: ")
                    .append(email.getBccAddresses()).append("\n").append("CC: ").append(email.getCcAddresses())
                    .append("\n")

                    .append("Subject: ").append(email.getSubject()).append("\n")

                    //the following line throws a NPE in debug mode
                    //.append("Message: ").append(email.getMimeMessage().getContent()).append("\n")

                    .append("SentDate: ").append(email.getSentDate()).append("\n");
            BaasBoxLogger.debug("Password Recovery is ready to send: \n" + logEmail.toString());
        }
        email.send();

    } catch (EmailException authEx) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(authEx));
        throw new PasswordRecoveryException(
                errorString + " Could not reach the mail server. Please contact the server administrator");
    } catch (Exception e) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(e));
        throw new Exception(errorString, e);
    }

}

From source file:tilda.utils.MailUtil.java

/**
 * //from   w  w w  . ja  v  a  2  s . com
 * @param SmtpInfo A string such as smtp.mydomain.com:422:ssl to connect to an SMTP server
 * @param From the user ID used to send emails from
 * @param Password The password for the account we send emails from
 * @param To Destination email(s)
 * @param Cc CC email(s)
 * @param Bcc BCC emails(s)
 * @param Subject The Subject
 * @param Message The message (HTML allowed)
 * @param Urgent Whether to send the message as urgent or not.
 * @return
 */
public static boolean send(String SmtpInfo, String From, String Password, String[] To, String[] Cc,
        String[] Bcc, String Subject, String Message, boolean Urgent) {
    String LastAddress = null;
    try {
        HtmlEmail email = new HtmlEmail();

        String[] parts = SmtpInfo.split(":");
        email.setHostName(parts[0]);
        if (parts.length > 1) {
            if (parts.length > 2 && parts[2].equalsIgnoreCase("ssl") == true) {
                email.setSslSmtpPort(parts[1]);
                email.setSSLOnConnect(true);
            } else {
                email.setSmtpPort(Integer.parseInt(parts[1]));
            }
        }

        email.setAuthentication(From, Password);
        email.setSubject(Subject);

        LOG.debug("Sending an email '" + email.getSubject() + "'.");
        if (To != null)
            for (String s : To) {
                if (TextUtil.isNullOrEmpty(s) == true)
                    continue;
                LastAddress = s;
                email.addTo(s);
            }
        if (Cc != null)
            for (String s : Cc) {
                if (TextUtil.isNullOrEmpty(s) == true)
                    continue;
                LastAddress = s;
                email.addCc(s);
            }
        if (Bcc != null)
            for (String s : Bcc) {
                if (TextUtil.isNullOrEmpty(s) == true)
                    continue;
                LastAddress = s;
                email.addBcc(s);
            }
        if (LastAddress == null) {
            LOG.debug("No recipient. Not sending anything.");
            return true;
        }
        email.setFrom(From);
        LastAddress = From;
        email.setHtmlMsg(Message);
        if (Urgent == true)
            email.addHeader("X-Priority", "1");
        LastAddress = null;
        email.send();
        return true;
    } catch (EmailException E) {
        if (LastAddress != null)
            LOG.debug("Email address '" + LastAddress + "' seems to be invalid.");
        LOG.error(E);
        return false;
    }
}