Example usage for javax.mail Message setFrom

List of usage examples for javax.mail Message setFrom

Introduction

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

Prototype

public abstract void setFrom(Address address) throws MessagingException;

Source Link

Document

Set the "From" attribute in this Message.

Usage

From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

private void sendMail(DispatchContext sInfo, BIObject biobj, Map parMap, byte[] response, String retCT,
        String fileExt, IDataStore dataStore, String toBeAppendedToName, String toBeAppendedToDescription) {
    logger.debug("IN");
    try {/*from  ww w .j av  a2 s . co  m*/

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        int smptPort = 25;

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

        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals("")) {
            logger.debug("Smtp user not configured");
            user = null;
        }
        //   throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals("")) {
            logger.debug("Smtp password not configured");
        }
        //   throw new Exception("Smtp password not configured");

        String mailSubj = sInfo.getMailSubj();
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parMap, null, false);

        String mailTxt = sInfo.getMailTxt();

        String[] recipients = findRecipients(sInfo, biobj, dataStore);
        if (recipients == null || recipients.length == 0) {
            logger.error("No recipients found for email sending!!!");
            return;
        }

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", smptPort);

        // open session
        Session session = null;

        // create autheticator object
        Authenticator auth = null;
        if (user != null) {
            auth = new SMTPAuthenticator(user, pass);
            props.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(props, auth);
            logger.error("Session.getDefaultInstance(props, auth)");
        } else {
            session = Session.getDefaultInstance(props);
            logger.error("Session.getDefaultInstance(props)");
        }

        // 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
        String subject = mailSubj + " " + biobj.getName() + toBeAppendedToName;
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt + "\n" + toBeAppendedToDescription);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message

        SchedulerDataSource sds = new SchedulerDataSource(response, retCT,
                biobj.getName() + toBeAppendedToName + fileExt);
        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
        Transport.send(msg);
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
    } finally {
        logger.debug("OUT");
    }
}

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  w  w  w  . j a  v  a  2  s .  c om
    }

    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:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message 
    if (ArgList.length == 5) {

        try {//w  w  w.j a v  a2  s  .c om
            //Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

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

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String strArrRecipients[] = ((String) ArgList[2]).split(",");

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

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent((String) ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw new RuntimeException("sendMail: " + e.toString());
        }
    } else {
        throw new RuntimeException("The function call sendMail requires 5 arguments.");
    }
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static void sendMail(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message 
    if (ArgList.length == 5) {

        try {//w  w  w.  j a  va  2s.  co  m
            //Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

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

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String strArrRecipients[] = ((String) ArgList[2]).split(",");

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

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent((String) ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw Context.reportRuntimeError("sendMail: " + e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call sendMail requires 5 arguments.");
    }
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message
    if (ArgList.length == 5) {

        try {/*  w  ww  . ja va  2  s  .  co m*/
            // Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

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

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String[] strArrRecipients = ((String) ArgList[2]).split(",");

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

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent(ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw new RuntimeException("sendMail: " + e.toString());
        }
    } else {
        throw new RuntimeException("The function call sendMail requires 5 arguments.");
    }
}

From source file:smilehouse.opensyncro.pipes.Pipe.java

private void addLogEntry(LogEntry logEntry, int statusCode) {
    if (this.log == null)
        this.log = new HashSet();

    logEntry.setStatusCode(statusCode);//from  w  w w.j a  v  a 2  s  .com
    logEntry.setTime(new Date());

    // The LogEntry is not explicitly added to the Pipe's log Set, since it causes
    // Hibernate to query all LogEntries from the database and thus consume
    // ever-increasing amount of server resources.

    //this.log.add(logEntry);
    String status = getStatusString(statusCode);

    Persister persister = new Persister(database);

    try {
        persister.update(logEntry);

        List messages;

        boolean mailAddressNotSet = ((getMailHost() == null || getRecipientAddress() == null)
                || (getMailHost().length() == 0 || getRecipientAddress().length() == 0));

        // Notification via email only if host and email address are present
        if (!mailAddressNotSet && !(getTransferLogNotificationLevel() == MessageLogger.MAIL_NONE)) {

            String date = dateFormat.format(new Date());
            String subject = this.getName() + " " + status + " " + date + " (" + database + ")";
            String message = "";

            // Get number of log messages at or below transferLogNotificationLevel.  

            int entries = persister.getLogMessageEntries(logEntry.getId(), getTransferLogNotificationLevel())
                    .size();

            //Generate mail message
            if (entries > 0) {

                messages = persister.getLogMessageEntries(logEntry.getId(), getLoggingVerbosityLevel());
                for (Iterator m = messages.iterator(); m.hasNext();) {
                    LogMessageEntry messageEntry = (LogMessageEntry) m.next();
                    message += (messageEntry.getMessage()) + "\n";
                }
            } else {
                message += MAIL_MESSAGE_NO_ENTRIES;
            }

            // Send notification email except when the message is
            // MAIL_MESSAGE_NO_ENTRIES or the pipe has aborted and 
            // isAbortMailEnabled()==true 
            if (!message.equals(MAIL_MESSAGE_NO_ENTRIES)
                    || (statusCode == LogEntry.STATUS_ABORTED && isAbortMailEnabled())) {
                try {

                    Properties props = new Properties();
                    props.put("mail.host", getMailHost());

                    Session mailConnection = Session.getInstance(props, null);
                    Message msg = new MimeMessage(mailConnection);
                    Address sender = new InternetAddress(MAIL_SENDER + "@" + getMailHost(), MAIL_SENDER);
                    Address[] receivers = receiverAddresses(getRecipientAddress());

                    // Set mail content and subject
                    msg.setContent(message, "text/plain");
                    msg.setFrom(sender);
                    msg.setRecipients(Message.RecipientType.TO, receivers);
                    msg.setSubject(subject);

                    // Send the mail
                    Transport.send(msg);

                } catch (MessagingException e) {
                    String error = "An error occurred when sending mail report from " + MAIL_SENDER + "@"
                            + getMailHost() + " to " + getRecipientAddress() + ":\n" + e.getMessage();
                    Environment.getInstance().log(error);
                    logEntry.logMessage(error, this, MessageLogger.ERROR);
                    persister.update(logEntry);
                } catch (RuntimeException ex) {
                    Environment.getInstance().log("A RuntimeException has occurred: " + ex.getMessage()
                            + ex.getStackTrace().toString());
                }
            }
        }
        // Remove unnecessary (debug level) messages from the LogEntry if Transfer log
        // verbosity level is set to DYNAMIC and the current LogEntry's status is either
        // OK or ABORTED
        if (getLoggingVerbosityLevel() == MessageLogger.LOG_DYNAMIC
                && (statusCode == LogEntry.STATUS_OK || statusCode == LogEntry.STATUS_ABORTED)) {
            messages = persister.getLogMessageEntries(logEntry.getId(), MessageLogger.DEBUG);
            if (messages.size() > 0) {
                for (Iterator m = messages.iterator(); m.hasNext();) {
                    LogMessageEntry messageEntry = (LogMessageEntry) m.next();
                    if (messageEntry.getMessageType() == MessageLogger.DEBUG) {
                        persister.delete(messageEntry);

                    }
                }
            }
        }
    } catch (Exception e) {
        Environment.getInstance().log(e.getMessage());
    } finally {
        persister.close();
    }
}

From source file:com.panet.imeta.trans.steps.mail.Mail.java

public void sendMail(Object[] r, String server, String port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {//from w w w  .ja v  a2 s  . c  om
            protocol = "smtps";
            // required to get rid of a SSL exception :
            //  nested exception is:
            //  javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (!Const.isEmpty(port))
        data.props.put("mail." + protocol + ".port", port);
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        data.props.put("mail.debug", "true");

    if (meta.isUsingAuthentication())
        data.props.put("mail." + protocol + ".auth", "true");

    Session session = Session.getInstance(data.props);
    session.setDebug(debug);

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

    // set message priority
    if (meta.isUsePriority()) {
        String priority_int = "1";
        if (meta.getPriority().equals("low"))
            priority_int = "3";
        if (meta.getPriority().equals("normal"))
            priority_int = "2";

        msg.setHeader("X-Priority", priority_int); //(String)int between 1= high and 3 = low.
        msg.setHeader("Importance", meta.getImportance());
        //seems to be needed for MS Outlook.
        //where it returns a string of high /normal /low.
    }

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName))
            email_address = senderName + '<' + email_address + '>';
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(Messages.getString("Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to 
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.split(" ");
        InternetAddress[] address = new InternetAddress[reply_Address_List.length];

        for (int i = 0; i < reply_Address_List.length; i++)
            address[i] = new InternetAddress(reply_Address_List[i]);

        // To add the real reply-to 
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String destinations[] = destination.split(" ");
    InternetAddress[] address = new InternetAddress[destinations.length];
    for (int i = 0; i < destinations.length; i++)
        address[i] = new InternetAddress(destinations[i]);

    msg.setRecipients(Message.RecipientType.TO, address);

    String realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String destinationsCc[] = realdestinationCc.split(" ");
        InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
        for (int i = 0; i < destinationsCc.length; i++)
            addressCc[i] = new InternetAddress(destinationsCc[i]);

        msg.setRecipients(Message.RecipientType.CC, addressCc);
    }

    String realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String destinationsBCc[] = realdestinationBCc.split(" ");
        InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
        for (int i = 0; i < destinationsBCc.length; i++)
            addressBCc[i] = new InternetAddress(destinationsBCc[i]);

        msg.setRecipients(Message.RecipientType.BCC, addressBCc);
    }

    if (mailsubject != null)
        msg.setSubject(mailsubject);

    msg.setSentDate(new Date());
    StringBuffer messageText = new StringBuffer();

    if (comment != null)
        messageText.append(comment).append(Const.CR).append(Const.CR);

    if (meta.getIncludeDate())
        messageText.append(Messages.getString("Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(Messages.getString("Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(Messages.getString("Mail.Log.Comment.PersonToContact") + " : ").append(contactPerson)
                .append(Const.CR);
        messageText.append(Messages.getString("Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

    MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
    // 1st part

    if (meta.isUseHTML()) {
        if (!Const.isEmpty(meta.getEncoding()))
            part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
        else
            part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
    } else
        part1.setText(messageText.toString());

    data.parts.addBodyPart(part1);

    // attached files
    if (meta.isDynamicFilename())
        setAttachedFilesList(r, log);
    else
        setAttachedFilesList(null, log);

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (!Const.isEmpty(port)) {
                transport.connect(Const.NVL(server, ""), Integer.parseInt(Const.NVL(port, "")),
                        Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null)
            transport.close();
    }

}

From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static void sendMail(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message
    if (ArgList.length == 5) {

        try {//from w  ww .  j a  v a  2  s  .  co  m
            // Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

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

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String[] strArrRecipients = ((String) ArgList[2]).split(",");

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

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent(ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw Context.reportRuntimeError("sendMail: " + e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call sendMail requires 5 arguments.");
    }
}

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;/*  w  ww  . j  a  va  2  s. 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:org.pentaho.di.trans.steps.mail.Mail.java

public void sendMail(Object[] r, String server, int port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingSecureAuthentication()) { // PDI-2955
        // if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {//  w w  w  . j a  va 2s. co  m
            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (port != -1) {
        data.props.put("mail." + protocol + ".port", "" + port); // needs to be supplied as a string, not as an integer
    }

    if (isDebug()) {
        data.props.put("mail.debug", "true");
    }

    if (meta.isUsingAuthentication()) {
        data.props.put("mail." + protocol + ".auth", "true");
    }

    Session session = Session.getInstance(data.props);
    session.setDebug(isDebug());

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

    // set message priority
    if (meta.isUsePriority()) {
        String priority_int = "1";
        if (meta.getPriority().equals("low")) {
            priority_int = "3";
        }
        if (meta.getPriority().equals("normal")) {
            priority_int = "2";
        }

        msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low.
        msg.setHeader("Importance", meta.getImportance());
        // seems to be needed for MS Outlook.
        // where it returns a string of high /normal /low.
        msg.setHeader("Sensitivity", meta.getSensitivity());
        // Possible values are normal, personal, private, company-confidential
    }

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName)) {
            email_address = senderName + '<' + email_address + '>';
        }
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(BaseMessages.getString(PKG, "Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.split(" ");
        InternetAddress[] address = new InternetAddress[reply_Address_List.length];

        for (int i = 0; i < reply_Address_List.length; i++) {
            address[i] = new InternetAddress(reply_Address_List[i]);
        }

        // To add the real reply-to
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String[] destinations = destination.split(" ");
    InternetAddress[] address = new InternetAddress[destinations.length];
    for (int i = 0; i < destinations.length; i++) {
        address[i] = new InternetAddress(destinations[i]);
    }

    msg.setRecipients(Message.RecipientType.TO, address);

    String realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String[] destinationsCc = realdestinationCc.split(" ");
        InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
        for (int i = 0; i < destinationsCc.length; i++) {
            addressCc[i] = new InternetAddress(destinationsCc[i]);
        }

        msg.setRecipients(Message.RecipientType.CC, addressCc);
    }

    String realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String[] destinationsBCc = realdestinationBCc.split(" ");
        InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
        for (int i = 0; i < destinationsBCc.length; i++) {
            addressBCc[i] = new InternetAddress(destinationsBCc[i]);
        }

        msg.setRecipients(Message.RecipientType.BCC, addressBCc);
    }

    if (mailsubject != null) {
        msg.setSubject(mailsubject);
    }

    msg.setSentDate(new Date());
    StringBuffer messageText = new StringBuffer();

    if (comment != null) {
        messageText.append(comment).append(Const.CR).append(Const.CR);
    }

    if (meta.getIncludeDate()) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
    }

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.PersonToContact") + " : ")
                .append(contactPerson).append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

    MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
    // 1st part

    if (meta.isUseHTML()) {
        if (!Const.isEmpty(meta.getEncoding())) {
            part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
        } else {
            part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
        }
    } else {
        part1.setText(messageText.toString());
    }

    data.parts.addBodyPart(part1);

    if (meta.isAttachContentFromField()) {
        // attache file content
        addAttachedContent(data.previousRowMeta.getString(r, data.IndexOfAttachedFilename),
                data.previousRowMeta.getString(r, data.indexOfAttachedContent));
    } else {
        // attached files
        if (meta.isDynamicFilename()) {
            setAttachedFilesList(r, log);
        } else {
            setAttachedFilesList(null, log);
        }
    }

    // add embedded images
    addImagePart();

    if (data.nrEmbeddedImages > 0 && data.nrattachedFiles == 0) {
        // If we need to embedd images...
        // We need to create a "multipart/related" message.
        // otherwise image will appear as attached file
        data.parts.setSubType("related");
    }

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (port != -1) {
                transport.connect(Const.NVL(server, ""), port, Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null) {
            transport.close();
        }
    }

}