Skip to content

aviyehuda.com

Menu
  • Open Source
  • Android
  • Java
  • Others
  • Contact Me
  • About Me
Menu

Send a simple SMTP email message with java

Posted on 05/12/2009

The next code will show you the simplest way to send an email in java.
The only thing you need is an email address and the smtp host address of your email supplier.

	public void sendSimpleMail() {
		try{
			String host = "<ENTER_SMTP_HOST>";
			String from = "Avi";
			String to = "aviyehuda@gmail.com";
			String body = "This is the message body.";
			String subject = "This is the message subject."; 
	
			Properties props = System.getProperties();
			props.put("mail.smtp.host", host);
			Session session = Session.getDefaultInstance(props, null);
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));
			message.addRecipient(Message.RecipientType.TO, 
			  new InternetAddress(to));
			message.setSubject(subject);
			message.setText(body);
	
			Transport.send(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
}

This code can only send a simple formatted text, without HTML or attachments. In the future I will show how to do those as well.

You will also need the mail.jar that can be found here.
Unless you are using Java 6 you will also need the activation.jar which can be found here.

downloaddownload source

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *


About Me

REFCARD – Code Gems for Android Developers

Categories

  • Android
  • AWS
  • AWS EMR
  • bluetooth
  • Chrome extension
  • ClientSide
  • Clover
  • Coding Coventions
  • Data Lake
  • General
  • GreaseMonkey
  • Hacks
  • hibernate
  • hibernate validator
  • HTML5
  • HtmlUnit
  • Image Manipulation
  • Java
  • Java Technologies
  • JavaScript
  • Java_Mail
  • JEE/Network
  • Job searching
  • Open Source
  • Pivot
  • projects
  • Pure Java
  • software
  • Spark
  • Trivia
  • Web development

Archives

  • March 2022 (1)
  • January 2022 (1)
  • January 2021 (1)
  • December 2018 (1)
  • August 2018 (1)
  • October 2013 (1)
  • March 2013 (1)
  • January 2013 (2)
  • July 2012 (1)
  • April 2012 (1)
  • March 2012 (1)
  • December 2011 (1)
  • July 2011 (1)
  • June 2011 (1)
  • May 2011 (2)
  • January 2011 (1)
  • December 2010 (1)
  • November 2010 (3)
  • October 2010 (4)
  • July 2010 (1)
  • April 2010 (2)
  • March 2010 (1)
  • February 2010 (2)
  • January 2010 (5)
  • December 2009 (10)
  • September 2009 (1)
 RSS Feed
6dc4b508c301309b9e838ba10393207a-332
©2023 aviyehuda.com | Design: Newspaperly WordPress Theme