Send Simple HTML email with JavaMail


Send Simple HTML email with JavaMail

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications.

This one is the simple program which can be used to send email with JAVA.

import javax.mail.*;
import javax.mail.internet.*;

import java.util.Properties;

class SimpleHTMLMail {
public static void main(String[] args) throws Exception{
System.out.println("Sending mail…");
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.mymailserver.com");
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");

Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML mail with images");
message.setFrom(new InternetAddress("you@domain.com"));
message.setContent("<h1>This is a test</h1>"
+ "<img src=\"http://www.domain.com/image.gif\">",
"text/html");
message.addRecipient(Message.RecipientType.TO,new InternetAddress("receive@domain.com"));

transport.connect();
transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}

Related Posts: