Example usage for javax.mail Message setSubject

List of usage examples for javax.mail Message setSubject

Introduction

In this page you can find the example usage for javax.mail Message setSubject.

Prototype

public abstract void setSubject(String subject) throws MessagingException;

Source Link

Document

Set the subject of this message.

Usage

From source file:bioLockJ.module.agent.MailAgent.java

private Message getMimeMessage() throws Exception {
    final Message message = new MimeMessage(getSession());
    message.setFrom(new InternetAddress(emailFrom));
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getRecipients()));
    message.setSubject("BioLockJ " + Config.requireString(Config.PROJECT_NAME) + " " + status);
    message.setContent(getContent());/*from   ww w.ja  v  a 2 s .  c  o m*/
    return message;
}

From source file:contestWebsite.ContactUs.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query("user")
            .setFilter(new FilterPredicate("name", FilterOperator.EQUAL, req.getParameter("name")));
    List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(3));
    Entity feedback = new Entity("feedback");
    if (users.size() != 0) {
        feedback.setProperty("user-id", users.get(0).getProperty("user-id"));
    }/*from   www.  j  av  a 2 s  . c  o m*/

    String name = escapeHtml4(req.getParameter("name"));
    String school = escapeHtml4(req.getParameter("school"));
    String comment = escapeHtml4(req.getParameter("text"));
    String email = escapeHtml4(req.getParameter("email"));

    HttpSession sess = req.getSession(true);
    sess.setAttribute("name", name);
    sess.setAttribute("school", school);
    sess.setAttribute("email", email);
    sess.setAttribute("comment", comment);

    Entity contestInfo = Retrieve.contestInfo();
    if (!(Boolean) sess.getAttribute("nocaptcha")) {
        URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify");
        String charset = java.nio.charset.StandardCharsets.UTF_8.name();
        String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s",
                URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset),
                URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset),
                URLEncoder.encode(req.getRemoteAddr(), charset));

        final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return connection.getInputStream();
            }
        }, Charsets.UTF_8));

        try {
            JSONObject JSONResponse = new JSONObject(response);
            if (!JSONResponse.getBoolean("success")) {
                resp.sendRedirect("/contactUs?captchaError=1");
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendRedirect("/contactUs?captchaError=1");
            return;
        }
    }

    feedback.setProperty("name", name);
    feedback.setProperty("school", school);
    feedback.setProperty("email", email);
    feedback.setProperty("comment", new Text(comment));
    feedback.setProperty("resolved", false);

    Transaction txn = datastore.beginTransaction();
    try {
        datastore.put(feedback);
        txn.commit();

        Session session = Session.getDefaultInstance(new Properties(), null);
        String appEngineEmail = (String) contestInfo.getProperty("account");

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress((String) contestInfo.getProperty("email"), "Contest Administrator"));
            msg.setSubject("Question about tournament from " + name);
            msg.setReplyTo(new InternetAddress[] { new InternetAddress(req.getParameter("email"), name),
                    new InternetAddress(appEngineEmail, "Tournament Website Admin") });

            VelocityEngine ve = new VelocityEngine();
            ve.init();

            VelocityContext context = new VelocityContext();
            context.put("name", name);
            context.put("email", email);
            context.put("school", school);
            context.put("message", comment);

            StringWriter sw = new StringWriter();
            Velocity.evaluate(context, sw, "questionEmail",
                    ((Text) contestInfo.getProperty("questionEmail")).getValue());
            msg.setContent(sw.toString(), "text/html");
            Transport.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }

        resp.sendRedirect("/contactUs?updated=1");
        sess.invalidate();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}

From source file:com.bia.monitor.service.EmailService.java

/**
 *
 * @param addressTo//  w w  w  . j av  a  2 s.  c o m
 * @param subject
 * @param message
 * @throws AddressException
 * @throws MessagingException
 */
