Send a simple SMTP email message with java

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

Your email address will not be published.