aspose file tools*
The moose likes Servlets and the fly likes how can i send mail with JAVAMAIL API through intranet. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "how can i send mail with JAVAMAIL API through intranet." Watch "how can i send mail with JAVAMAIL API through intranet." New topic
Author

how can i send mail with JAVAMAIL API through intranet.

Amit Punjwani
Ranch Hand

Joined: Jul 10, 2000
Posts: 50
how can i send mail with JAVAMAIL API through intranet.
I have written program in JSP to send mails with JAVAMAIL API , This application works fine when i use on my personal PC at my home, but when i am using this application in intranet of my company then its giving Exception ( Send Mail Exception). Our company uses a proxy server as the default gateway. I think the problem is with security permissions. Kindly help me in solving this problem.
Thanx in adv
Amit
nagendra barla
Greenhorn

Joined: Aug 17, 2001
Posts: 4
I got stucked with the same problem.if u got solution please mail to npbarla@yahoo.com
mrsmithq
Greenhorn

Joined: Aug 17, 2001
Posts: 8
Try messign around with this. It works through a proxy but get rid of the extra code
/****************************************************************************/
/*program name:SendMessage.java*/
/*authorominic Cara*/
/*date began:07/17/2001*/
/*system:GSP Dispatch */
/**/
/*Modification History*/
/**/
/*DateInitialsReason*/
/*--------------------------------------------------*/
/**/
/**/
/**/
/**/
/****************************************************************************/
import java.io.*;
import java.net.InetAddress;
import javax.mail.*;
import javax.mail.internet.*;
import java.lang.*;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.sql.*;
// import java.sql.Date;
import java.io.UnsupportedEncodingException;

public class SendMessage

{
public static String ProcessName = "SendMessageProcess";
public static Connection databaseCon;
public static int databaseState = 0;
public static int rCount = 0;
public static Statement databaseStmt;
public static int lastDatabaseErrorNumber;
public static String lastDatabaseErrorMessage;
public static ResultSet resultSet1;
public static ResultSetMetaData resultSetMetaData;
public static int columnCount;
public static int rowCount;
public static Applog applog;// applog is an instance of class Applog.
// It records program activity.

// main program entry point

public static void main(String[] argv)

{
StringdatabaseConnection = null,// String Declarations
databaseUser = null,
databasePassword = null,
to= null,
from= null,
cc = null,
bcc = null,
url = null,
protocol = null,
host = null,
user = null,
password = null,
messageType= null,
messageFormat= null,
timeCreated= null,
timeSent= null,
timeModified= null,
//messageText= null,
optionalMessage= null,
mailHost = null,
record = null, // name of folder in which to record mail
logfilename= null,
mlvar = null;
String mailer = "SendMessage",
sendStatus= "Y";
int dbStatus= 0;

// showProcessName();

boolean debug = false;
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));

