Sending an HTML Mail using Java is as simple as sending a normal text mail as discussed in our previous blog post.
There are simple changes for sending HTML Mails.
public void setContent(Object o, String type)
This method is required to be called instead of setText(String text)
Let us check the following example.
Sending a text mail using Java
There are simple changes for sending HTML Mails.
public void setContent(Object o, String type)
This method is required to be called instead of setText(String text)
Let us check the following example.
import javax.mail.*; import javax.mail.internet.*; import java.util.*; public class SendHTMLMail { String myEmail,myPassword; SendHTMLMail() { String body ="<html><body><center>Welcome to Java with Z <hr />hello World </center></body></html>"; myEmail = "youremail@gmail.com"; myPassword="yourpassword"; String host="smtp.gmail.com"; String port="465"; String recAdd="somene@gmail.com"; Properties prop = new Properties(); prop.put("mail.smtp.auth","true"); prop.put("mail.smtp.socketFactory.port",port); prop.put("mail.smtp.starttls.enable","true"); prop.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); prop.put("mail.smtp.socketFactory.fallback","false"); prop.put("mail.smtp.host",host); SecurityManager manager=System.getSecurityManager(); try { Authenticator auth= new SMTPAuthenticator(); System.out.println("Authenticated"); Session session =Session.getDefaultInstance(prop,auth); System.out.println("Session Acquired"); MimeMessage msg = new MimeMessage(session); msg.setSubject("My HTML Mail"); msg.setContent(body,"text/html"); msg.setFrom(new InternetAddress(myEmail)) msg.setRecipient(Message.RecipientType.TO,new InternetAddress(recAdd)); System.out.println("Message ready "); Transport.send(msg); System.out.println("Mail Sent"); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new SendHTMLMail(); } private class SMTPAuthenticator extends Authenticator { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(myEmail,myPassword); } } }
0 comments:
Post a Comment