Forum Stats

  • 3,815,776 Users
  • 2,259,079 Discussions
  • 7,893,225 Comments

Discussions

Java - Add Email Subject and Body

frank.anellia
frank.anellia Member Posts: 104
edited Dec 6, 2017 7:30PM in Java Programming

Hello,

I have this program I've been working on that monitors the size of Linux mounts on servers.  Here is the code:

import java.io.IOException;import java.nio.file.FileStore;import java.nio.file.FileSystems;import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*;public class LinuxMounts {    public static void main(String[] args) throws IOException {                String mailFrom = "[email protected]";        String mailTo = "<[email protected]>";        String mailSubject = "Testing from Java";        String mailBody = "You passed!";        String mailHost = "localhost";        printHeading();        for (FileStore store : FileSystems.getDefault().getFileStores()) {            String strPath = store.toString();            if (strPath.matches("^/(u01|backups).*$")){                long total = store.getTotalSpace() / 1024 / 1024 / 1024;                long used = (store.getTotalSpace() - store.getUnallocatedSpace()) / 1024 / 1024 / 1024;                long avail = store.getUsableSpace() / 1024 / 1024 / 1024;                float percentage = ((used * 100) / total);                System.out.format("%-50s %20d %20d %20d %20.2f %n", store, total, used, avail, percentage);            }        }                sendEmail(mailFrom, mailTo, mailSubject, mailBody, mailHost);    }        static void printHeading(){                String heading1 = "Filesystem";        String heading2 = "Total Size (MB)";        String heading3 = "Used Space (MB)";        String heading4 = "Available Space (MB)";        String heading5 = "Percentage Used (%)";        System.out.format("%-50s %20s %20s %20s %20s %n", heading1, heading2, heading3, heading4, heading5);    }        public static void sendEmail(String fromEmail, String toEmail, String subject, String body,String mailHost){        Properties properties = System.getProperties();        //Setup mail server        properties.setProperty("mail.smtp.host", mailHost);        Session session = Session.getDefaultInstance(properties);        try {            MimeMessage message = new MimeMessage(session);            message.setFrom(new InternetAddress(fromEmail));            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));            message.setSubject(subject);            message.setText(body);            // Send message            Transport.send(message);            System.out.println("Sent message successfully....");        } catch (MessagingException mex) {                mex.printStackTrace();          }    } }

The program works.  I would like to send the output of printHeading() and the mount values in the body of the email.  Eventually, I would like to add the server name and some other details to the 'Subject' line.

Any ideas how I can pass those values to the Body and Subject of the email?

Thanks,

Frank

Sankar-JV-Oracle

Best Answer

  • mNem
    mNem Member Posts: 1,380 Gold Trophy
    edited Dec 6, 2017 1:13PM Answer ✓

    Probably you want to build your body with a StringBuilder and then pass that to the sendMail() method.

    Something like this ...

    import java.io.IOException; 

        import java.nio.file.FileStore; 

        import java.nio.file.FileSystems; 

        import java.util.*; 

        import javax.mail.*; 

        import javax.mail.internet.*; 

        import javax.activation.*; 

         

        public class LinuxMounts { 

            public static void main(String[] args) throws IOException { 

                 

                String mailFrom = "[email protected]"; 

                String mailTo = "<[email protected]>"; 

                String mailSubject = "Testing from Java"; 

                String mailBody = "You passed!"; 

                String mailHost = "localhost"; 

         

                StringBuilder sbMailBody = new StringBuilder();

                sbMailBody.append(printHeading()); 

                sbMailBody.append(mailBody);

         

         

                for (FileStore store : FileSystems.getDefault().getFileStores()) { 

                    String strPath = store.toString(); 

         

                    if (strPath.matches("^/(u01|backups).*$")){ 

                        long total = store.getTotalSpace() / 1024 / 1024 / 1024; 

                        long used = (store.getTotalSpace() - store.getUnallocatedSpace()) / 1024 / 1024 / 1024; 

                        long avail = store.getUsableSpace() / 1024 / 1024 / 1024; 

                        float percentage = total == 0 ? 0 :((used * 100) / total);  //prevent divide by zero exp

                        sbMailBody.append(String.format("%-50s %20d %20d %20d %20.2f %n", store, total, used, avail, percentage)); 

                    } 

                } 

               

                System.out.println(sbMailBody.toString());

                 

                sendEmail(mailFrom, mailTo, mailSubject, sbMailBody.toString(), mailHost); 

            } 

             

            static String printHeading(){ 

                 

                String heading1 = "Filesystem"; 

                String heading2 = "Total Size (MB)"; 

                String heading3 = "Used Space (MB)"; 

                String heading4 = "Available Space (MB)"; 

                String heading5 = "Percentage Used (%)"; 

         

                String strHeading = String.format("%-50s %20s %20s %20s %20s %n", heading1, heading2, heading3, heading4, heading5); 

                return strHeading;

            } 

             

            public static void sendEmail(String fromEmail, String toEmail, String subject, String body,String mailHost){ 

         

                Properties properties = System.getProperties(); 

         

         

                //Setup mail server 

                properties.setProperty("mail.smtp.host", mailHost); 

         

         

                Session session = Session.getDefaultInstance(properties); 

         

         

                try { 

                    MimeMessage message = new MimeMessage(session); 

         

         

                    message.setFrom(new InternetAddress(fromEmail)); 

                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); 

                    message.setSubject(subject); 

                    message.setText(body); 

         

                    // Send message 

                    Transport.send(message); 

                    System.out.println("Sent message successfully...."); 

         

         

                } catch (MessagingException mex) { 

                        mex.printStackTrace(); 

                  } 

            }  

        } 

    Sankar-JV-Oracle

Answers

  • mNem
    mNem Member Posts: 1,380 Gold Trophy
    edited Dec 6, 2017 1:13PM Answer ✓

    Probably you want to build your body with a StringBuilder and then pass that to the sendMail() method.

    Something like this ...

    import java.io.IOException; 

        import java.nio.file.FileStore; 

        import java.nio.file.FileSystems; 

        import java.util.*; 

        import javax.mail.*; 

        import javax.mail.internet.*; 

        import javax.activation.*; 

         

        public class LinuxMounts { 

            public static void main(String[] args) throws IOException { 

                 

                String mailFrom = "[email protected]"; 

                String mailTo = "<[email protected]>"; 

                String mailSubject = "Testing from Java"; 

                String mailBody = "You passed!"; 

                String mailHost = "localhost"; 

         

                StringBuilder sbMailBody = new StringBuilder();

                sbMailBody.append(printHeading()); 

                sbMailBody.append(mailBody);

         

         

                for (FileStore store : FileSystems.getDefault().getFileStores()) { 

                    String strPath = store.toString(); 

         

                    if (strPath.matches("^/(u01|backups).*$")){ 

                        long total = store.getTotalSpace() / 1024 / 1024 / 1024; 

                        long used = (store.getTotalSpace() - store.getUnallocatedSpace()) / 1024 / 1024 / 1024; 

                        long avail = store.getUsableSpace() / 1024 / 1024 / 1024; 

                        float percentage = total == 0 ? 0 :((used * 100) / total);  //prevent divide by zero exp

                        sbMailBody.append(String.format("%-50s %20d %20d %20d %20.2f %n", store, total, used, avail, percentage)); 

                    } 

                } 

               

                System.out.println(sbMailBody.toString());

                 

                sendEmail(mailFrom, mailTo, mailSubject, sbMailBody.toString(), mailHost); 

            } 

             

            static String printHeading(){ 

                 

                String heading1 = "Filesystem"; 

                String heading2 = "Total Size (MB)"; 

                String heading3 = "Used Space (MB)"; 

                String heading4 = "Available Space (MB)"; 

                String heading5 = "Percentage Used (%)"; 

         

                String strHeading = String.format("%-50s %20s %20s %20s %20s %n", heading1, heading2, heading3, heading4, heading5); 

                return strHeading;

            } 

             

            public static void sendEmail(String fromEmail, String toEmail, String subject, String body,String mailHost){ 

         

                Properties properties = System.getProperties(); 

         

         

                //Setup mail server 

                properties.setProperty("mail.smtp.host", mailHost); 

         

         

                Session session = Session.getDefaultInstance(properties); 

         

         

                try { 

                    MimeMessage message = new MimeMessage(session); 

         

         

                    message.setFrom(new InternetAddress(fromEmail)); 

                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); 

                    message.setSubject(subject); 

                    message.setText(body); 

         

                    // Send message 

                    Transport.send(message); 

                    System.out.println("Sent message successfully...."); 

         

         

                } catch (MessagingException mex) { 

                        mex.printStackTrace(); 

                  } 

            }  

        } 

    Sankar-JV-Oracle
  • Unknown
    edited Dec 6, 2017 1:54PM
    1. publicstaticvoidsendEmail(StringfromEmail,StringtoEmail,Stringsubject,Stringbody,StringmailHost){
    The program works. I would like to send the output of printHeading() and the mount values in the body of the email. Eventually, I would like to add the server name and some other details to the 'Subject' line.Any ideas how I can pass those values to the Body and Subject of the email?

    Not sure what you are asking.

    See the above quote from you?

    See those 'Stringsubject' and 'Stringbody' parameters?

    Whatever you have in their is what will get used.

    So if you want headings, mount values, or anything else you need to add incorporate them into those two strings.

    Are you asking how to construct strings by concatenating other strings together?

    The Java Tutorials has dozens of trails of how to use strings and the StringBuilder class.

    https://docs.oracle.com/javase/tutorial/java/data/strings.html

  • frank.anellia
    frank.anellia Member Posts: 104
    edited Dec 6, 2017 2:07PM

    That worked!  I actually understand the coding to construct the email body.  I am receiving a "java.io.PrintStream' message in the email body:

    1. [email protected]@3957f3a4

    ...instead of the mounts output.  The header is there, just not the mounts.

    Are you able to explain what you're doing with the following expression:

    float percentage = total == 0 ? 0 : ((used * 100) / total);  //prevent divide by 0 exp

    I know the error that you're avoiding by writing this but not sure how you came about it?

    Thanks for your help, again!

  • mNem
    mNem Member Posts: 1,380 Gold Trophy
    edited Dec 6, 2017 3:18PM
    Are you able to explain what you're doing with the following expression:float percentage = total == 0 ? 0 : ((used * 100) / total);  //prevent divide by 0 exp  I know the error that you're avoiding by writing this but not sure how you came about it?

    You can think of it as the short form of ...

           
           float percentage = 0;       if (total == 0) {          percentage = 0;       } else {          percentage = ((used * 100) / total);       }      

    On my system, it produced the error. In any case, it is good to make sure the total is not zero when it is used as a denominator.

    As for the

    I am receiving a "java.io.PrintStream' message in the email body:

    what does it print to the console before invoking the sendMail() method?

                System.out.println(sbMailBody.toString());

                 

                sendEmail(mailFrom, mailTo, mailSubject, sbMailBody.toString(), mailHost); 

    I've been struggling to post this reply for about last half an hour. The reply box comes up with the spinner going forever.

  • mNem
    mNem Member Posts: 1,380 Gold Trophy
    edited Dec 6, 2017 3:45PM

    Explanation from the official documentation about ternary conditional operator

    https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

    Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

    The following program, ConditionalDemo2, tests the ?: operator:

    class ConditionalDemo2 {    public static void main(String[] args){        int value1 = 1;        int value2 = 2;        int result;        boolean someCondition = true;        result = someCondition ? value1 : value2;        System.out.println(result);    }}

    Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).

  • mNem
    mNem Member Posts: 1,380 Gold Trophy
    edited Dec 6, 2017 3:59PM

    If you haven't sorted it out yet, check this one please...

           //sbMailBody.append(System.out.format("%-50s %20d %20d %20d %20.2f %n", store, total, used, avail, percentage));
           sbMailBody.append(String.format("%-50s %20d %20d %20d %20.2f %n", store, total, used, avail, percentage));
  • frank.anellia
    frank.anellia Member Posts: 104
    edited Dec 6, 2017 7:30PM

    That was it!  Your help is greatly appreciated!  Thanks!  Also, many thanks for explaining the conditional operators.

This discussion has been closed.