Java Web Sending Mail

We can use a third-party mailbox server to send mail.


There are two commonly used mail transfer protocols: POP3/SMTP and IMAP/SMTP.

The difference between POP and IMAP: Operations on the mailbox client, such as mobile mail, tags read, will not be synchronized to the mailbox server if POP is used; if IMAP is used, these operations will be synchronized to the mailbox server.



Two jar packages are required

  • javax.mail.jar
  • activation.jar



Example: Sending mail using QQ mailbox server

IMAP is used here. It can be configured in the Settings - > Accounts - > POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV service.

public class SendMailServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// Connection protocol
        properties.put("", "");// Mailbox Server Host Name
        properties.put("mail.smtp.port", 465);// Port number
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");//Whether to use ssl Secure connection
        properties.put("mail.debug", "true");//Whether to display relevant information in the console

        //Getting session objects
        Session session = Session.getInstance(properties);
        //Getting mail objects
        Message message = new MimeMessage(session);

        try {
            // Setting the sender's mailbox address
            message.setFrom(new InternetAddress(""));
            // Setting the addressee's mailbox address
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(""));

            //When there are multiple recipients, write in array form
            //InternetAddress[] receiverArr={new InternetAddress(""),new InternetAddress(""),new InternetAddress("")};
            //message.setRecipients(Message.RecipientType.TO, receiverArr);

            // Setting Mail Title
            message.setSubject("Mail title");
            // Setting Mail Content
            message.setText("Mail content");

            //Getting Postman Objects
            Transport transport = session.getTransport();
            //Connect to your own email account. The second parameter is the authorization code.
            transport.connect("", "xxxxxxxxxxx");
            //Send mail
            transport.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


When used, the scarlet letter part can be modified.

Tags: Java Session SSL Mobile

Posted on Mon, 07 Oct 2019 20:00:43 -0700 by mortimerdude