Discussions
Categories
- 196.9K All Categories
- 2.2K Data
- 240 Big Data Appliance
- 1.9K Data Science
- 450.4K Databases
- 221.7K General Database Discussions
- 3.8K Java and JavaScript in the Database
- 31 Multilingual Engine
- 550 MySQL Community Space
- 478 NoSQL Database
- 7.9K Oracle Database Express Edition (XE)
- 3K ORDS, SODA & JSON in the Database
- 546 SQLcl
- 4K SQL Developer Data Modeler
- 187.1K SQL & PL/SQL
- 21.3K SQL Developer
- 295.9K Development
- 17 Developer Projects
- 138 Programming Languages
- 292.6K Development Tools
- 107 DevOps
- 3.1K QA/Testing
- 646K Java
- 28 Java Learning Subscription
- 37K Database Connectivity
- 155 Java Community Process
- 105 Java 25
- 22.1K Java APIs
- 138.1K Java Development Tools
- 165.3K Java EE (Java Enterprise Edition)
- 18 Java Essentials
- 160 Java 8 Questions
- 86K Java Programming
- 80 Java Puzzle Ball
- 65.1K New To Java
- 1.7K Training / Learning / Certification
- 13.8K Java HotSpot Virtual Machine
- 94.3K Java SE
- 13.8K Java Security
- 204 Java User Groups
- 24 JavaScript - Nashorn
- Programs
- 443 LiveLabs
- 38 Workshops
- 10.2K Software
- 6.7K Berkeley DB Family
- 3.5K JHeadstart
- 5.7K Other Languages
- 2.3K Chinese
- 171 Deutsche Oracle Community
- 1.1K Español
- 1.9K Japanese
- 232 Portuguese
Java - Add Email Subject and Body

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
Best 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();
}
}
}
Answers
-
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();
}
}
}
-
- 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
-
That worked! I actually understand the coding to construct the email body. I am receiving a "java.io.PrintStream' message in the email body:
...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!
-
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 ...
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.
-
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 anif-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: "IfsomeCondition
istrue
, assign the value ofvalue1
toresult
. Otherwise, assign the value ofvalue2
toresult
."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 anif-then-else
statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments). -
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)); -
That was it! Your help is greatly appreciated! Thanks! Also, many thanks for explaining the conditional operators.