Example usage for javax.mail Message setText

List of usage examples for javax.mail Message setText

Introduction

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

Prototype

public void setText(String text) throws MessagingException;

Source Link

Document

A convenience method that sets the given String as this part's content with a MIME type of "text/plain".

Usage

From source file:org.kite9.diagram.server.AbstractKite9Controller.java

public void sendErrorEmail(Throwable t, String xml, String url) {
    try {//from   ww  w .j a  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:GUI.DashbordAdminFrame.java

private void btnEnvMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnvMailActionPerformed
    // TODO add your handling code here:
    String to = null;//from  w  ww  . j  a v  a2s.c  o  m
    UserDao u = new UserDao();
    List listeTo = new ArrayList();
    listeTo = u.findAllEmail();

    String from = "allfordealpi@gmail.com";
    final String username = "allfordealpi@gmail.com";
    final String password = "pidev2016";

    String host = "smtp.gmail.com";

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

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

    try {

        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        for (Object o : listeTo) {

            to = (String) o;
            System.out.println(to);
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

            message.setSubject(tfObjet.getText());

            message.setText(taContenu.getText());

            // Send message
            Transport.send(message);
        }
        System.out.println("Sent message successfully....");

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

}

From source file:userinterface.DoctorWorkArea.DiagnosePatientJPanel.java

private void addtoCartButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addtoCartButton6ActionPerformed
    // TODO add your handling code here:

    int selectedRow = productTable.getSelectedRow();
    if (selectedRow < 0) {
        JOptionPane.showMessageDialog(null, "Please select a Product from the Table");
        return;//from  ww  w .  ja va 2s .  com
    }

    Product product = (Product) productTable.getValueAt(selectedRow, 0);
    int quantity = (Integer) quantitySpinner.getValue();
    if (quantity == 0) {
        JOptionPane.showMessageDialog(null, "Please enter a number for Medicine Quantity!");
        return;
    }

    if (product != null) {
        updateQuantity(product, quantity, SUBTRACT);
    }
    String medName = product.getProdName();

    Employee patient = (Employee) patientCombo1.getSelectedItem();
    patient.getMedicalRecord().setMedicinePrescribed(medName);
    String email = patient.getEmail();

    if (email.trim().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Patient profile is not updated for email!");
        return;
    }

    if (isValidEmailAddress(email)) {
        String uuid = UUID.randomUUID().toString();
        //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample");

        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("neelzsaxena@gmail.com", "painforever24");
            }

        }

        );
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("neelzsaxena@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject("Prescribed Medicines");
            message.setText("The medicine Prescribed is :" + medName + '\n' + "The Quantity authorized is:"
                    + quantity + '\n' + "The unique barcode is:" + uuid);
            Transport.send(message);
            populateTable();
            JOptionPane.showMessageDialog(null, "message sent");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "message failed");
        }

    } else {
        JOptionPane.showMessageDialog(null, "Invalid Email Id");
        return;
    }

    //        String uuid = UUID.randomUUID().toString();
    //        //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample");
    //        
    //        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("neelzsaxena@gmail.com", "painforever24");
    //                    }
    //   
    //            }
    //
    //   );
    //        try{
    //            Message message = new MimeMessage(session);
    //            message.setFrom(new InternetAddress("neelzsaxena@gmail.com"));
    //            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
    //            message.setSubject("Prescribed Medicines");
    //            message.setText("The medicine Prescribed is :" +medName + '\n'+
    //                            "The Quantity authorized is:"+quantity + '\n'+
    //                            "The unique barcode is:"+uuid);
    //                Transport.send(message);
    //                    populateTable();
    //                    JOptionPane.showMessageDialog(null,"message sent");
    //            }catch(Exception e){
    //                JOptionPane.showMessageDialog(null,"message failed");
    //            }

}

From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java

/**
 * Prepares message prior to be sent via execute()-method, i.e. sets
 * properties such as protocol, authentication, etc.
 *
 * @return Message-object to be sent to execute()-method
 * @throws MessagingException/*  w  w w  .  j  av a2s. co m*/
 *             when problems constructing or sending the mail occur
 * @throws IOException
 *             when the mail content can not be read or truststore problems
 *             are detected
 */
