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

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

Introduction

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

Prototype

public Email setSubject(final String aSubject) 

Source Link

Document

Set the email subject.

Usage

From source file:fr.gael.dhus.messaging.mail.MailServer.java

public void send(Email email, String to, String cc, String bcc, String subject) throws EmailException {
    email.setHostName(getSmtpServer());//ww  w .  j  a  v  a 2s  . c  o  m
    email.setSmtpPort(getPort());
    if (getUsername() != null) {
        email.setAuthentication(getUsername(), getPassword());
    }
    if (getFromMail() != null) {
        if (getFromName() != null)
            email.setFrom(getFromMail(), getFromName());
        else
            email.setFrom(getFromMail());
    }
    if (getReplyto() != null) {
        try {
            email.setReplyTo(ImmutableList.of(new InternetAddress(getReplyto())));
        } catch (AddressException e) {
            logger.error("Cannot configure Reply-to (" + getReplyto() + ") into the mail: " + e.getMessage());
        }
    }

    // Message configuration
    email.setSubject("[" + cfgManager.getNameConfiguration().getShortName() + "] " + subject);
    email.addTo(to);

    // Add CCed
    if (cc != null) {
        email.addCc(cc);
    }
    // Add BCCed
    if (bcc != null) {
        email.addBcc(bcc);
    }

    email.setStartTLSEnabled(isTls());
    try {
        email.send();
    } catch (EmailException e) {
        logger.error("Cannot send email: " + e.getMessage());
        throw e;
    }
}

From source file:com.neu.controller.MessageController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource");

    String action = request.getParameter("action");
    ModelAndView mv = new ModelAndView();

    HttpSession session = request.getSession();
    String userName = (String) session.getAttribute("userName");

    if (action.equalsIgnoreCase("reply")) {

        try {/*from   w w  w.j  a va 2 s  .c  om*/

            String receiver = request.getParameter("to");
            System.out.println("Printing receiver in reply case: " + receiver);

            QueryRunner run = new QueryRunner(ds);
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            UsersBean ub = run.query("select * from userstable where userName =?", user, receiver);
            if (ub != null) {
                System.out.println("printing userEmail received from DB: " + ub.getUserEmail());

                mv.addObject("toEmail", ub.getUserEmail());
                mv.addObject("to", receiver);
            }

            mv.setViewName("reply");

        } catch (SQLException e) {
            System.out.println(e);

        }

    } else if (action.equalsIgnoreCase("sent")) {
        System.out.println("In sent case");

        try {
            String receiver = request.getParameter("to");
            String receiverEmail = request.getParameter("toEmail");

            System.out.println("printing receiver email: " + receiverEmail);

            QueryRunner run = new QueryRunner(ds);
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            UsersBean ub = run.query("select * from userstable where userName =?", user, userName);
            if (ub != null) {
                String senderEmail = ub.getUserEmail();
                System.out.println("printing senderemail: " + senderEmail);

                ResultSetHandler<MessageBean> msg = new BeanHandler<MessageBean>(MessageBean.class);
                Object[] params = new Object[4];
                params[0] = userName;
                params[1] = request.getParameter("message");
                Date d = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                String messageDate = format.format(d);
                params[2] = messageDate;
                params[3] = receiver;
                int inserts = run.update(
                        "Insert into messages (fromUser,message,messageDate,userName) values(?,?,?,?)", params);//Logic to send the email

                try {
                    Email email = new SimpleEmail();
                    email.setHostName("smtp.googlemail.com");//If a server is capable of sending email, then you don't need the authentication. In this case, an email server needs to be running on that machine. Since we are running this application on the localhost and we don't have a email server, we are simply asking gmail to relay this email.
                    email.setSmtpPort(465);
                    email.setAuthenticator(
                            new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc"));
                    email.setSSLOnConnect(true);
                    email.setFrom(senderEmail);//This email will appear in the from field of the sending email. It doesn't have to be a real email address.This could be used for phishing/spoofing!
                    email.setSubject("Thanks for Signing Up!");
                    email.setMsg("Welcome to Web tools Lab 5 Spring Application sign up email test!");
                    email.addTo(receiverEmail);//Will come from the database
                    email.send();
                } catch (Exception e) {
                    System.out.println("Email Exception" + e.getMessage());
                    e.printStackTrace();
                }
                mv.setViewName("messageSent");
            } else {
                mv.addObject("error", "true");
                mv.setViewName("index");

            }

        } catch (Exception ex) {
            System.out.println("Error Message" + ex.getMessage());
            ex.printStackTrace();

        }

    }

    return mv;
}

