A detailed description of the Web-based mail delivery system for Java Mail

Source: Internet
Author: User
Tags imap rfc server port microsoft outlook



The system is web-based and references a third-party API:mail.jar development package.



I. Introduction to the directory structure



We can download the Mail.jar development package on the Oracle website, the version I downloaded is 1.4.5. After the download is successful, you will get a javamail1_4_5.zip file and unzip it.



The first is the root directory of the Mail.jar is its core package






In the Lib subdirectory there is a jar package that corresponds to the following, where Mailapi.jar encapsulates the creation of the message content and the API class for sending and receiving messages to ordinary developers, and three other jar files (Imap.jar, Pop3.jar, Smtp.jar) Is the service implementation that encapsulates their name relative to the protocol. The relationship between the Mailapi.jar and the other three jar files is like the JDBC API's relationship to the JDBC driver implemented by each database. When compiling a Java mail program, you only need to mailapi.jar the file, but at run time you must have the underlying service implementation of the appropriate mail protocol. This application only uses the mail sending function, So you can import only two files of Smtp.jar and Mailapi.jar, and if your application needs to use the message's receive feature, you can install the two jar files Pop3.jar or Imap.jar and Mailapi.jar without importing the entire Mail.jar file.






Two. Introduction of related agreements



1.SMTP protocol



The SMTP (Simple Mail Transfer Protocol) is simply the message Transfer Protocol, which is a set of rules for sending mail from the source address to the destination, and it controls the way the letters are relayed. The SMTP protocol belongs to the TCP/IP protocol family, which helps each computer find its next destination when sending or relaying letters. Through the server specified by the SMTP protocol, e-Mail can be sent to the recipient's server, the whole process only a few minutes. An SMTP server is a sending mail server that follows the SMTP protocol and is used to send or relay e-mail messages.



2.POP protocol



The POP represents the Post Office Protocol (post offices Protocol). Currently using version 3, also known as POP3,RFC 1939, defines the protocol. POP is a mechanism that most people on the Internet use to get mail. It specifies a mailbox support for each user. That's what it can do, and it creates a lot of confusion. When using pop, many of the performance users are familiar with are not supported by the POP protocol, such as viewing the performance of several new mail messages. These properties are built into programs such as Eudora or Microsoft Outlook, and they can remember things like the last message received and how much is new.



3.IMAP protocol



IMAP is a more advanced protocol for receiving messages. As defined in RFC 2060, IMAP represents the Internet Message Access Protocol (Internet messages access Protocol), currently using version 4, also known as IMAP4. When IMAP is used, the mail server must support this protocol. You can't just use a POP program for IMAP, and expect it to support all IMAP performance. Assuming that the mail server supports IMAP, JavaMail-based programs can take advantage of this situation-users have multiple folders on the server, and these folders can be shared by multiple users.



Because of this more advanced performance, you might think that all users will use IMAP. That is not the case. Requires the server to receive new messages, send them to the user when requested, and maintain messages in multiple folders for each user. This allows the message to be backed up in a centralized way, but as the user's long-term mail folder becomes larger and smaller, each user is compromised when disk space is exhausted. With POP, you can uninstall messages saved on the mail server.


Finally, Mime,mine represents the multi-purpose Internet Mail extension standard (Multipurpose Internet Mail Extensions). It is not a mail transfer protocol. However, a format is defined for messages, attachments, and other contents that transmit content.


OK, the above is the basic knowledge of e-mail sending and receiving, with the basic knowledge, we in the combination of code to Java mail in-depth understanding and learning



Messages sent and accepted by






Sent by mail






Three. Package for mail delivery

public class Mail {
  
    private MimeMessage mimeMsg; // MIME mail object
    private Session session; // Mail configuration object
    private Properties props; // System properties
    @SuppressWarnings ("unused")
private boolean needAuth = false; // Whether smtp needs authentication
    // smtp authentication username and password
    private String username;
    private String password;
    private Multipart mp; // Multipart object, mail content, header, attachments and other content are added to it before generating MimeMessage object
       