public Message prepareMessage() throws MessagingException, IOException {

    Properties props = new Properties();

    String protocol = getProtocol();

    // set properties using JAF
    props.setProperty("mail." + protocol + ".host", smtpServer);
    props.setProperty("mail." + protocol + ".port", getPort());
    props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication));

    // set timeout
    props.setProperty("mail." + protocol + ".timeout", getTimeout());
    props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout());

    if (useStartTLS || useSSL) {
        try {
            String allProtocols = StringUtils
                    .join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " ");
            logger.info("Use ssl/tls protocols for mail: " + allProtocols);
            props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols);
        } catch (Exception e) {
            logger.error("Problem setting ssl/tls protocols for mail", e);
        }
    }

    if (enableDebug) {
        props.setProperty("mail.debug", "true");
    }

    if (useStartTLS) {
        props.setProperty("mail.smtp.starttls.enable", "true");
        if (enforceStartTLS) {
            // Requires JavaMail 1.4.2+
            props.setProperty("mail.smtp.starttls.require", "true");
        }
    }

    if (trustAllCerts) {
        if (useSSL) {
            props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    } else if (useLocalTrustStore) {
        File truststore = new File(trustStoreToUse);
        logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
        if (!truststore.exists()) {
            logger.info(
                    "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
            truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse);
            logger.info("load local truststore -Attempting to read truststore from:  "
                    + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                logger.info(
                        "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()
                                + ". Local truststore not available, aborting execution.");
                throw new IOException("Local truststore file not found. Also not available under : "
                        + truststore.getAbsolutePath());
            }
        }
        if (useSSL) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    }

    session = Session.getInstance(props, null);

    Message message;

    if (sendEmlMessage) {
        message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
    } else {
        message = new MimeMessage(session);
        // handle body and attachments
        Multipart multipart = new MimeMultipart();
        final int attachmentCount = attachments.size();
        if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
            if (attachmentCount == 1) { // i.e. mailBody is empty
                File first = attachments.get(0);
                InputStream is = null;
                try {
                    is = new BufferedInputStream(new FileInputStream(first));
                    message.setText(IOUtils.toString(is));
                } finally {
                    IOUtils.closeQuietly(is);
                }
            } else {
                message.setText(mailBody);
            }
        } else {
            BodyPart body = new MimeBodyPart();
            body.setText(mailBody);
            multipart.addBodyPart(body);
            for (File f : attachments) {
                BodyPart attach = new MimeBodyPart();
                attach.setFileName(f.getName());
                attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
                multipart.addBodyPart(attach);
            }
            message.setContent(multipart);
        }
    }

    // set from field and subject
    if (null != sender) {
        message.setFrom(new InternetAddress(sender));
    }

    if (null != replyTo) {
        InternetAddress[] to = new InternetAddress[replyTo.size()];
        message.setReplyTo(replyTo.toArray(to));
    }

    if (null != subject) {
        message.setSubject(subject);
    }

    if (receiverTo != null) {
        InternetAddress[] to = new InternetAddress[receiverTo.size()];
        receiverTo.toArray(to);
        message.setRecipients(Message.RecipientType.TO, to);
    }

    if (receiverCC != null) {
        InternetAddress[] cc = new InternetAddress[receiverCC.size()];
        receiverCC.toArray(cc);
        message.setRecipients(Message.RecipientType.CC, cc);
    }

    if (receiverBCC != null) {
        InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
        receiverBCC.toArray(bcc);
        message.setRecipients(Message.RecipientType.BCC, bcc);
    }

    for (int i = 0; i < headerFields.size(); i++) {
        Argument argument = (Argument) ((TestElementProperty) headerFields.get(i)).getObjectValue();
        message.setHeader(argument.getName(), argument.getValue());
    }

    message.saveChanges();
    return message;
}

From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java