System.out.println("parsing XML file "+argv[0]);
try
{
Hashtable cfg = new Hashtable();

ParseXML parseInput = new ParseXML(false);
cfg = parseInput.parseXmlFile(argv[0], false);
System.out.println("successfully parsed config file "+ argv[0] );

// this is an example of asking the parser for a specific variable

// Now get the connection string DSN, user name,
// and password for use when opening database

// get the name of the Database connection from the config file
databaseConnection = (String) cfg.get("DatabaseConnection");
if (databaseConnection == null)
{
System.out.println("ERROR - variable 'DatabaseConnection' "
+ "is not in config file");
databaseConnection = "jdbc:mysql://127.0.0.1:3306/GSP_TEST";
}
else
{
System.out.println("variable DatabaseConnection equals "
+ databaseConnection);
}

// get the database user name from the config file
databaseUser = (String) cfg.get("DatabaseUser");
if (databaseUser == null )
{
System.out.println("ERROR - 'variable DatabaseUser' "
+ "is not in config file");
databaseUser = "root";
}
else
{
System.out.println("variable DatabaseUser equals "
+ databaseUser);
}

// get the database user's password from the config file
databasePassword = (String) cfg.get("DatabasePassword");
if (databasePassword == null )
{
System.out.println("ERROR - variable 'DatabasePassword'"
+ " in config file is blank");
databasePassword = "";
}
else
{
System.out.println("variable DatabasePassword equals "
+ databasePassword);
}

// get MessageType from config file
messageType = (String) cfg.get("MessageType");
if (messageType == null )
{
System.out.println("ERROR - 'MessageType'"
+ " is not in config file");
messageType = "P";
}
else
{
System.out.println("variable MessageType equals "
+ messageType);
}

// get MessageFormat from config file
messageFormat = (String) cfg.get("MessageFormat");
if (messageFormat == null )
{
System.out.println("ERROR - 'MessageFormat'"
+ " is not in config file");
messageFormat = "email";
}
else
{
System.out.println("variable MessageFormat equals "
+ messageFormat);
}

// get To_Receiver from config file
to = (String) cfg.get("To_Receiver");
if (to == null )
{
System.out.println("ERROR - 'To_Receiver'"
+ " is not in config file");
to = "dcara@riddler.gsptech.fedex.com";
}
else
{
System.out.println("variable To_Receiver equals "
+ to);
}

// get From_Sender from config file
from = (String) cfg.get("From_Sender");
if (from == null )
{
System.out.println("ERROR - 'From_Sender'"
+ " is not in config file");
from = "shipalert@gsptech.fedex.com";
}
else
{
System.out.println("variable From_Sender equals "
+ from);
}

// get MailHost from config file
mailHost = (String) cfg.get("MailHost");
if (mailHost == null )
{
System.out.println("ERROR - 'MailHost'"
+ " is not in config file");
mailHost = "riddler.gsptech.fedex.com";
}
else
{
System.out.println("variable MailHost equals "
+ mailHost);
}

// get Protocol from config file
protocol = (String) cfg.get("Protocol");
if (protocol == null )
{
protocol = "pop3";
System.out.println("ERROR - 'Protocol'"
+ " is not in config file");
}
else
{
System.out.println("variable Protocol equals "
+ protocol);
}

// get Host from config file
host = (String) cfg.get("Host");
if (host == null )
{
System.out.println("ERROR - 'Host'"
+ " is not in config file");
host = "riddler.gsptech.fedex.com";
}
else
{
System.out.println("variable Host equals "
+ host);
}

// get User from config file
user = (String) cfg.get("User");
if (user == null )
{
System.out.println("ERROR - 'User'"
+ " is not in config file");
user = "dcara";
}
else
{
System.out.println("variable User equals "
+ user);
}

// get Password from config file
password = (String) cfg.get("Password");
if (password == null )
{
System.out.println("ERROR - 'Password'"
+ " is not in config file");
password = "";
}
else
{
System.out.println("variable Password equals "
+ password);
}

// get Record from config file
record = (String) cfg.get("Record");
if (record == null )
{
System.out.println("ERROR - 'Record'"
+ " is not in config file");
record = "sent";
}
else
{
System.out.println("variable Record equals "
+ record);
}

// get optionalMessage from config file
optionalMessage = (String) cfg.get("OptionalMessage");
if (optionalMessage == null )
{
System.out.println("ERROR - 'OptionalMessage'"
+ " is not in config file");
optionalMessage = "'OptionalMessage' is not in config file. "
+ "This is a hard-coded message from Class SendMessage.";
}
else
{
System.out.println("variable OptionalMessage equals "
+ optionalMessage);
}

// get the name of the log file to write to,
// then open and initialize
logfilename = (String) cfg.get("LogFileName");

if (logfilename == null)
{
System.out.println("ERROR - 'LogFileName'"
+ " is not in config file");
logfilename = "C:/SendMessage/Applog/SendMessage.log";
}
else
{
System.out.println("variable LogFileName equals "
+logfilename);
}

// get the maxLevel variable from the config file
mlvar = (String) cfg.get("MaxLevel");
int maxLevel = 5;// default maxLevel
if ( mlvar == null )
{
System.out.println("ERROR - 'MaxLevel'"
+ " is not in config file");
mlvar = "5";
maxLevel = Integer.parseInt(mlvar);
}
else
{
System.out.println("variable maxLevel equals "
+mlvar);
maxLevel = Integer.parseInt(mlvar);
}

//now create the log file
applog = new Applog(logfilename);
applog.setMaxLevel(maxLevel);
applog.setLogCCYY();
applog.log(ProcessName ,"Beginning program",2);

} // end try statement and assignment of config variables


catch (Exception e)

{
// System.out.println("exception when reading XML file "+argv[0]);
e.printStackTrace(System.err);
}

System.out.println("\nNow sending message");

try
{
System.out.println("To: " + to);
Properties props = System.getProperties();
// XXX - could use Session.getTransport() and Transport.connect()
// XXX - assume we're using SMTP

if (mailHost != null)
{
props.put("mail.smtp.host", mailHost);
}

// Get a Session object
Session session = Session.getDefaultInstance(props, null);

if (debug)
{
session.setDebug(true);
}

// construct the message
Message msg = new MimeMessage(session);

if (from != null)
{
msg.setFrom(new InternetAddress(from));
}
else
{
msg.setFrom();
}

msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));

