Skip to main content

Java Mail API

Java Mail API:
-->DB software manages the data in the form of DB table cols
-->WebServer manages and executes web application
-->JNDI Registry manages objects
-->Similarly mail server manages and executes Email Accounts and Email Messages
       Java App---(jdbc api(java.sql.javax.sql,...))---->DW Software

       Java App---(jndi api(javax.naming and its sub packages))--->JNDI registry
            E.g:- rmi registry, Cos registry...

       Java App--(java mail api(javax.mail,javax.activation ))-->Mail Server
           E.g:- james server, Lotus Notes, Microsoft exchange server

Mail Server Architecture:-



1.)SMTP=Simple Mail Transfer Protocol
2.)POP=Post Office Protocol
3.)IMAP=Internet Mail Access Protocol

-->Incoming server receives and manages email messages in the email accounts
-->Outgoing server sends the email messages from one account to another account
-->The pop3 enabled mail server sends the email messages to mail client permanently, so there onwards maintaing email messages is the responsibility of mail client
-->The IMAP enabled mail server maintains the email message even after  it is ready by mail client



Gmail MailServers Outgoing Server Details:-
Host name: smtp.gmail.com
Port no: 465
-->when startls is enabled the port no: 587

Incoming server Details:-
Host name: pop.gmail.com
Port no: 995

Possible Email Operations:-
1.)Send mail
2.)Send mail with attachment
3.)Read Mail
4.)Delete Mail

To establish the connection to outgoing server of gmail
Steps:-
  1. //prepare mail properties
  2. Properties props=new Properties();
  3.  props.put("mail.smtp.host", "smtp.gmail.com");
  4.  props.put("mail.smtp.port", "465");   
  5.  props.put("mail.smtp.auth","true");
  6.  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  7. //create session object representing connection with outgoing server
  8. Session session=Session.getInstance(props,auth(object of class extends Authenticator );
  9. private class MyAuthenticator extends Authenticator
  10. {
  11. public static PasswordAuthentication getPasswordAuthentication() {
  12. return MyAuthenticator auth=new MyAuthenticator();
  13. }   
-->java mail api comes in the form of javax.mail<ver>.jar(collect it from mvn repository.com)
-->To establish connection with incoming serverof gmail, we can use the above code but in the mail property names replacesmtp with pop3 and use the following host, port details
Host name:  pop3.gmail.com
Port no: 995

ConnTest:
  1. package com.nt.mail;

  2. import java.util.properties;
  3. import javax.mail.Session;

  4. public class ConnTest{
  5.  public static void main(String... args) throws Exception{
  6.         //Prepare Mail Properties
  7.            Properties props=new Properties();
  8.            props.put("mail.transport.protocol","smtp");
  9.            props.put("mail.smtp.host","localhost");
  10.            props.put("mail.smtp.port","25");

  11.        //Get Session Object
  12.          Session ses=Session.getInstance(props);
  13.          if(ses==null)
  14.                System.out.println("Connection not established");
  15.          else
  16.                System.out.println("Connection established");
  17.       }
  18. }

Procedure to send Email Message:-
1.)Prepare mail properties
2.)Prepare Authenticator object
3.)Create session object having main properties, authenticator object (Establish the connection without going server to gmail mail server)
4.)Prepare Email message having header, body values
5.)Send Email Messages

SendMailTest:

  1. package com.nt.mail;

  2. import java.util.Date;
  3. import java.util.Properties;
  4. import javax.mail.Session;
  5. import javax.mail.Transport;
  6. import javax.mail.internet.InternetAddress;
  7. import javax.mail.internet.MimeMessage;
  8. import javax.mail.internet.MimeMessage.RecipientType;

  9. public class SendMail {
  10.   public static void main(String[] args) throws Exception{
  11. Properties props=new Properties();
  12. props.put("mail.transport.protocol","smtp");
  13. props.put("mail.smtp.host","localhost");
  14. props.put("mail.smtp.port","25");

  15. //get Session obj
  16. Session ses=Session.getInstance(props);

  17. //Create Email Message
  18. MimeMessage message=new MimeMessage(ses);
  19. message.setFrom(new InternetAddress("kalam1"));
  20. message.setRecipient(RecipientType.TO,new InternetAddress("modi1"));
  21. message.setSubject("open it to know it");
  22. message.setSentDate(new Date());
  23. message.setText("Mr.Modi Do not declare holiday on the day of my death, Instead make people to work an extra day");

  24. //send message
  25. Transport.send(message);
  26. System.out.println("Mail has been delivered");
  27.   }

  28. }

