Java Mail : SMTP server to send mail with Java and gmail

You need to have SMTP Server listening on port : 25.

To check if you have the service on a windows machine. Use the command
C:\>telnet localhost 25

If you received a message such as
"Connecting To locahost...Could not open connection to the host, on port 25: Connect failed"

we might install an email server such as :
Mercury email server(also comes with WAMMP)
http://www.pmail.com/overviews/ovw_mercury.htm
Apache James
http://james.apache.org/

Sample Program to Test:

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;



public class EMail {

public static void main(String[] args) {
// TODO Auto-generated method stub
String to="to_uname@gmail.com";
String from="from_uname@gmail.com";

String host="localhost";

Properties props=System.getProperties();

props.setProperty("mail.smtp.host", host);
props.setProperty("mail.user", "unaem");
props.setProperty("mail.password", "password");
Session session=Session.getDefaultInstance(props);

try
{
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Java Mail - Test");
message.setText("Hi User,/n/nThis is a sample message/n/nRegards, Sent User");

Transport.send(message);
}
catch(MessagingException mex)
{
mex.printStackTrace();
}

}


}

Source: http://stackoverflow.com/questions/18781556/send-a-mail-with-java-and-gmail

Analytics