if (cc != null)
{
msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(cc, false));
}

if (bcc != null)
{msg.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(bcc, false));
}

msg.setText(optionalMessage);

msg.setHeader("X-Mailer", mailer);
msg.setSentDate(new Date());

// send the thing off
Transport.send(msg);

System.out.println("Mail was sent successfully.\n");
}


catch (Exception e)

{
e.printStackTrace();
}





// create a calendar instance and get the current date/time
GregorianCalendar clToday = new GregorianCalendar();
System.out.println("Date/Time: " +clToday.getTime());
String now = null;
now = formatDate(clToday);

// create a hashtable for database fields and their
// corresponding data, then load the hashtable
// with the fields and data
Hashtable sqlValues = new Hashtable();
sqlValues.clear();
sqlValues.put("message_type", messageType);
sqlValues.put("message_format", messageFormat);
sqlValues.put("from_sender", from);
sqlValues.put("to_receiver", to);
sqlValues.put("optional_message", optionalMessage);
sqlValues.put("date_created", now);
sqlValues.put("date_sent", now);
sqlValues.put("date_modified", now);
sqlValues.put("send_status", sendStatus);

// now create a SQL statement
String SqlStatement = "INSERT INTO gsp_shipalert (";

// read the hashtable to find the enumerated entries in the table
Enumeration paramaters = sqlValues.keys();
String field = null;
String data= null;

while (paramaters.hasMoreElements())
{
field= (String)paramaters.nextElement();
data = (String)sqlValues.get(field);

// append the SQL statement with the fields from the hashtable
SqlStatement = SqlStatement + field;
System.out.println("SQL: "+SqlStatement);
if (paramaters.hasMoreElements())
{ SqlStatement = SqlStatement + ", "; }
}

// append SQL statement with VALUES clause
SqlStatement = SqlStatement + ") VALUES (";
System.out.println("SQL: "+SqlStatement);

Enumeration moreParameters = sqlValues.keys();
// reset Strings
field = null;
data = null;

while (moreParameters.hasMoreElements())
{
field = (String)moreParameters.nextElement();
data = (String) sqlValues.get(field);

// append the SQL statement with data from the hashtable
SqlStatement = SqlStatement +"'"+ data+"'";
System.out.println("SQL: "+SqlStatement);
if (moreParameters.hasMoreElements())
{ SqlStatement = SqlStatement + ", "; }
}

SqlStatement = SqlStatement + ")";
System.out.println("SQL: "+SqlStatement);

/************************************************************/
/*SQL statement now has the following format:*/
/**/
/*INSERT INTO gsp_shipalert (field1, field2,...fieldn)*/
/*VALUES (data1, data2,...datan);*/
/************************************************************/

System.out.println("Will execute statement " + SqlStatement);

try
{
// open the database for writing when inserting records
dbStatus = openDatabase(databaseConnection, databaseUser,
databasePassword);
if (dbStatus != 0)
{
System.out.println("ERROR - Database open Error "
+ dbStatus);
applog.log(ProcessName, "ERROR - Database open Error "
+ dbStatus, 2);
// System.exit(0);
}
}

catch (Exception e)

{
// System.out.println("exception when opening database " + );
e.printStackTrace(System.err);
}

// execute the sql statement
dbStatus = executeDatabaseOperation(SqlStatement);

try
{
// close the database
dbStatus = closeDatabase();
if (dbStatus != 0)
{
System.out.println("ERROR - Database Close Error "
+ dbStatus);
applog.log(ProcessName, "ERROR - Database Close Error "
+ dbStatus, 2);
System.exit(0);
}
}

catch (Exception e)

{
// System.out.println("exception when opening database " +);
e.printStackTrace(System.err);
}

if (dbStatus != 0)
{
System.out.println("Database Insert Error "+dbStatus);
System.out.println("Database Insert Error Message: "
+ getlastDatabaseErrorMessage());
}
}

// create a date string in the form of
// 'YYYY-MM-DD HH:MM:SS' from the system date

public static String formatDate(GregorianCalendar TodaysDate)