protected void fillContent(Message email, Execution execution, JCRSessionWrapper session)
        throws MessagingException {
    String text = getTemplate().getText();
    String html = getTemplate().getHtml();
    List<AttachmentTemplate> attachmentTemplates = getTemplate().getAttachmentTemplates();

    try {//from  w  ww.  ja  v  a 2s.c  o  m
        if (html != null || !attachmentTemplates.isEmpty()) {
            // multipart
            MimeMultipart multipart = new MimeMultipart("related");

            BodyPart p = new MimeBodyPart();
            Multipart alternatives = new MimeMultipart("alternative");
            p.setContent(alternatives, "multipart/alternative");
            multipart.addBodyPart(p);

            // html
            if (html != null) {
                BodyPart htmlPart = new MimeBodyPart();
                html = evaluateExpression(execution, html, session);
                htmlPart.setContent(html, "text/html; charset=UTF-8");
                alternatives.addBodyPart(htmlPart);
            }

            // text
            if (text != null) {
                BodyPart textPart = new MimeBodyPart();
                text = evaluateExpression(execution, text, session);
                textPart.setContent(text, "text/plain; charset=UTF-8");
                alternatives.addBodyPart(textPart);
            }

            // attachments
            if (!attachmentTemplates.isEmpty()) {
                addAttachments(execution, multipart);
            }

            email.setContent(multipart);
        } else if (text != null) {
            // unipart
            text = evaluateExpression(execution, text, session);
            email.setText(text);
        }
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    } catch (ScriptException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

protected void fillContent(MailTemplate template, Message email, WorkItem workItem, JCRSessionWrapper session)
        throws Exception {
    String text = template.getText();
    String html = template.getHtml();
    List<AttachmentTemplate> attachmentTemplates = template.getAttachmentTemplates();

    if (html != null || !attachmentTemplates.isEmpty()) {
        // multipart
        MimeMultipart multipart = new MimeMultipart("related");

        BodyPart p = new MimeBodyPart();
        Multipart alternatives = new MimeMultipart("alternative");
        p.setContent(alternatives, "multipart/alternative");
        multipart.addBodyPart(p);/*from   w  w w .  java  2  s.  c  o  m*/

        // html
        if (html != null) {
            BodyPart htmlPart = new MimeBodyPart();
            html = evaluateExpression(workItem, html, session);
            htmlPart.setContent(html, "text/html; charset=UTF-8");
            alternatives.addBodyPart(htmlPart);
        }

        // text
        if (text != null) {
            BodyPart textPart = new MimeBodyPart();
            text = evaluateExpression(workItem, text, session);
            textPart.setContent(text, "text/plain; charset=UTF-8");
            alternatives.addBodyPart(textPart);
        }

        // attachments
        if (!attachmentTemplates.isEmpty()) {
            addAttachments(template, workItem, multipart, session);
        }

        email.setContent(multipart);
    } else if (text != null) {
        // unipart
        text = evaluateExpression(workItem, text, session);
        email.setText(text);
    }
}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

private void sendEmail(SmtpMessage msg) throws MessagingException {
    Properties props = new Properties();
    boolean doAuth = false;
    props.setProperty("mail.smtp.host", prov.getSmtpHost());
    props.setProperty("mail.smtp.port", Integer.toString(prov.getSmtpPort()));
    if (prov.getSmtpUser() != null && !prov.getSmtpUser().isEmpty()) {
        logger.debug("SMTP user found '" + prov.getSmtpUser() + "', enabling authentication");
        props.setProperty("mail.smtp.user", prov.getSmtpUser());
        props.setProperty("mail.smtp.auth", "true");
        doAuth = true;// ww w.  j av  a  2s . c  o m
    } else {
        logger.debug("No SMTP user, disabling authentication");
        doAuth = false;
        props.setProperty("mail.smtp.auth", "false");
    }
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.starttls.enable", Boolean.toString(prov.isSmtpTLS()));
    if (logger.isDebugEnabled()) {
        props.setProperty("mail.debug", "true");
        props.setProperty("mail.socket.debug", "true");
    }

    if (prov.getLocalhost() != null && !prov.getLocalhost().isEmpty()) {
        props.setProperty("mail.smtp.localhost", prov.getLocalhost());
    }

    if (prov.isUseSOCKSProxy()) {

        props.setProperty("mail.smtp.socks.host", prov.getSocksProxyHost());

        props.setProperty("mail.smtp.socks.port", Integer.toString(prov.getSocksProxyPort()));
        props.setProperty("mail.smtps.socks.host", prov.getSocksProxyHost());

        props.setProperty("mail.smtps.socks.port", Integer.toString(prov.getSocksProxyPort()));
    }

    //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword));

    Session session = null;
    if (doAuth) {
        logger.debug("Creating authenticated session");
        session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(prov.getSmtpUser(), prov.getSmtpPassword());
            }
        });
    } else {
        logger.debug("Creating unauthenticated session");
        session = Session.getInstance(props);
    }
    if (logger.isDebugEnabled()) {
        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);

    if (msg.contentType != null) {
        msgToSend.setContent(msg.msg, msg.contentType);
    } else {
        msgToSend.setText(msg.msg);
    }

    msgToSend.saveChanges();
    Transport.send(msgToSend);

    //tr.sendMessage(msg, msg.getAllRecipients());
    //tr.close();
}