From source file:com.neu.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource");

    String action = request.getParameter("action");
    ModelAndView mv = new ModelAndView();

    HttpSession session = request.getSession();

    if (action.equalsIgnoreCase("login")) {
        try {//from w w w.  ja  va2s.  co  m
            String userName = request.getParameter("user");
            String password = request.getParameter("password");
            QueryRunner run = new QueryRunner(ds);
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            Object[] params = new Object[2];
            params[0] = userName;
            params[1] = password;
            UsersBean ub = run.query("select * from userstable where userName =? and userPassword=?", user,
                    params);
            if (ub != null) {
                ResultSetHandler<List<MessageBean>> messages = new BeanListHandler<MessageBean>(
                        MessageBean.class);
                List<MessageBean> msg = run.query("select * from messages where userName =?", messages,
                        userName);
                session.setAttribute("userName", userName);
                session.setAttribute("messageList", msg);
                mv.setViewName("userhome");
            } else {
                mv.addObject("error", "true");
                mv.setViewName("index");

            }

        } catch (Exception ex) {
            System.out.println("Error Message" + ex.getMessage());

        }

    } else if (action.equalsIgnoreCase("logout")) {

        session.invalidate();
        mv.setViewName("index");
    } else if (action.equalsIgnoreCase("signup")) {

        System.out.println("sign up");
        //                
        //                String userName = request.getParameter("user");
        //                String password = request.getParameter("password");
        //                String emailObj = request.getParameter("emailObj");
        //                
        // System.out.println("printing details: " + userName + " " +password + " "+emailObj);
        mv.setViewName("signup");
    } else if (action.equalsIgnoreCase("signupsubmit")) {

        System.out.println("sign up submit");

        String userName = request.getParameter("user");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        System.out.println("printing details: " + userName + " " + password + " " + email);

        if (userName.equals("") || (password.equals("")) || (email.equals(""))) {
            System.out.println("empty values");
            mv.addObject("error", "true");
        }

        else {
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            Object[] params = new Object[3];
            params[0] = userName;
            params[1] = password;
            params[2] = email;
            QueryRunner run = new QueryRunner(ds);
            int inserts = run.update("insert into userstable (UserName,UserPassword,UserEmail) values (?,?,?)",
                    params);//Logic to insert into table
            System.out.println("inserts value " + inserts);

            if (inserts > 0) {
                mv.addObject("success", "true");
                Email emailObj = new SimpleEmail();
                emailObj.setHostName("smtp.googlemail.com");//If a server is capable of sending emailObj, then you don't need the authentication. In this case, an emailObj server needs to be running on that machine. Since we are running this application on the localhost and we don't have a emailObj server, we are simply asking gmail to relay this emailObj.
                emailObj.setSmtpPort(465);
                emailObj.setAuthenticator(
                        new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc"));
                emailObj.setSSLOnConnect(true);
                emailObj.setFrom("webtools@hello.com");//This emailObj will appear in the from field of the sending emailObj. It doesn't have to be a real emailObj address.This could be used for phishing/spoofing!
                emailObj.setSubject("TestMail");
                emailObj.setMsg("This is spring MVC Contact Application sending you the email");
                emailObj.addTo(email);//Will come from the sign up details
                emailObj.send();
            }

        }

        mv.setViewName("signup");
    }

    return mv;
}

From source file:com.gst.infrastructure.core.service.GmailBackedPlatformEmailService.java

@Override
public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) {
    final Email email = new SimpleEmail();
    final SMTPCredentialsData smtpCredentialsData = this.externalServicesReadPlatformService
            .getSMTPCredentials();/*from   w w  w.  java 2s. co  m*/
    final String authuserName = smtpCredentialsData.getUsername();

    final String authuser = smtpCredentialsData.getUsername();
    final String authpwd = smtpCredentialsData.getPassword();

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(false); // true if you want to debug
    email.setHostName(smtpCredentialsData.getHost());
    try {
        if (smtpCredentialsData.isUseTLS()) {
            email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        }
        email.setFrom(authuser, authuserName);

        final StringBuilder subjectBuilder = new StringBuilder().append("Welcome ")
                .append(emailDetail.getContactName()).append(" to ").append(emailDetail.getOrganisationName());

        email.setSubject(subjectBuilder.toString());

        final String sendToEmail = emailDetail.getAddress();

        final StringBuilder messageBuilder = new StringBuilder()
                .append("You are receiving this email as your email account: ").append(sendToEmail)
                .append(" has being used to create a user account for an organisation named [")
                .append(emailDetail.getOrganisationName()).append("] on Mifos.\n")
                .append("You can login using the following credentials:\nusername: ")
                .append(emailDetail.getUsername()).append("\n").append("password: ").append(unencodedPassword)
                .append("\n")
                .append("You must change this password upon first log in using Uppercase, Lowercase, number and character.\n")
                .append("Thank you and welcome to the organisation.");

        email.setMsg(messageBuilder.toString());

        email.addTo(sendToEmail, emailDetail.getContactName());
        email.send();
    } catch (final EmailException e) {
        throw new PlatformEmailSendException(e);
    }
}