{
int year, month, day, hour, minute, second;

//assign
DecimalFormat df = null;
String formattedDate = null;
year= TodaysDate.get(Calendar.YEAR);
month= TodaysDate.get(Calendar.MONTH);
// For some reason month is one less than the actual month**
System.out.println("Month = " + month);
day= TodaysDate.get(Calendar.DAY_OF_MONTH);
hour= TodaysDate.get(Calendar.HOUR_OF_DAY);
minute= TodaysDate.get(Calendar.MINUTE);
second = TodaysDate.get(Calendar.SECOND);

// format date and time as 'YYYY-MM-DD HH:MM:SS' from the system date
df = new DecimalFormat("0000");// to convert year to four digits
formattedDate = df.format(year);// YYYY
df = new DecimalFormat("00");
formattedDate += "-";// YYYY-
//** so here we are correctingfor the discrepancy
formattedDate += df.format(month+1);// YYYY-MM
formattedDate += "-";// YYYY-MM-
formattedDate += df.format(day);// YYYY-MM-DD
formattedDate += " ";// YYYY-MM-DD
formattedDate += df.format(hour);// YYYY-MM-DD HH
formattedDate += ":";// YYYY-MM-DD HH:
formattedDate += df.format(minute);// YYYY-MM-DD HH:MM
formattedDate += ":";// YYYY-MM-DD HH:MM:
formattedDate += df.format(second);// YYYY-MM-DD HH:MM:SS

return formattedDate;
} // end function formatDate


public static int openDatabase(String connectionName,
String connectionUser, String connectionPassword)

{
int returnError = 0;

setlastDatabaseErrorNumber(0);
setlastDatabaseErrorMessage("");

try
{
// The newInstance() call is a work around for some
// broken Java implementations

// load the mySQL driver
Class.forName("org.gjt.mm.mysql.Driver").newInstance();

try
{
// establish a connection by having the appropriate
// driver connect to the DBMS
databaseCon = DriverManager.getConnection(connectionName
+ "?user="+ connectionUser
+ "&password="+ connectionPassword);
System.out.println("Database is open");
applog.log(ProcessName, "Opened Database" ,2); //**
databaseState = 1;
}

catch (SQLException E)

{
setlastDatabaseErrorMessage(E.getMessage());
// out.println("SQLState: " + E.getSQLState());
setlastDatabaseErrorNumber(E.getErrorCode());
returnError = -2;
}
} // end outer try block


catch (Exception E)

{
// out.println("Unable to load driver.");
// E.printStackTrace();
returnError = -1;
}

return returnError;
} // end openDatabase(String connectionName )

// closeDatabase method

public static int closeDatabase()

{
int returnError = 0;
if ( databaseState != 0 )
{
if ( databaseState == 2 )
{
try
{databaseStmt.close();}

catch (SQLException E)

{returnError = -2;}
}
try
{
databaseCon.close();
applog.log(ProcessName, "Database Closed",2);
System.out.println("Database has been closed");
}

catch (SQLException E)

{
setlastDatabaseErrorMessage( E.getMessage());
setlastDatabaseErrorNumber( E.getErrorCode());
returnError = -2;
}
databaseState = 0;
}

else
{returnError = -1;}

return returnError;
} // closeDatabase()



public static int executeDatabaseOperation(String sqlStatement)

{
int returnError = 0;
if (databaseState != 0)// databaseState != 1
{
try
{
// Use connection we've already created
if (databaseState == 2)
{
databaseStmt.close();
}


databaseStmt = databaseCon.createStatement();

resultSet1 = databaseStmt.executeQuery(sqlStatement);
System.out.println("SQL statement has been executed");
applog.log(ProcessName, "Executing SQL statement "
+ sqlStatement, 5);
databaseState = 2;

if (resultSet1 == null)
{
returnError = -3;
setlastDatabaseErrorNumber(-5);
setlastDatabaseErrorMessage("Query resulted in NULL Object");
}
}


catch (SQLException E)

{
setlastDatabaseErrorMessage(E.getMessage());
// out.println("SQLState: " + E.getSQLState());
setlastDatabaseErrorNumber(E.getErrorCode());
returnError = -1;
}
}
return returnError;
} // executeDatabaseOperation(String sqlStatement )


public static void setlastDatabaseErrorNumber( int ernum )

{lastDatabaseErrorNumber = ernum;}


public static void setlastDatabaseErrorMessage( String ermsg )

{lastDatabaseErrorMessage = ermsg;}


public static int getlastDatabaseErrorNumber()

{
return lastDatabaseErrorNumber;}


public static String getlastDatabaseErrorMessage()

{
return lastDatabaseErrorMessage;}

/*
public static void showProcessName()
{System.out.println("Process Name is " + ProcessName);}
*/
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how can i send mail with JAVAMAIL API through intranet.