Send Email from Java
Good small Java class which will send email from java.; and trying to save this content in my blog for future reference.
SendMail.java:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;{
public SendMail()
{
}
public static void main(String args[])
{
SendMail sm = new SendMail();
try
{
String smtpServer = args[0];
String sender = args[1];
String recipient = args[2];
String subject = args[3];
BufferedReader content = new BufferedReader(new InputStreamReader(new FileInputStream(args[4])));
sm.sendMail(smtpServer, sender, recipient, subject, content);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void sendMail(String smtpServer, String sender, String recipient, String subject, BufferedReader content)
{
try
{
Socket s = new Socket(smtpServer, 25);
out = new PrintWriter(s.getOutputStream());
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String hostName = InetAddress.getLocalHost().getHostName();
receive();
send("HELO " + hostName);
receive();
send("MAIL FROM: ");
receive();
send("RCPT TO: ");
receive();
send("DATA");
receive();
send("Subject: " + subject + "\n");
for(String line = content.readLine(); line != null; line = content.readLine())
send(line);
send(".");
receive();
s.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void send(String s)
throws IOException
{
System.out.println(s);
out.print(s);
out.print("\r\n");
out.flush();
}
public void receive()
throws IOException
{
String line = in.readLine();
if(line != null)
System.out.println(line);
}
private BufferedReader in;
private PrintWriter out;
}
#!/bin/sh
mail-server="bedge1-mail1.Central.XXX.COM"
TO="abc@xxx.com"
FROM="bsk@xxx.com"
SUB="Test Mail"
LOGFILE="EmailData"
$JAVA SendMail ${mail-server} $TO $FROM $SUB $LOGFILE