From source file:com.adobe.acs.commons.email.impl.EmailServiceImpl.java

private Email getEmail(final MailTemplate mailTemplate, final Class<? extends Email> mailType,
        final Map<String, String> params) throws EmailException, MessagingException, IOException {

    final Email email = mailTemplate.getEmail(StrLookup.mapLookup(params), mailType);

    if (params.containsKey(EmailServiceConstants.SENDER_EMAIL_ADDRESS)
            && params.containsKey(EmailServiceConstants.SENDER_NAME)) {

        email.setFrom(params.get(EmailServiceConstants.SENDER_EMAIL_ADDRESS),
                params.get(EmailServiceConstants.SENDER_NAME));

    } else if (params.containsKey(EmailServiceConstants.SENDER_EMAIL_ADDRESS)) {
        email.setFrom(params.get(EmailServiceConstants.SENDER_EMAIL_ADDRESS));
    }/*from   w ww  .  ja  v  a 2s .  com*/
    if (connectTimeout > 0) {
        email.setSocketConnectionTimeout(connectTimeout);
    }
    if (soTimeout > 0) {
        email.setSocketTimeout(soTimeout);
    }

    // #1008 setting the subject via the setSubject(..) parameter.
    if (params.containsKey(EmailServiceConstants.SUBJECT)) {
        email.setSubject(params.get(EmailServiceConstants.SUBJECT));
    }

    return email;
}

From source file:adams.core.net.SimpleApacheSendEmail.java

/**
 * Sends an email./*ww  w  . j  av a2s.  c om*/
 *
 * @param email   the email to send
 * @return      true if successfully sent
 * @throws Exception   in case of invalid internet addresses or messaging problem
 */
