Example of a SMTP call using a java program on linux

Hi All,

I'd like to write a java program that makes an SMTP connection to an email server & then send a test email eg "hello world" to a specified address.

Is there any example showing how this works?


is the API, I'd like to use.

Who is Participating?
mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
Here is the basic idea...
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 TestSendingEmail
   public static void main(String [] args)
      String to = "you@yahoo.com";
      String from = "me@gmail.com";
      String smtpHost = "smtp.host.com";

      Properties properties = System.getProperties();
      properties.setProperty("mail.smtp.host", smtpHost);
      Session session = Session.getDefaultInstance(properties);

      try {
         MimeMessage message = new MimeMessage(session);

         message.setFrom(new InternetAddress(from));
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

         message.setSubject("An email from me to you");

         message.setText("Hello World!!");

      } catch (MessagingException ex) {

Open in new window

For this you will need to have the following ...

Javamail - http://www.oracle.com/technetwork/java/javamail/index.html
JavaBeans Activation Framework - http://www.oracle.com/technetwork/java/javase/downloads/index-135046.html
Mahesh BhutkarCommented:
Your smtp server must be up & running with proper configuration to support above code.
CEHJConnect With a Mentor Commented:
Most smtp servers will expect authentication of some kind. Here's an example of one of the most demanding:

Mahesh BhutkarCommented:
Is this problem resolved?
eeclintAuthor Commented:
Sorry for the delay as I didn't see the solutions.

I will attempt to run this code in my box & ask further questions in a new thread if required.

Thanks for your help.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.