    / **
     * Constructor
     * @param smtp mail sending server
     * /
    public Mail (String smtp) {
        setSmtpHost (smtp);
        createMimeMessage ();
    }
  
    / **
     * Set up mail sending server
     * @param hostName String
     * /
    public void setSmtpHost (String hostName) {
           
        if (props == null)
            props = System.getProperties (); // Get system property object
        props.put ("mail.smtp.host", hostName); // Set SMTP host
    }
  
  
    / **
     * Create MIME mail object
     * @return
     * /
    public boolean createMimeMessage ()
    {
        try {
            System.out.println ("Ready to get mail conversation object!");
            session = Session.getDefaultInstance (props, null); // Get mail session object
        }
        catch (Exception e) {
            System.err.println ("An error occurred while getting the mail conversation object!" + E);
            return false;
        }
      
        System.out.println ("Ready to create MIME mail object!");
        try {
            mimeMsg = new MimeMessage (session); // Create MIME mail object
            mp = new MimeMultipart ();
          
            return true;
        } catch (Exception e) {
            System.err.println ("Failed to create MIME mail object!" + E);
            return false;
        }
    }
      
    / **
     * Set whether SMTP requires authentication
     * @param need
     * /
    public void setNeedAuth (boolean need) {
        System.out.println ("Set smtp authentication: mail.smtp.auth =" + need);
        if (props == null) props = System.getProperties ();
        if (need) {
            props.put ("mail.smtp.auth", "true");
        } else {
            props.put ("mail.smtp.auth", "false");
        }
    }
  
    / **
     * Set username and password
     * @param name
     * @param pass
     * /
    public void setNamePass (String name, String pass) {
        username = name;
        password = pass;
    }
  
    / **
     * Set email subject
     * @param mailSubject
     * @return
     * /
    public boolean setSubject (String mailSubject) {
        System.out.println ("Set mail subject!");
        try {
            mimeMsg.setSubject (mailSubject);
            return true;
        }
        catch (Exception e) {
            System.err.println ("There was an error setting the subject of the email!");
            return false;
        }
    }
      
    / **
     * Set email body
     * @param mailBody String
     * /
    public boolean setBody (String mailBody) {
        try {
            BodyPart bp = new MimeBodyPart ();
            bp.setContent ("" + mailBody, "text / html; charset = GBK");
            mp.addBodyPart (bp);
          
            return true;
        } catch (Exception e) {
        System.err.println ("An error occurred while setting the email body!" + E);
        return false;
        }
    }
    / **
     * Add attachments 
     * @param filename String
     * /
    public boolean addFileAffix (String filename) {
      
        System.out.println ("Add email attachment:" + filename);
        try {
            BodyPart bp = new MimeBodyPart ();
            FileDataSource fileds = new FileDataSource (filename);
            bp.setDataHandler (new DataHandler (fileds));
            bp.setFileName (fileds.getName ());
              
            mp.addBodyPart (bp);
              
            return true;
        } catch (Exception e) {
            System.err.println ("Add email attachment:" + filename + "An error occurred!" + E);
            return false;
        }
    }
      
