Skip to content

Send Email from Java

February 17, 2011

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 class SendMail
{

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

Advertisements

From → java

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: