All Things Techie With Huge, Unstructured, Intuitive Leaps

Linux Sendmail Not Working

It's real easy to send email using a linux server.  We have an app where we need to send notification details to our users so we send it via the linux server that is already running Apache Tomcat.

Since the details and notifications go beyond the simple, we use java to write the details to a temp file, get the email address from the database, invoke a bash shell to send the mail and then delete the temp file.

Here is how its done.



String messbody = (new StringBuilder(String.valueOf(messbody)))
.append("Please log into www.mydomain.com to see the latest things on your account.").toString();

Then I generate a random file name by assembling a bunch of random characters:

int rancharacter = 65 + (int) (Math.random() * 90);

char ck = (char) rancharacter; 
String fnum = String.valueOf(ck); 

I did the rancharacter many times to generate a random string.  I created a linux directory where this would be written to.  It is in /home/messages.



String longfileName = "/home/messages/" + fnum; 
 File f = new File(longfileName); 
 try {
 BufferedWriter bout = new BufferedWriter( new FileWriter(longfileName)); 
 bout.write(messbody);
 bout.close(); 
 } catch (IOException e)
 { System.out
 .println("Writing email file exception");
 System.out.println("Exception " + e.getMessage()); }

Now that I have a file, I wrote a very little bash script called mailer, put it in the /bin directory and did a chmod so that it could be executed.  The bash script looks like this:


#!/bin/bash
IFS=":-;"
#FILE= "/home/messages/$3"
#echo $(basename "$2")
mail -s $(basename "$2") $(basename "$1") < /home/messages/$(basename "$3")


The only thing life to do, is to create a subject, get the email, get the runtime so that one can execute a linux command, and send the email.

Here's some code:

String emailAddress = email;   //previous declared variable that went to the database
 String subject = "Account_Notification";  //I had to put the underscore to eliminate space problems
 String messBody = fileName; 
 String cmd = "mailer" + " " + emailAddress
 + "  " + subject + " " + longfileName; 
  // get the linux runtime to execute the command
 try { Runtime run
 = Runtime.getRuntime(); Process pr = run.exec(cmd);
 pr.waitFor(); BufferedReader buf = new
 BufferedReader( new InputStreamReader(
 pr.getInputStream()));
 
 } catch (Exception fu) {
 
 System.out.print(fu.getMessage()); } 
 boolean success = f.delete();

OK - all of this was working.  Then I changed the message body and it stopped working.  What caused it to stop working.  In the body of the message, I put java.util.Date.toString();

That would stop Centos linux from mailing.  Weird.  I hope that this helps someone.



No comments:

Post a Comment