    / **
     * Set sender
     * @param from String
     * /
    public boolean setFrom (String from) {
        System.out.println ("Set sender!");
        try {
            mimeMsg.setFrom (new InternetAddress (from)); // Set the sender
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    / **
     * Set recipient
     * @param to String
     * /
    public boolean setTo (String to) {
        if (to == null) return false;
        try {
            mimeMsg.setRecipients (Message.RecipientType.TO, InternetAddress.parse (to));
            return true;
        } catch (Exception e) {
            return false;
        }
    }
      
    / **
     * Set CC
     * @param copyto String
     * /
    public boolean setCopyTo (String copyto)
    {
        if (copyto == null) return false;
        try {
        mimeMsg.setRecipients (Message.RecipientType.CC, (Address []) InternetAddress.parse (copyto));
        return true;
        }
        catch (Exception e)
        {return false;}
    }
      
    / **
     * send email 
     * /
    public boolean sendOut ()
    {
        try {
            mimeMsg.setContent (mp);
            mimeMsg.saveChanges ();
            System.out.println ("Sending mail ...");
              
            Session mailSession = Session.getInstance (props, null);
            Transport transport = mailSession.getTransport ("smtp");
            transport.connect ((String) props.get ("mail.smtp.host"), username, password);
            transport.sendMessage (mimeMsg, mimeMsg.getRecipients (Message.RecipientType.TO));
            transport.sendMessage (mimeMsg, mimeMsg.getRecipients (Message.RecipientType.CC));
            //transport.send(mimeMsg);
              
            System.out.println ("Send mail successfully!");
            transport.close ();
              
            return true;
        } catch (Exception e) {
            System.err.println ("Failed to send email!" + E);
            return false;
        }
    }
  
    / **
     * Call sendOut method to complete mail sending
     * @param smtp
     * @param from
     * @param to
     * @param subject
     * @param content
     * @param username
     * @param password
     * @return boolean
     * /
    public static boolean send (String smtp, String from, String to, String subject, String content, String username, String password) {
        Mail theMail = new Mail (smtp);
        theMail.setNeedAuth (true); // Require authentication
          
        if (! theMail.setSubject (subject)) return false;
        if (! theMail.setBody (content)) return false;
        if (! theMail.setTo (to)) return false;
        if (! theMail.setFrom (from)) return false;
        theMail.setNamePass (username, password);
          
        if (! theMail.sendOut ()) return false;
        return true;
    }
      
    / **
     * Call sendOut method to complete mail sending, with CC
     * @param smtp
     * @param from
     * @param to
     * @param copyto
     * @param subject
     * @param content
     * @param username
     * @param password
     * @return boolean
     * /
    public static boolean sendAndCc (String smtp, String from, String to, String copyto, String subject, String content, String username, String password) {
        Mail theMail = new Mail (smtp);
        theMail.setNeedAuth (true); // Require authentication
          
        if (! theMail.setSubject (subject)) return false;
        if (! theMail.setBody (content)) return false;
        if (! theMail.setTo (to)) return false;
        if (! theMail.setCopyTo (copyto)) return false;
        if (! theMail.setFrom (from)) return false;
        theMail.setNamePass (username, password);
          
        if (! theMail.sendOut ()) return false;
        return true;
    }
      
    / **
     * Call sendOut method to complete mail sending, with attachment
     * @param smtp
     * @param from
     * @param to
     * @param subject
     * @param content
     * @param username
     * @param password
     * @param filename attachment path
     * @return
     * /
    public static boolean send (String smtp, String from, String to, String subject, String content, String username, String password, String filename) {
        Mail theMail = new Mail (smtp);
        theMail.setNeedAuth (true); // Require authentication
          
        if (! theMail.setSubject (subject)) return false;
        if (! theMail.setBody (content)) return false;
        if (! theMail.addFileAffix (filename)) return false;
        if (! theMail.setTo (to)) return false;
        if (! theMail.setFrom (from)) return false;
        theMail.setNamePass (username, password);
          
        if (! theMail.sendOut ()) return false;
        return true;
    }
      
    / **
     * Call sendOut method to complete email sending, with attachments and CC
     * @param smtp
     * @param from
     * @param to
     * @param copyto
     * @param subject
     * @param content
     * @param username
     * @param password
     * @param filename
     * @return
     * /
    public static boolean sendAndCc (String smtp, String from, String to, String copyto, String subject, String content, String username, String password, String filename) {
        Mail theMail = new Mail (smtp);
        theMail.setNeedAuth (true); // Require authentication
          
        if (! theMail.setSubject (subject)) return false;
        if (! theMail.setBody (content)) return false;
        if (! theMail.addFileAffix (filename)) return false;
        if (! theMail.setTo (to)) return false;
        if (! theMail.setCopyTo (copyto)) return false;
        if (! theMail.setFrom (from)) return false;
        theMail.setNamePass (username, password);
          
        if (! theMail.sendOut ()) return false;
        return true;
    }
      
}
Code analysis:
In the third line, MimeMessage, MINE stands for the multi-purpose Internet mail extension standard. It inherits from the Message class. The javax.mail.Message class is the core API for creating and parsing mail. Its instance object can be understood as an email .

In the fourth line, the Session class is a class that is easily misunderstood. This is due to the confusing class name. Don't think that the Session here represents a real interactive session like HttpSession, but there is no corresponding physical connection when creating the Session object, it is just a collection of configuration information. The main role of Session includes two aspects:

       1) Receive various configuration property information: property information set through the Properties object;