private void send(InternetAddress[] addressTo, String subject, String message)
        throws AddressException, MessagingException {
    logger.info("sending email.. " + addressTo);
    Message msg = new MimeMessage(createSession());
    InternetAddress addressFrom = new InternetAddress(USERNAME);
    msg.setFrom(addressFrom);
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // set bcc
    InternetAddress[] bcc1 = getBCC();
    msg.setRecipients(Message.RecipientType.BCC, bcc1);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    //String message = comment;
    msg.setContent(message, EMAIL_CONTENT_TYPE);

    Transport.send(msg);
}

From source file:br.com.cgcop.administrativo.modelo.ContaEmail.java

public void enviarEmailHtml(List<String> destinos, String msg, String titulo) {
    //       Recipient's email ID needs to be mentioned.
    String to = "";
    String rodape = "<br/><br/><br/><br/>  <div style=\"border-top: 1px dashed #c8cdbe;border-top: 1px dashed #c8cdbe \">"
            + "Esta mensagem  uma notificao enviada automaticamente por tanto no deve ser respondida. <br/> "
            + "<span style=\"font-style: italic; font-family: Narrow; font-size: large; color: rgb(0, 153, 0);\">Sistema de Gesto de Projetos e Obras - SGPO</span><br/>"
            + "<span style=\"font-size: large; font-style: italic; color: rgb(0, 153, 0); font-family: Narrow;\">Oiti Engenharia e Gesto Ambiental</span>"
            + "</div>";
    for (String d : destinos) {
        if (d.equals(destinos.get(destinos.size() - 1))) {
            to = to.concat(d);/*from   w  w  w  .  ja  v a2 s  . c o  m*/
        } else {
            to = to.concat(d.concat(","));
        }
    }

    // Sender's email ID needs to be mentioned
    String from = this.email;
    final String username = this.email;//change accordingly
    final String password = this.senha;//change accordingly

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", this.host);
    props.put("mail.smtp.port", "25");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {

        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject(titulo);

        // Send the actual HTML message, as big as you like
        message.setContent(msg + rodape, "text/html");

        // Send message
        Transport.send(message);

    } catch (MessagingException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.skalli.core.mail.MailComponent.java

private void sendMailInternal(Address[] rcptTo, Address[] rcptCC, Address[] rcptBCC, Address from,
        String subject, String body) {
    try {//w ww .  j a  v  a 2 s.c om
        String mailHost = "mail.sap.corp"; //$NON-NLS-1$
        Properties props = System.getProperties();
        props.put("mail.smtp.host", mailHost); //$NON-NLS-1$
        Session session = Session.getInstance(props, null);
        Message message = new MimeMessage(session);
        message.setFrom(from);
        if (rcptTo != null && rcptTo.length > 0) {
            message.setRecipients(Message.RecipientType.TO, rcptTo);
        }
        if (rcptCC != null && rcptCC.length > 0) {
            message.setRecipients(Message.RecipientType.CC, rcptCC);
        }
        if (rcptBCC != null && rcptBCC.length > 0) {
            message.setRecipients(Message.RecipientType.BCC, rcptBCC);
        }

        message.setSubject(subject);
        message.setContent(body, "text/plain"); //$NON-NLS-1$
        Transport.send(message);
    } catch (AddressException e) {
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.bia.gmailjava.EmailService.java

/**
 *
 * @param addressTo//from  ww  w  .  j  ava 2 s.c  o m
 * @param subject
 * @param message
 * @throws AddressException
 * @throws MessagingException
 */
private void send(InternetAddress[] addressTo, String subject, String message)
        throws AddressException, MessagingException {
    Message msg = new MimeMessage(createSession());
    InternetAddress addressFrom = new InternetAddress(USERNAME);
    msg.setFrom(addressFrom);
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // set bcc
    //InternetAddress[] bcc1 = getBCC();
    //msg.setRecipients(Message.RecipientType.BCC, bcc1);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    //String message = comment;
    msg.setContent(message, EMAIL_CONTENT_TYPE);

    Transport.send(msg);
}

From source file:it.infn.ct.security.actions.PassRecovery.java

private void sendMail(String code) throws MailException {
    javax.mail.Session session = null;/*from  w ww.  j  a v a  2 s  . c  o  m*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        String title = user.getTitle() == null ? "" : user.getTitle();

        mailMsg.setFrom(new InternetAddress(mailFrom));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(user.getPreferredMail(),
                title + user.getGivenname() + " " + user.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", title + " " + user.getGivenname() + " " + user.getSurname());
        mailBody = mailBody.replaceAll("_CODE_", code);

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail from address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:esg.node.components.notification.ESGNotifier.java

private boolean sendNotification(String userid, String userAddress, String messageText) {
    Message msg = null;
    boolean success = false;
    String myAddress = null;//from  w  w w  . ja v  a 2  s . c o m

    try {
        msg = new MimeMessage(session);
        msg.setHeader("X-Mailer", "ESG DataNode IshMailer");
        msg.setSentDate(new Date());
        myAddress = props.getProperty("mail.admin.address", "esg-admin@llnl.gov");
        msg.setFrom(new InternetAddress(myAddress));
        msg.setSubject(subject + "ESG File Update Notification");

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userAddress));
        //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(userAddress));

        msg.setText(messageText);

        Transport.send(msg);
        success = true;
    } catch (MessagingException ex) {
        log.error("Problem Sending Email Notification: to " + userid + ": " + userAddress + " (" + subject
                + ")\n" + messageText + "\n", ex);
    }

    msg = null; //gc niceness

    return success;
}

From source file:com.spartasystems.holdmail.util.TestMailClient.java

public void sendResourceEmail(String resourceName, String sender, String recipient, String subject) {

    try {/*ww w  .j a  va 2s  . co m*/

        InputStream resource = TestMailClient.class.getClassLoader().getResourceAsStream(resourceName);
        if (resource == null) {
            throw new MessagingException("Couldn't find resource at: " + resourceName);
        }

        Message message = new MimeMessage(session, resource);

        // wipe out ALL exisitng recipients
        message.setRecipients(Message.RecipientType.TO, new Address[] {});
        message.setRecipients(Message.RecipientType.CC, new Address[] {});
        message.setRecipients(Message.RecipientType.BCC, new Address[] {});

        // then set the new data
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
        message.setFrom(InternetAddress.parse(sender)[0]);
        message.setSubject(subject);

        Transport.send(message);

        logger.info("Outgoing mail forwarded to " + recipient);

    } catch (MessagingException e) {
        throw new HoldMailException("couldn't send mail: " + e.getMessage(), e);
    }

}

From source file:com.waveerp.sendMail.java

public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc, String strPath) throws Exception {

    String strResult = "OK";

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.port", strPort);
    props.put("mail.user", strUser);
    props.put("mail.password", strPass01);

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }//from www  .ja v  a  2  s.c  om
    };
    Session session = Session.getInstance(props, auth);

    // creates a new e-mail message
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(strSource));
    //InternetAddress[] toAddresses = { new InternetAddress(strDestination) };
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination));
    msg.setSubject(strSubject);
    msg.setSentDate(new Date());

    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(strMsg, "text/html");

    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // adds attachments
    //if (attachFiles != null && attachFiles.length > 0) {
    //    for (String filePath : attachFiles) {
    //        MimeBodyPart attachPart = new MimeBodyPart();
    //
    //        try {
    //            attachPart.attachFile(filePath);
    //        } catch (IOException ex) {
    //            ex.printStackTrace();
    //        }
    //
    //        multipart.addBodyPart(attachPart);
    //    }
    //}

    String fna;
    String fnb;
    URL fileUrl;

    fileUrl = null;
    fileUrl = this.getClass().getResource("sendMail.class");
    fna = fileUrl.getPath();
    fna = fna.substring(0, fna.indexOf("WEB-INF"));
    //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath );
    fnb = URLDecoder.decode(fna + strPath);

    MimeBodyPart attachPart = new MimeBodyPart();
    try {

        attachPart.attachFile(fnb);

    } catch (IOException ex) {

        //ex.printStackTrace();
        strResult = ex.getMessage();

    }
    multipart.addBodyPart(attachPart);

    // sets the multi-part as e-mail's content
    msg.setContent(multipart);

    // sends the e-mail
    Transport.send(msg);

    return strResult;

}