@Override
public boolean sendMail(Email email) throws Exception {
    org.apache.commons.mail.Email mail;
    String id;
    MultiPartEmail mpemail;
    EmailAttachment attachment;

    if (email.getAttachments().length > 0) {
        mail = new MultiPartEmail();
        mpemail = (MultiPartEmail) mail;
        for (File file : email.getAttachments()) {
            attachment = new EmailAttachment();
            attachment.setPath(file.getAbsolutePath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setName(file.getName());
            mpemail.attach(attachment);
        }
    } else {
        mail = new SimpleEmail();
    }
    mail.setFrom(email.getFrom().getValue());
    for (EmailAddress address : email.getTo())
        mail.addTo(address.getValue());
    for (EmailAddress address : email.getCC())
        mail.addCc(address.getValue());
    for (EmailAddress address : email.getBCC())
        mail.addBcc(address.getValue());
    mail.setSubject(email.getSubject());
    mail.setMsg(email.getBody());
    mail.setHostName(m_Server);
    mail.setSmtpPort(m_Port);
    mail.setStartTLSEnabled(m_UseTLS);
    mail.setSSLOnConnect(m_UseSSL);
    if (m_RequiresAuth)
        mail.setAuthentication(m_User, m_Password.getValue());
    mail.setSocketTimeout(m_Timeout);
    try {
        id = mail.send();
        if (isLoggingEnabled())
            getLogger().info("Message sent: " + id);
    } catch (Exception e) {
        getLogger().log(Level.SEVERE, "Failed to send email: " + mail, e);
        return false;
    }

    return true;
}

From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java

/**
 * Send the actual email./*from  www . j a  v a  2  s .  com*/
 * 
 * @param oid
 * @param from
 * @param recipient
 * @param subject
 * @param body
 * @return
 */
public boolean email(String oid, String from, String recipient, String subject, String body) {
    try {
        Email email = new SimpleEmail();
        log.debug("Email host: " + host);
        log.debug("Email port: " + port);
        log.debug("Email username: " + username);
        log.debug("Email from: " + from);
        log.debug("Email to: " + recipient);
        log.debug("Email Subject is: " + subject);
        log.debug("Email Body is: " + body);
        email.setHostName(host);
        email.setSmtpPort(Integer.parseInt(port));
        email.setAuthenticator(new DefaultAuthenticator(username, password));
        // the method setSSL is deprecated on the newer versions of commons
        // email...
        email.setSSL("true".equalsIgnoreCase(ssl));
        email.setTLS("true".equalsIgnoreCase(tls));
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(body);
        if (recipient.indexOf(",") >= 0) {
            String[] recs = recipient.split(",");
            for (String rec : recs) {
                email.addTo(rec);
            }
        } else {
            email.addTo(recipient);
        }
        email.send();
    } catch (Exception ex) {
        log.debug("Error sending notification mail for oid:" + oid, ex);
        return false;
    }
    return true;
}

From source file:com.pkrete.locationservice.admin.mailer.impl.BasicEmailService.java

/**
 * Send an email to the given user when the user is created or the password
 * is modified.//from   www.j av a2s  . c  o  m
 *
 * @param user the receiver of the email
 */
@Override
public void send(UserFull user) {
    logger.info("Create new email message.");
    Email email = new SimpleEmail();
    email.setHostName(PropertiesUtil.getProperty("mail.host"));
    email.setSmtpPort(this.converterService.strToInt(PropertiesUtil.getProperty("mail.port")));
    email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getProperty("mail.user"),
            PropertiesUtil.getProperty("mail.password")));
    email.setTLS(true);
    try {
        // Init variables
        String header = null;
        String msg = null;

        // Set from address
        email.setFrom(this.messageSource.getMessage("mail.from", null, null));

        // Set message arguments
        Object[] args = new Object[] { user.getUsername(), user.getPasswordUi() };

        // Set variables values
        if (user.getUpdated() == null) {
            // This is a new user
            if (logger.isDebugEnabled()) {
                logger.debug("The message is for a new user.");
            }
            // Set subject
            email.setSubject(this.messageSource.getMessage("mail.title.add", null, null));
            // Set message header
            header = this.messageSource.getMessage("mail.header.add", null, null);
            // Set message content
            msg = this.messageSource.getMessage("mail.message.add", args, null);
        } else {
            // This is an existing user
            logger.debug("The message is for an existing user.");
            // Set subject
            email.setSubject(this.messageSource.getMessage("mail.title.edit", null, null));
            // Get message header
            header = this.messageSource.getMessage("mail.header.edit", null, null);
            // Get message content
            msg = this.messageSource.getMessage("mail.message.edit", args, null);
        }

        // Get note
        String note = this.messageSource.getMessage("mail.note", null, null);
        // Get footer
        String footer = this.messageSource.getMessage("mail.footer", null, null);
        // Get signature
        String signature = this.messageSource.getMessage("mail.signature", null, null);

        // Build message body
        StringBuilder result = new StringBuilder();
        if (!header.isEmpty()) {
            result.append(header).append("\n\n");
        }
        if (!msg.isEmpty()) {
            result.append(msg).append("\n\n");
        }
        if (!note.isEmpty()) {
            result.append(note).append("\n\n");
        }
        if (!footer.isEmpty()) {
            result.append(footer).append("\n\n");
        }
        if (!signature.isEmpty()) {
            result.append(signature).append("\n\n");
        }
        // Set message contents
        email.setMsg(result.toString());
        // Set message receiver
        email.addTo(user.getEmail());
        // Send message
        email.send();
        logger.info("Email was sent to \"{}\".", user.getEmail());
    } catch (Exception e) {
        logger.error("Failed to send email to \"{}\".", user.getEmail());
        logger.error(e.getMessage(), e);
    }
}

From source file:com.cws.esolutions.security.quartz.PasswordExpirationNotifier.java

/**
 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
 *///from  w ww .  ja  v a 2 s  .  co m
