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:org.kite9.diagram.server.AbstractKite9Controller.java

public void sendErrorEmail(Throwable t, String xml, String url) {
    try {/*from   ww  w  .ja v  a  2  s .c  o m*/
        Properties props = new Properties();
        props.put("mail.smtp.host", "server.kite9.org");
        Session session = Session.getInstance(props);
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("servicetest@kite9.com"));
        msg.setRecipient(RecipientType.TO, new InternetAddress("rob@kite9.com"));
        String name = ctx.getServletContextName();
        boolean local = isLocal();
        msg.setSubject("Failure in " + (local ? "TEST" : name) + " Service: " + this.getClass().getName());
        StringWriter sw = new StringWriter(10000);
        PrintWriter pw = new PrintWriter(sw);
        pw.write("URL: " + url + "\n");

        t.printStackTrace(pw);

        if (xml != null) {
            pw.println();
            pw.print(xml);
        }

        pw.close();
        msg.setText(sw.toString());
        Transport.send(msg);
    } catch (Exception e) {
    } finally {
        t.printStackTrace();
    }
}

From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsReset.java

private Boolean doEmail(String csid, String emailparam, Request in, JSONObject userdetails)
        throws UIException, JSONException {

    String token = createToken(csid);
    EmailData ed = spec.getEmailData();/*from  w w  w  .ja  v a 2 s  . c  om*/
    String[] recipients = new String[1];

    /* ABSTRACT EMAIL STUFF : WHERE do we get the content of emails from? cspace-config.xml */
    String messagebase = ed.getPasswordResetMessage();
    String link = ed.getBaseURL() + ed.getLoginUrl() + "?token=" + token + "&email=" + emailparam;
    String message = messagebase.replaceAll("\\{\\{link\\}\\}", link);
    String greeting = userdetails.getJSONObject("fields").getString("screenName");
    message = message.replaceAll("\\{\\{greeting\\}\\}", greeting);
    message = message.replaceAll("\\\\n", "\\\n");
    message = message.replaceAll("\\\\r", "\\\r");

    String SMTP_HOST_NAME = ed.getSMTPHost();
    String SMTP_PORT = ed.getSMTPPort();
    String subject = ed.getPasswordResetSubject();
    String from = ed.getFromAddress();
    if (ed.getToAddress().isEmpty()) {
        recipients[0] = emailparam;
    } else {
        recipients[0] = ed.getToAddress();
    }
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    boolean debug = false;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", ed.doSMTPAuth());
    props.put("mail.debug", ed.doSMTPDebug());
    props.put("mail.smtp.port", SMTP_PORT);

    Session session = Session.getDefaultInstance(props);
    // XXX fix to allow authpassword /username

    session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom;
    try {
        addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setText(message);

        Transport.send(msg);
    } catch (AddressException e) {
        throw new UIException("AddressException: " + e.getMessage());
    } catch (MessagingException e) {
        throw new UIException("MessagingException: " + e.getMessage());
    }

    return true;
}

From source file:UserInfo_Frame.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port ", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("anhduc.nguyen77000@gmail.com", "Matmachung020587");
        }//from  ww  w .  j  ava2 s.  c  o m
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("anhduc.nguyen77000@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("oracle.submit@gmail.com"));
        message.setSubject("hi this is me");
        message.setText("hi how are you, i am fine");
        Transport.send(message);
        JOptionPane.showMessageDialog(null, "message sent");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

From source file:org.apache.nifi.processors.standard.PutEmail.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;//ww w  .j  a  va 2  s. c  om
    }

    final Properties properties = this.getMailPropertiesFromFlowFile(context, flowFile);

    final Session mailSession = this.createMailSession(properties);

    final Message message = new MimeMessage(mailSession);
    final ComponentLog logger = getLogger();

    try {
        message.addFrom(toInetAddresses(context, flowFile, FROM));
        message.setRecipients(RecipientType.TO, toInetAddresses(context, flowFile, TO));
        message.setRecipients(RecipientType.CC, toInetAddresses(context, flowFile, CC));
        message.setRecipients(RecipientType.BCC, toInetAddresses(context, flowFile, BCC));

        message.setHeader("X-Mailer",
                context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions(flowFile).getValue());
        message.setSubject(context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue());
        String messageText = context.getProperty(MESSAGE).evaluateAttributeExpressions(flowFile).getValue();

        if (context.getProperty(INCLUDE_ALL_ATTRIBUTES).asBoolean()) {
            messageText = formatAttributes(flowFile, messageText);
        }

        String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions(flowFile)
                .getValue();
        message.setContent(messageText, contentType);
        message.setSentDate(new Date());

        if (context.getProperty(ATTACH_FILE).asBoolean()) {
            final MimeBodyPart mimeText = new PreencodedMimeBodyPart("base64");
            mimeText.setDataHandler(new DataHandler(new ByteArrayDataSource(
                    Base64.encodeBase64(messageText.getBytes("UTF-8")), contentType + "; charset=\"utf-8\"")));
            final MimeBodyPart mimeFile = new MimeBodyPart();
            session.read(flowFile, new InputStreamCallback() {
                @Override
                public void process(final InputStream stream) throws IOException {
                    try {
                        mimeFile.setDataHandler(
                                new DataHandler(new ByteArrayDataSource(stream, "application/octet-stream")));
                    } catch (final Exception e) {
                        throw new IOException(e);
                    }
                }
            });

            mimeFile.setFileName(flowFile.getAttribute(CoreAttributes.FILENAME.key()));
            MimeMultipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeText);
            multipart.addBodyPart(mimeFile);
            message.setContent(multipart);
        }

        send(message);

        session.getProvenanceReporter().send(flowFile, "mailto:" + message.getAllRecipients()[0].toString());
        session.transfer(flowFile, REL_SUCCESS);
        logger.info("Sent email as a result of receiving {}", new Object[] { flowFile });
    } catch (final ProcessException | MessagingException | IOException e) {
        context.yield();
        logger.error("Failed to send email for {}: {}; routing to failure",
                new Object[] { flowFile, e.getMessage() }, e);
        session.transfer(flowFile, REL_FAILURE);
    }
}

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