From source file:com.cabserver.handler.Admin.java

@POST
@Path("forgot-password")
@Produces(MediaType.TEXT_HTML)//w  ww .j a  v a 2s.c  om
public Response forgotPassword(String jsonData) {
    // String data = "";
    HashMap<String, String> responseMap = new HashMap<String, String>();
    try {

        // log.info("forgotPassword before decoding = " + jsonData);

        jsonData = (URLDecoder.decode(jsonData, "UTF-8"));

        // log.info("forgotPassword >>" + jsonData);

        // jsonData = jsonData.split("=")[1];
        if (jsonData.contains("=")) {
            jsonData = jsonData.split("=")[1];
            // log.info("forgotPassword >> data=" + jsonData);
        }

        log.info("forgotPassword >> json data=" + jsonData);

        if (jsonData != null && jsonData.length() > 1) {

            // Gson gson = new Gson();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(jsonData);

            // LoginInfo result = new LoginInfo();
            String phone = (String) obj.get("phone");
            // String password = (String) obj.get("password");

            // log.info("phone =" + phone);
            // log.info("password =" + password);

            if (phone != null) {

                UserMaster um = DatabaseManager.getEmailIdByPhone(phone);

                if (um != null) {

                    log.info("forgotPassword >> Email fetched by phone number. HTTP code is 200.");

                    responseMap.put("code", "200");
                    responseMap.put("msg", "Password is sent to your registered E-Mail ID.");
                    responseMap.put("phone", phone);
                    // responseMap.put("password", um.getPassword());
                    // responseMap.put("mailid", um.getMailId());

                    try {

                        if (Boolean.parseBoolean(ConfigDetails.constants.get("LOCAL_MAIL_SEND"))) {

                            Message message = new MimeMessage(CacheBuilder.session);
                            message.setFrom(new InternetAddress("VikingTaxee@gmail.com"));
                            message.setRecipients(Message.RecipientType.TO,
                                    InternetAddress.parse(um.getMailId()));
                            message.setSubject("VikingTaxee Account Password Information");
                            message.setText("Dear Customer You password is : " + "\n\n " + um.getPassword());

                            Transport.send(message);

                            log.info("forgotPassword >> Password is sent to your registered E-Mail ID.");

                        } else {

                            TravelMaster tm = new TravelMaster();

                            tm.setFromMailId("VikingTaxee@gmail.com");
                            tm.setToMailId(um.getMailId());
                            tm.setSubject("VikingTaxee Account Password Information");
                            tm.setMailText(um.getPassword());
                            tm.setMailType(
                                    Integer.parseInt(ConfigDetails.constants.get("MAIL_TYPE_FORGOT_PASSWORD")));

                            CacheBuilder.mailSendingDataMap.put((long) new Random().nextInt(100000), tm);
                        }

                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                } else {
                    log.info("forgotPassword >> Password reset not done. Please call customer Care.");

                    responseMap.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
                    responseMap.put("msg",
                            "Forgot password process can not be completed. Please call customer Care.");

                }

            }

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (responseMap.size() < 1) {

        log.info("Login Error. HTTP bookingStatus code is " + ConfigDetails.constants.get("BOOKING_FAILED_CODE")
                + ".");

        responseMap.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
        responseMap.put("msg", "Server Error.");
        return Response.status(200).entity(jsonCreater(responseMap)).build();
    } else {
        return Response.status(200).entity(jsonCreater(responseMap)).build();
    }

}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

public void start(PipelineContext pipelineContext) {
    try {//from  w ww . ja va 2s .  c o m
        final Document dataDocument = readInputAsDOM4J(pipelineContext, INPUT_DATA);
        final Element messageElement = dataDocument.getRootElement();

        // Get system id (will likely be null if document is generated dynamically)
        final LocationData locationData = (LocationData) messageElement.getData();
        final String dataInputSystemId = locationData.getSystemID();

        // Set SMTP host
        final Properties properties = new Properties();
        final String testSmtpHostProperty = getPropertySet().getString(EMAIL_TEST_SMTP_HOST);

        if (testSmtpHostProperty != null) {
            // Test SMTP Host from properties overrides the local configuration
            properties.setProperty("mail.smtp.host", testSmtpHostProperty);
        } else {
            // Try regular config parameter and property
            String host = messageElement.element("smtp-host").getTextTrim();
            if (host != null && !host.equals("")) {
                // Precedence goes to the local config parameter
                properties.setProperty("mail.smtp.host", host);
            } else {
                // Otherwise try to use a property
                host = getPropertySet().getString(EMAIL_SMTP_HOST);
                if (host == null)
                    host = getPropertySet().getString(EMAIL_HOST_DEPRECATED);
                if (host == null)
                    throw new OXFException("Could not find SMTP host in configuration or in properties");
                properties.setProperty("mail.smtp.host", host);

            }
        }

        // Create session
        final Session session;
        {
            // Get credentials
            final String usernameTrimmed;
            final String passwordTrimmed;
            {
                final Element credentials = messageElement.element("credentials");
                if (credentials != null) {
                    final Element usernameElement = credentials.element("username");
                    final Element passwordElement = credentials.element("password");
                    usernameTrimmed = (usernameElement != null) ? usernameElement.getStringValue().trim()
                            : null;
                    passwordTrimmed = (passwordElement != null) ? passwordElement.getStringValue().trim() : "";
                } else {
                    usernameTrimmed = null;
                    passwordTrimmed = null;
                }
            }

            // Check if credentials are supplied
            if (StringUtils.isNotEmpty(usernameTrimmed)) {
                // NOTE: A blank username doesn't trigger authentication

                if (logger.isInfoEnabled())
                    logger.info("Authentication");
                // Set the auth property to true
                properties.setProperty("mail.smtp.auth", "true");

                if (logger.isInfoEnabled())
                    logger.info("Username: " + usernameTrimmed);

                // Create an authenticator
                final Authenticator authenticator = new SMTPAuthenticator(usernameTrimmed, passwordTrimmed);

                // Create session with authenticator
                session = Session.getInstance(properties, authenticator);
            } else {
                if (logger.isInfoEnabled())
                    logger.info("No Authentication");
                session = Session.getInstance(properties);
            }
        }

        // Create message
        final Message message = new MimeMessage(session);

        // Set From
        message.addFrom(createAddresses(messageElement.element("from")));

        // Set To
        String testToProperty = getPropertySet().getString(EMAIL_TEST_TO);
        if (testToProperty == null)
            testToProperty = getPropertySet().getString(EMAIL_FORCE_TO_DEPRECATED);

        if (testToProperty != null) {
            // Test To from properties overrides local configuration
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(testToProperty));
        } else {
            // Regular list of To elements
            for (final Element toElement : Dom4jUtils.elements(messageElement, "to")) {
                final InternetAddress[] addresses = createAddresses(toElement);
                message.addRecipients(Message.RecipientType.TO, addresses);
            }
        }

        // Set Cc
        for (final Element ccElement : Dom4jUtils.elements(messageElement, "cc")) {
            final InternetAddress[] addresses = createAddresses(ccElement);
            message.addRecipients(Message.RecipientType.CC, addresses);
        }

        // Set Bcc
        for (final Element bccElement : Dom4jUtils.elements(messageElement, "bcc")) {
            final InternetAddress[] addresses = createAddresses(bccElement);
            message.addRecipients(Message.RecipientType.BCC, addresses);
        }

        // Set headers if any
        for (final Element headerElement : Dom4jUtils.elements(messageElement, "header")) {
            final String headerName = headerElement.element("name").getTextTrim();
            final String headerValue = headerElement.element("value").getTextTrim();

            // NOTE: Use encodeText() in case there are non-ASCII characters
            message.addHeader(headerName,
                    MimeUtility.encodeText(headerValue, DEFAULT_CHARACTER_ENCODING, null));
        }

        // Set the email subject
        // The JavaMail spec is badly written and is not clear about whether this needs to be done here. But it
        // seems to use the platform's default charset, which we don't want to deal with. So we preemptively encode.
        // The result is pure ASCII so that setSubject() will not attempt to re-encode it.
        message.setSubject(MimeUtility.encodeText(messageElement.element("subject").getStringValue(),
                DEFAULT_CHARACTER_ENCODING, null));

        // Handle body
        final Element textElement = messageElement.element("text");
        final Element bodyElement = messageElement.element("body");

        if (textElement != null) {
            // Old deprecated mechanism (simple text body)
            message.setText(textElement.getStringValue());
        } else if (bodyElement != null) {
            // New mechanism with body and parts
            handleBody(pipelineContext, dataInputSystemId, message, bodyElement);
        } else {
            throw new OXFException("Main text or body element not found");// TODO: location info
        }

        // Send message
        final Transport transport = session.getTransport("smtp");
        Transport.send(message);
        transport.close();
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:com.quinsoft.zeidon.zeidonoperations.ZDRVROPR.java

public int CreateSeeMessage(int lConnection, String szSMTPServer, String szUserEmailAddress,
        String szRecipientEmailAddress, String szCCAddress, String szBCCAddress, String szSubjectText,
        int MimeType, String szMessageBody, String string4, String string5, int attachmentFlag,
        String szAttachmentFileName, String szUserEmailName, String szUserEmailPassword) {
    InternetAddress fromAddress = null;/*ww  w  .  j a v  a  2  s.  c o m*/
    String host = szSMTPServer; //enc-exhub.enc-ad.enc.edu
    String from = szUserEmailAddress;
    String to[] = szRecipientEmailAddress.split("[\\s,;]+");
    InternetAddress[] toAddress = new InternetAddress[to.length];
    String cc[] = szCCAddress.split("[\\s,;]+");
    InternetAddress[] ccAddress = new InternetAddress[cc.length];
    String bcc[] = szBCCAddress.split("[\\s,;]+");
    InternetAddress[] bccAddress = new InternetAddress[bcc.length];
    //String host = "enc-exhub.enc-ad.enc.edu";
    //String from = "kellysautter@comcast.net";
    //String to = "kellysautter@comcast.net";

    // Set properties
    Properties props = new Properties();
    //mail.smtp.sendpartial
    props.put("mail.smtp.host", host);
    props.put("mail.debug", "true");

    // Get session
    // Going to use getDefaultInstance
    // If I get java.lang.SecurityException: Access to default session denied
    // then it said to go use .getInstance(props).
    Session session = Session.getDefaultInstance(props);

    try {
        // Instantiate a message
        Message msg = new MimeMessage(session);

        try {
            if (from != null && !from.isEmpty())
                fromAddress = new InternetAddress(from);
            if (szRecipientEmailAddress != null && !szRecipientEmailAddress.isEmpty()) {
                for (int iCnt = 0; iCnt < to.length; iCnt++) {
                    toAddress[iCnt] = new InternetAddress(to[iCnt]);
                }
            }
            if (szCCAddress != null && !szCCAddress.isEmpty()) {
                for (int iCnt = 0; iCnt < cc.length; iCnt++) {
                    ccAddress[iCnt] = new InternetAddress(cc[iCnt]);
                }
            }
            if (szBCCAddress != null && !szBCCAddress.isEmpty()) {
                for (int iCnt = 0; iCnt < bcc.length; iCnt++) {
                    bccAddress[iCnt] = new InternetAddress(bcc[iCnt]);
                }
            }
        } catch (AddressException e) {
            task.log().error("*** CreateSeeMessage: setting addresses **** ");
            task.log().error(e);
            return -1;
        }
        // Set the FROM message
        msg.setFrom(fromAddress);

        if (szRecipientEmailAddress != null && !szRecipientEmailAddress.isEmpty())
            msg.setRecipients(Message.RecipientType.TO, toAddress);
        if (szCCAddress != null && !szCCAddress.isEmpty())
            msg.setRecipients(Message.RecipientType.CC, ccAddress);
        if (szBCCAddress != null && !szBCCAddress.isEmpty())
            msg.setRecipients(Message.RecipientType.BCC, bccAddress);

        // Set the message subject and date we sent it.
        msg.setSubject(szSubjectText);
        msg.setSentDate(new Date());

        // Set message content
        msg.setText(szMessageBody);

        // Send the message
        Transport.send(msg);
    } catch (MessagingException mex) {
        task.log().error("*** CreateSeeMessage: Transport.send error ****  ");
        task.log().error(mex);
        // Email was bad?
        if (mex instanceof SendFailedException)
            return -1;

        // SMTP connection bad?
        return -2;
    }

    return 0;
}