Sending Email Message with Attachment:-
(1),(2),(3) same as above
(4)Prepare Email message just having header values
(5)Prepare body of type Multipart
(6)Prepare body parts(like text, attachment and etc...)
(7)Add Body part2 to body
(8)Set body as the Message content
(9)Send message

SendMailAttachment:
  1. package com.nt.mail;
  2. /*
  3.    Java Application to send an E-mail with attachment
  4. */
  5. import java.util.Date;
  6. import java.util.Properties;
  7. import javax.activation.DataHandler;
  8. import javax.activation.FileDataSource;
  9. import javax.mail.Message;
  10. import javax.mail.Message.RecipientType;
  11. import javax.mail.Multipart;
  12. import javax.mail.Session;
  13. import javax.mail.Transport;
  14. import javax.mail.internet.InternetAddress;
  15. import javax.mail.internet.MimeBodyPart;
  16. import javax.mail.internet.MimeMessage;
  17. import javax.mail.internet.MimeMultipart;

  18. public class SendAttachment
  19. {
  20. public static void main(String []args) throws Exception
  21.     {
  22. //Creating Properties Object
  23. Properties properties=new Properties();

  24. //adding protocol,mailserver address & the port number of the mailserver
  25. properties.put("mail.transport.protocol","smtp");
  26. properties.put("mail.smtp.host","localhost");
  27. properties.put("mail.smtp.port","25");

  28. //Creating the Session Object
  29. Session session=Session.getInstance(properties);

  30. //Creating and configuring the Message object
  31. Message message=new MimeMessage(session);
  32. message.setFrom(new InternetAddress("kalam1"));
  33.   message.setRecipient(RecipientType.TO,new InternetAddress("modi1"));
  34. message.setSentDate(new Date());
  35. message.setSubject("MAIL WITH ATTACHMENT");

  36. // mail body obj
  37. Multipart mailbody=new MimeMultipart();

  38. // mail body part1 obj (text content)
  39. MimeBodyPart part1=new MimeBodyPart();
  40. part1.setText("hello see my resume");
  41. mailbody.addBodyPart(part1);

  42.   //mail body part2(attachment)
  43. FileDataSource fds=new FileDataSource("src/resume.txt");// represents attachment file
  44. MimeBodyPart part2=new MimeBodyPart();
  45. part2.setDataHandler(new DataHandler(fds));
  46. part2.setFileName(fds.getName());
  47. mailbody.addBodyPart(part2);
  48. message.setContent(mailbody);

  49. //Sending the mail. 
  50. Transport.send(message);
  51. System.out.println("Mail has been delivered");
  52.     }//main
  53. }//class
  54. //>javac SendAttachment.java

  55. //>java SendAttachment one.txt

To read Email Messages:-
(1),(2),(3) same as above but pointing to incoming server
(4)Connect to pop3s store based Email account
(5)Open Inbox folder in ReadOnly mode
(6)Read all the messages
(7)Close folder and store

ReadMail:
  1. package com.nt.mail;

  2. import java.util.Properties;
  3. import javax.mail.Folder;
  4. import javax.mail.Message;
  5. import javax.mail.Session;
  6. import javax.mail.Store;

  7. public class RecieveMail {

  8. public static void main(String[] args)throws Exception {
  9. Properties properties=new Properties();
  10.  properties.put("mail.transport.protocol","pop");
  11.  properties.put("mail.pop.port","110");
  12.  properties.put("mail.host","localhost");

  13.  Session session=Session.getInstance(properties);
  14.  Store store=session.getStore("pop3");
  15.  store.connect("localhost","modi1","modi1");

  16. // Access InBox
  17. Folder inbox=store.getFolder("INBOX");
  18. inbox.open(Folder.READ_ONLY);

  19. //read email messages
  20. System.out.println("Messages count"+inbox.getMessageCount());
  21. Message messages[]=inbox.getMessages();

  22. //Display messages
  23. for(Message msg:messages){
  24. msg.writeTo(System.out);
  25. System.out.println("------------------------------");
  26. }
  27. store.close();
  28. inbox.close(false);
  29. }
  30. }

