We send simple text in email in previous post in the series. In this article, we will send rich text. For rich text, MIME type is "text/html". The actual mail content is written in HTML. While sending email, HTML contents will be set and content type is set to "text/html".
We assume that mail server is running on localhost and is connected to internet to send email.
For prerequisites please refer to my previous article on JavaMail API.
Using this example, you can send as big as HTML content you like.
We assume that mail server is running on localhost and is connected to internet to send email.
For prerequisites please refer to my previous article on JavaMail API.
Using this example, you can send as big as HTML content you like.
// File Name SendHTMLEmail.javaCompile and run this program to send an HTML email:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendHTMLEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com";
// Sender's email ID needs to be mentioned
String from = "web@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Send the actual HTML message, as big as you like
message.setContent("<h1>This is actual message</h1>", "text/html" );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
$ java SendHTMLEmail
Sent message successfully....
No comments:
Post a Comment