private void sendMail(UserRequest usreq) throws MailException {
    javax.mail.Session session = null;/*from   w w  w  .  j  a  v  a2  s . co 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 {
        mailMsg.setFrom(new InternetAddress(mailFrom, idPAdmin));

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

        String ccMail[] = mailCC.split(";");
        InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
        for (int i = 0; i < ccMail.length; i++) {
            mailCCopy[i] = new InternetAddress(ccMail[i]);
        }

        mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_",
                usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname());

        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:EmailBean.java

public void sendMessage() throws Exception {

    Properties properties = System.getProperties();

    //populate the 'Properties' object with the mail
    //server address, so that the default 'Session'
    //instance can use it.
    properties.put("mail.smtp.host", smtpHost);

    Session session = Session.getDefaultInstance(properties);

    Message mailMsg = new MimeMessage(session);//a new email message

    InternetAddress[] addresses = null;// w  ww  .j  a  v  a2  s . com

    try {

        if (to != null) {

            //throws 'AddressException' if the 'to' email address
            //violates RFC822 syntax
            addresses = InternetAddress.parse(to, false);

            mailMsg.setRecipients(Message.RecipientType.TO, addresses);

        } else {

            throw new MessagingException("The mail message requires a 'To' address.");

        }

        if (from != null) {

            mailMsg.setFrom(new InternetAddress(from));

        } else {

            throw new MessagingException("The mail message requires a valid 'From' address.");

        }

        if (subject != null)
            mailMsg.setSubject(subject);

        if (content != null)
            mailMsg.setText(content);

        //Finally, send the mail message; throws a 'SendFailedException'
        //if any of the message's recipients have an invalid address
        Transport.send(mailMsg);

    } catch (Exception exc) {

        throw exc;

    }

}

From source file:com.tremolosecurity.proxy.auth.PasswordReset.java

private void sendEmail(SmtpMessage msg) throws MessagingException {
    Properties props = new Properties();

    props.setProperty("mail.smtp.host", this.reset.getSmtpServer());
    props.setProperty("mail.smtp.port", Integer.toString(reset.getSmtpPort()));
    props.setProperty("mail.smtp.user", reset.getSmtpUser());
    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.starttls.enable", Boolean.toString(reset.isSmtpTLS()));
    //props.setProperty("mail.debug", "true");
    //props.setProperty("mail.socket.debug", "true");

    if (reset.getSmtpLocalhost() != null && !reset.getSmtpLocalhost().isEmpty()) {
        props.setProperty("mail.smtp.localhost", reset.getSmtpLocalhost());
    }//from w  w  w  .  j  av a  2  s .c o m

    if (reset.isUseSocks()) {

        props.setProperty("mail.smtp.socks.host", reset.getSocksHost());

        props.setProperty("mail.smtp.socks.port", Integer.toString(reset.getSocksPort()));
        props.setProperty("mail.smtps.socks.host", reset.getSocksHost());

        props.setProperty("mail.smtps.socks.port", Integer.toString(reset.getSocksPort()));
    }

    //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword));
    Session session = Session.getDefaultInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(reset.getSmtpUser(), reset.getSmtpPassword());
        }
    });
    //Session session = Session.getInstance(props, null);
    session.setDebugOut(System.out);
    //session.setDebug(true);
    //Transport tr = session.getTransport("smtp");
    //tr.connect();

    //tr.connect(this.smtpHost,this.smtpPort, this.smtpUser, this.smtpPassword);

    Message msgToSend = new MimeMessage(session);
    msgToSend.setFrom(new InternetAddress(msg.from));
    msgToSend.addRecipient(Message.RecipientType.TO, new InternetAddress(msg.to));
    msgToSend.setSubject(msg.subject);
    msgToSend.setText(msg.msg);

    msgToSend.saveChanges();
    Transport.send(msgToSend);
    //tr.sendMessage(msg, msg.getAllRecipients());
    //tr.close();
}

From source file:com.enonic.vertical.userservices.OrderHandlerController.java

private void sendMail(String receiverEmail, String receiverName, String senderEmail, String senderName,
        String subject, String message) throws MessagingException, UnsupportedEncodingException {

    // smtp server
    Properties smtpProperties = new Properties();
    smtpProperties.put("mail.smtp.host", verticalProperties.getMailSmtpHost());
    Session session = Session.getDefaultInstance(smtpProperties, null);

    // create message
    Message msg = new MimeMessage(session);

    // set from address
    if (senderEmail != null && !senderEmail.equals("")) {
        InternetAddress addressFrom = new InternetAddress(senderEmail);
        if (senderName != null && !senderName.equals("")) {
            addressFrom.setPersonal(senderName);
        }/*from w w w .  ja  v a2 s. c  o m*/
        msg.setFrom(addressFrom);
    }

    // set to address
    InternetAddress addressTo = new InternetAddress(receiverEmail);
    if (receiverName != null) {
        addressTo.setPersonal(receiverName);
    }
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    // Setting subject and content type
    msg.setSubject(subject);

    message = RegexpUtil.substituteAll("(\\\\n)", "\n", message);
    msg.setContent(message, "text/plain; charset=UTF-8");

    // send message
    Transport.send(msg);
}

From source file:sk.lazyman.gizmo.web.app.PageEmail.java

private Message createMimeMessage(Session session, String subject)
        throws UnsupportedEncodingException, MessagingException {

    Message mimeMessage = new MimeMessage(session);
    String from = getPropertyValue(MAIL_FROM);
    mimeMessage.setFrom(new InternetAddress(from));

    EmailDto dto = model.getObject();//  www. j  a  v  a 2 s  .c o m

    InternetAddress mailTo[] = convertEmailAddress(dto.getTo());
    mimeMessage.setRecipients(Message.RecipientType.TO, mailTo);

    String mailCc = dto.getCc();
    if (StringUtils.isNotEmpty(mailCc)) {
        mimeMessage.setRecipients(Message.RecipientType.CC, convertEmailAddress(mailCc));
    }
    String mailBcc = dto.getBcc();
    if (StringUtils.isNotEmpty(mailBcc)) {
        mimeMessage.setRecipients(Message.RecipientType.BCC, convertEmailAddress(mailBcc));
    }
    mimeMessage.setSubject(subject);

    return mimeMessage;
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {

    String contentType;/*  w w  w  . j  a  v a 2s.c om*/
    String fileExtension;
    String nameSuffix;
    JobExecutionContext jobExecutionContext;

    logger.debug("IN");

    try {

        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        nameSuffix = dispatchContext.getNameSuffix();
        jobExecutionContext = dispatchContext.getJobExecutionContext();

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";

        int smptPort = 25;

        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");

        /*
        if( (user==null) || user.trim().equals(""))
           throw new Exception("Smtp user not configured");
                
        if( (pass==null) || pass.trim().equals(""))
           throw new Exception("Smtp password not configured");
        */

        String mailTos = "";
        List dlIds = dispatchContext.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(document, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        Session session = null;

        if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
            props.put("mail.smtp.auth", "false");
            session = Session.getInstance(props);
            logger.debug("Connecting to mail server without authentication");
        } else {
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SMTPAuthenticator(user, pass);
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }
            session = Session.getInstance(props, auth);
            logger.debug("Connecting to mail server with authentication");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = document.getName() + nameSuffix;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType,
                document.getName() + nameSuffix + fileExtension);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        //mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }

        if (jobExecutionContext.getNextFireTime() == null) {
            String triggername = jobExecutionContext.getTrigger().getName();
            dlIds = dispatchContext.getDlIds();
            it = dlIds.iterator();
            while (it.hasNext()) {
                Integer dlId = (Integer) it.next();
                DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);
                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                        (document.getId()).intValue(), triggername);
            }
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }

    return true;
}