For Deleting Email Messages:-
(1),(2),(3) &(4) are same as read mail
(5)Open Inbox folder in READWrite mode
(6)Read all messages or specific messages
(7)Mark certain messages for deletion(Flags.Flag.DELETED,true)
(8)Close Inbox with flag true

DeleteMail:
  1. package com.nt.mail;

  2. import java.util.Properties;
  3. import javax.mail.Flags;
  4. import javax.mail.Folder;
  5. import javax.mail.Message;
  6. import javax.mail.Session;
  7. import javax.mail.Store;

  8. public class DeleteMail {

  9. public static void main(String[] args) throws Exception{
  10. Properties properties=new Properties();
  11.  properties.put("mail.transport.protocol","pop");
  12.  properties.put("mail.pop.port","110");
  13.  properties.put("mail.host","localhost");

  14.  Session session=Session.getInstance(properties);
  15.  Store store=session.getStore("pop3");
  16.  store.connect("localhost","modi1","modi1");

  17.  // Access InBox
  18.  Folder inbox=store.getFolder("INBOX");
  19.  inbox.open(Folder.READ_WRITE);
  20.  System.out.println("Messages count"+inbox.getMessageCount());

  21.  //Read messages
  22.  Message message=inbox.getMessage(1);

  23.  //Mark the message for deleteion
  24.  message.setFlag(Flags.Flag.DELETED,true);

  25.  //close inbox with flag true
  26.  inbox.close(true);
  27.  System.out.println("Messages count"+inbox.getMessageCount());
  28.  store.close();
  29. }
  30. }

Note: When Inbox is closed with the flag true, all the marked messages for deletion will be deleted

Comments

Popular posts from this blog

JSP Comments

Comments in JSP:- -->Compiler /Interpreter doesn't take commented code for compilation /Interpretation, so the commented code doesn't participate in execution JSP supports 3 types of comments:- a.)HTML comments /Template text comments/ Output comments Syn :- <!---text---> -->Recognized by html interpreter of browser b.)JSP comments /Hidden comments Syn :- <%--text--%> -->JSP page compiler recognize these comments c.)Java comments /Scripting comments Syn :- //-->For single line /*-- -----*/-->For multiple line -->Java compiler(java) recognize these comments -->In Eclipse IDE JES class for first.jsp comes in our(workspace)folder/.metadata/.plugins/.org eclipse Comments (1)JSP comment<%--%> (2)Java comment(// or /*--*/) (3)HTML comments(<!---> JES Source Code (1)No (2)Yes (3)Yes In JES compiled code (1)No (2)No (3)Yes In the code going to browser (1)No (2)No (3)Yes Output (1)No (2)No (3)No -->Jsp comments are not visible in any phase

Scripting Tags

JSP Tags/ Elements (1)Scriptlet     Standard syn:-         <%.........%>     xml syn:-        <jsp:scriptlet>...</jsp:scriptlet> Note: All scripting tags allows us to place script code(java code) 1.)The code placed in scriptlet go to _jspService(-,-) of JES class 2.)In a jsp page we can have zero or more scriptlets 3.)We place request processing logics in scriptlets 4.)Variables declared in scriptlets becomes the local variables in _jspService(-,-) of JES class in first.jsp In first.jsp: <% int a=10;  out.println("square:"+(a*a));%> In first_jsp.java(JES): public class first_jsp extends..{     public void _jspService(-,-){        int t=30;        out.println(“Square:”+(t*t));     }  } The code placed in scriptlet can use implicit objects of jsp because implicit objects and the code placed scriptlet goes to _jspService(-,-) method of JES class first.jsp Browser s/w name: <%out.println(request.getHeader("user-agent");%> first_jsp.java pu

Project Architecture's

1.) Functional flow/ Architecture a.) Only for 6+/7+years b.) Explain the flow of process/business 2.) Technical Flow/Architecture a.) Upto 5+ years b.) Explain technologies /components that are involved in the project Servlet & JSP Project Architecture:- 1.)What is need of Business Deligate to convert VO class object to DTO class object ? a.) If Business Deligate is not there servlet component directly prepares DTO class object by receiving and translating form data and passes to service class, if service class excepts certain input in other format like numeric employee number as string employee number then we need to modify servlet component code i.e For the changes that happened in business tier service component we have to modify servlet component of presentation tier b.) If Business Deligate is taken then it gets original form data as VO class object having string inputs and converts VO class object to DTO class object to pass to service class c.) If service class excepts