       2) Initialize the JavaMail environment: According to the JavaMail configuration file, initialize the JavaMail environment to create instances of other important classes through the Session object.

       So, it might be easier to understand if you rename the Session to Configure

The fifth line Properties object, he said the property object
Because JavaMail needs to communicate with the mail server, this requires the program to provide a lot of information such as server address, port, user name, password, etc. JavaMail encapsulates these attributes through the Properties object information

The thirty-eighth line is the process of creating a MINE mail object. It can be seen that the corresponding properties object information is configured through the session to complete the creation of the mail.

Line 185 is the code for sending mail. It can be seen that the initial environment of javaMail is initialized through the session class to obtain the Properties object; then the Transport method of the session is called, (in fact, the session has two methods of transmission and storage, but this web application Only the sending of mail is used, so the relevant methods of Store are not elaborated)

Transport transport = mailSession.getTransport ("smtp");
 transport.connect ((String) props.get ("mail.smtp.host"), username, password);

Means to obtain the specified type of Transport through session, and then configure the server port, user name and password and other relevant authentication information.

Line 195 indicates message sending

The Transport class is used here. This class sends messages in the language specified by the protocol (usually SMTP). It is an abstract class, and it works somewhat like Session. Only call the static send () method

Line 273 is used to verify whether the transmission was successful.

Above, we have a very good package for sending emails. Below, we will call the test through a web page.

The first is a mail client

<body>
<center>
<p> Send Email using JSP </ p>
</ center>
<form action = "SendMailServlet" method = "post" enctype = "multipart / form-data">
Recipient: <input type = "text" name = "to"> <br>
From: <input type = "text" name = "from"> <br>
Sender password: <input type = "password" name = "password"> <br>
Title: <input type = "text" name = "subject"> <br>
Content <br>
<textarea name = "content" rows = "10" cols = "80"> </ textarea> <br>
<input type = "submit" value = "Submit">
</ form>
The
</ body>

Handled by the sendMailServlet in the background, its code is as follows
public class SendMailServlet extends HttpServlet {

/ **
*
* /
private static final long serialVersionUID = 1L;

@Override
protected void doGet (HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost (req, resp);
}

@Override
protected void doPost (HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String smtp = "smtp.163.com";
String from = req.getParameter ("from");
String to = req.getParameter ("to");
String copyto = "[email protected]";
String subject = req.getParameter ("subject");
String content = req.getParameter ("content");
String username = req.getParameter ("from");
String password = req.getParameter ("password");
The
The
Mail.sendAndCc (smtp, from, to, copyto, subject, content, username, password);
The
if (Mail.send (smtp, from, copyto, subject, content, username, password)) {
req.setAttribute ("result", "Send successfully, please check in the mailbox");
} else {
req.setAttribute ("result", "Sending failed");
}
The
req.getRequestDispatcher ("MailResult.jsp"). forward (req, resp);
}

}
Processing pages
<body>
          The result shows: $ {result}
  </ body>
Finally, attach the web.xml configuration file
<servlet>
    <description> This is the description of my J2EE component </ description>
    <display-name> This is the display name of my J2EE component </ display-name>
    <servlet-name> SendMailServlet </ servlet-name>
    <servlet-class> com.qzp.servlet.SendMailServlet </ servlet-class>
  </ servlet>
<servlet-mapping>
    <servlet-name> SendMailServlet </ servlet-name>
    <url-pattern> / SendMailServlet </ url-pattern>
  </ servlet-mapping>

Click Submit to finish sending the email.

The above is a complete web-based mail sending system. If you don't understand, please correct me.
Detailed explanation of web-based java Mail mail sending system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.