Send mail in Java
Simple Java program to send mail.
Check for libraries at the end of this article.
import java.util.Properties; import javax.mail.Session; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.Transport; public class TestMail { public static void main(String[] args) { String from = "from@example.com"; String recipients = "to@example.com"; String subject = "My subject"; String message = "My body message<br />" + "<b>this is bold</b>"; //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", "smtp.example.com"); // create some properties and get the default Session Session session = Session.getDefaultInstance (props, null); session.setDebug(false); // create a message Message msg = new MimeMessage(session); try { // set the from address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); // set the to address InternetAddress addressTo = new InternetAddress(recipients); msg.setRecipient(Message.RecipientType.TO, addressTo); // put custom headers here (optional) msg.addHeader("myHeader", "myHeader Message"); // Setting the Subject and Content Type ((MimeMessage)msg).setSubject(subject, "iso-8859-1"); msg.setContent(message, "text/html; charset=\"ISO-8859-1\""); // send message Transport.send(msg); System.out.println("Done"); } catch(Exception e) { System.out.println("Excepcao: " + e.getMessage()); } } }
Compile & Run
To compile use: javac -cp mail.jar TestMail.java
To run use (unix like OS): java -cp .:mail.jar:activation.jar TestMail
To run use (windows): java -cp .;mail.jar;activation.jar TestMail
FILES
JavaMail API home:
http://java.sun.com/products/javamail/
JavaMail download page:
http://java.sun.com/products/javamail/downloads/index.html
or local files:
mail.jar
activation.jar
by LSimpson
Loading ...