public void execute(final JobExecutionContext context) {
    final String methodName = PasswordExpirationNotifier.CNAME
            + "#execute(final JobExecutionContext jobContext)";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("JobExecutionContext: {}", context);
    }

    final Map<String, Object> jobData = context.getJobDetail().getJobDataMap();

    if (DEBUG) {
        DEBUGGER.debug("jobData: {}", jobData);
    }

    try {
        UserManager manager = UserManagerFactory
                .getUserManager(bean.getConfigData().getSecurityConfig().getUserManager());

        if (DEBUG) {
            DEBUGGER.debug("UserManager: {}", manager);
        }

        List<String[]> accounts = manager.listUserAccounts();

        if (DEBUG) {
            DEBUGGER.debug("accounts: {}", accounts);
        }

        if ((accounts == null) || (accounts.size() == 0)) {
            return;
        }

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 30);
        Long expiryTime = cal.getTimeInMillis();

        if (DEBUG) {
            DEBUGGER.debug("Calendar: {}", cal);
            DEBUGGER.debug("expiryTime: {}", expiryTime);
        }

        for (String[] account : accounts) {
            if (DEBUG) {
                DEBUGGER.debug("Account: {}", (Object) account);
            }

            List<Object> accountDetail = manager.loadUserAccount(account[0]);

            if (DEBUG) {
                DEBUGGER.debug("List<Object>: {}", accountDetail);
            }

            try {
                Email email = new SimpleEmail();
                email.setHostName((String) jobData.get("mailHost"));
                email.setSmtpPort(Integer.parseInt((String) jobData.get("portNumber")));

                if ((Boolean) jobData.get("isSecure")) {
                    email.setSSLOnConnect(true);
                }

                if ((Boolean) jobData.get("isAuthenticated")) {
                    email.setAuthenticator(new DefaultAuthenticator((String) jobData.get("username"),
                            PasswordUtils.decryptText((String) (String) jobData.get("password"),
                                    (String) jobData.get("salt"), secConfig.getSecretAlgorithm(),
                                    secConfig.getIterations(), secConfig.getKeyBits(),
                                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                                    systemConfig.getEncoding())));
                }

                email.setFrom((String) jobData.get("emailAddr"));
                email.addTo((String) accountDetail.get(6));
                email.setSubject((String) jobData.get("messageSubject"));
                email.setMsg(String.format((String) jobData.get("messageBody"), (String) accountDetail.get(4)));

                if (DEBUG) {
                    DEBUGGER.debug("SimpleEmail: {}", email);
                }

                email.send();
            } catch (EmailException ex) {
                ERROR_RECORDER.error(ex.getMessage(), ex);
            } catch (SecurityException sx) {
                ERROR_RECORDER.error(sx.getMessage(), sx);
            }
        }
    } catch (UserManagementException umx) {
        ERROR_RECORDER.error(umx.getMessage(), umx);
    }
}

From source file:net.scran24.user.server.services.HelpServiceImpl.java

@Override
public void reportUncaughtException(String strongName, List<String> classNames, List<String> messages,
        List<StackTraceElement[]> stackTraces, String surveyState) {
    Subject subject = SecurityUtils.getSubject();
    ScranUserId userId = (ScranUserId) subject.getPrincipal();

    if (userId == null)
        throw new RuntimeException("User must be logged in");

    String rateKey = userId.survey + "#" + userId.username;
    RateInfo rateInfo = rateMap.get(rateKey);

    boolean rateExceeded = false;

    long time = System.currentTimeMillis();

    if (rateInfo == null) {
        rateMap.put(rateKey, new RateInfo(1, time));
    } else {//from w w  w. ja v a2s. c om
        long timeSinceLastRequest = time - rateInfo.lastRequestTime;

        if (timeSinceLastRequest > 10000) {
            rateMap.put(rateKey, new RateInfo(1, time));
        } else if (rateInfo.requestCount >= 10) {
            rateExceeded = true;
        } else {
            rateMap.put(rateKey, new RateInfo(rateInfo.requestCount + 1, time));
        }
    }

    if (!rateExceeded) {
        System.out.println(String.format("Sending email", userId.survey, userId.username));

        Email email = new SimpleEmail();

        email.setHostName(smtpHostName);
        email.setSmtpPort(smtpPort);
        email.setCharset(EmailConstants.UTF_8);
        email.setAuthenticator(new DefaultAuthenticator(smtpUserName, smtpPassword));
        email.setSSLOnConnect(true);

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < classNames.size(); i++) {
            sb.append(String.format("%s: %s\n", classNames.get(i), messages.get(i)));

            StackTraceElement[] deobfStackTrace = deobfuscator.resymbolize(stackTraces.get(i), strongName);

            for (StackTraceElement ste : deobfStackTrace) {
                sb.append(String.format("  %s\n", ste.toString()));
            }
            sb.append("\n");
        }

        sb.append("Survey state:\n");
        sb.append(surveyState);
        sb.append("\n");

        try {
            email.setFrom("no-reply@intake24.co.uk", "Intake24");
            email.setSubject(String.format("Client exception (%s/%s): %s", userId.survey, userId.username,
                    messages.get(0)));

            email.setMsg(sb.toString());

            email.addTo("bugs@intake24.co.uk");

            email.send();
        } catch (EmailException ee) {
            log.error("Failed to send e-mail notification", ee);
        }
    }

}