codescracker


java

Java Send Email



« Previous Tutorial Next Tutorial »


You are free to send e-mail using your Java program. Before start with sending email in Java, make sure that JavaMail API and Java Activation Framework (JAF) is installed on your platform properly

Java Send Email Example

Here is an example, sends simple email in Java. This is JavaSimpleEmail.java file:

/* Java Program Example - Java Sending Email

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class JavaSimpleEmail
{
	public static void main(String [] args)
	{    
		String to = "abcd@gmail.com";
		String from = "web@gmail.com";
		String host = "localhost";
		
		Properties properties = System.getProperties();
		properties.setProperty("mail.smtp.host", host);
		Session session = Session.getDefaultInstance(properties);
	
		try
		{
			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(from));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			msg.setSubject("This is the Subject Line");
			msg.setText("This is the actual message");
			Transport.send(msg);
			System.out.println("Message sent successfully....");
		}	
		catch(MessagingException mex)
		{
			mex.printStackTrace();
		}
	}
}

Now compile and run this program to send a simple e-mail:

$ java JavaSimpleEmail
Message sent successfully....

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test