SoFunction
Updated on 2025-03-08

Java mail sending and receiving function implementation code

The examples in this article share the specific implementation code of the email sending and receiving function for your reference. The specific content is as follows

Preparation work, environment construction:
1. Build a mail server locally
Easymail server,
2. Create a new email account
Zhang San sent an email to Li Si.
  Step 1:
Create a new domain name: Tools, Server settings, enter in the single domain name box
Step 2:
Create a new email account: zhangsan@
                            lisi@
3. Install foxmail
Configure the email sending server (smtp): localhost      25
Email receiving server (pop3): localhost     110
Create a new account and you can receive emails!

Notice

If it is a web project, because Javaee comes with email function, there may be problems!
We need to use our own file functions! You need to delete the mail package in javaee!

use:

For JavaMail development, first introduce jar files:

[If you use jdk1.6 or above, you can do not use this jar file]
【Email sending core package】

/**
  * 1. Send a normal email
  * @author
  *
  */
public class App_SendMail {

  @Test
  public void testSend() throws Exception {

    //0. Mail parameters    Properties prop = new Properties();
    ("", "smtp");  // Specify the protocol    ("", "localhost");    // Host    ("", 25);         // Port    ("", "true");       // User password authentication    ("", "true");         // Debug mode
    //1. Create a mail session    Session session = (prop);
    //2. Create a mail object (whole email object)    MimeMessage message = new MimeMessage(session);
    //3. Set the mail body parameters:    //3.1 Title    ("My first email");
    //3.2 Email sending time    (new Date());
    //3.3 Sender    (new InternetAddress("zhangsan@"));
    //3.4 Recipient    (, new InternetAddress("lisi@"));
    //3.5 Content    ("Hello, it has been sent successfully! Text..."); // Simple plain text email    ();  // Save email (optional)
    //4. Send    Transport trans = ();
    ("zhangsan", "888");
    // Send email    (message, ());
    ();
  }
}

With pictures

/**
  * Email with image resources
  * @author
  *
  */
public class App_2SendWithImg {

  // Initialize parameters  private static Properties prop;
  // Sender  private static InternetAddress sendMan = null;
  static {
    prop = new Properties();
    ("", "smtp");  // Specify the protocol    ("", "localhost");    // Host    ("", 25);         // Port    ("", "true");       // User password authentication    ("", "true");         // Debug mode    try {
      sendMan = new InternetAddress("zhangsan@");
    } catch (AddressException e) {
      throw new RuntimeException(e);
    }
  }

  @Test
  public void testSend() throws Exception {
    // 1. Create a mail session    Session session = (prop);
    // 2. Create a mail object    MimeMessage message = new MimeMessage(session);
    // 3. Set parameters: title, sender, recipient, sending time, content    ("Email with pictures");
    (sendMan);
    (, new InternetAddress("lisi@"));
    (new Date());

    /********************* Set email content: Multifunctional user email (related)*********************/
    // 4.1 Build a multi-functional mail block    MimeMultipart related = new MimeMultipart("related");
    // 4.2 Build multi-functional mail block content = text on the left + picture resources on the right    MimeBodyPart content = new MimeBodyPart();
    MimeBodyPart resource = new MimeBodyPart();

    // Set specific content: a. Resources (pictures)    String filePath = App_2SendWithImg.("").getPath();
    DataSource ds = new FileDataSource(new File(filePath));
    DataHandler handler = new DataHandler(ds);
    (handler);
    ("");  // Set the resource name and refer to the foreign key
    // Set specific content: b. Text    ("<img src='cid:'/> OK Haha!", "text/html;charset=UTF-8");

    (content);
    (resource);

    /*********4.3 Add complex emails built to the emails *******/
    (related);


    // 5. Send    Transport trans = ();
    ("zhangsan", "888");
    (message, ());
    ();
  }
}

Pictures + attachments

/**
  * 3. Email with picture resources and attachments
  * @author
  *
  */
public class App_3ImgAndAtta {

  // Initialize parameters  private static Properties prop;
  // Sender  private static InternetAddress sendMan = null;
  static {
    prop = new Properties();
    ("", "smtp");  // Specify the protocol    ("", "localhost");    // Host    ("", 25);         // Port    ("", "true");       // User password authentication    ("", "true");         // Debug mode    try {
      sendMan = new InternetAddress("zhangsan@");
    } catch (AddressException e) {
      throw new RuntimeException(e);
    }
  }

  @Test
  public void testSend() throws Exception {
    // 1. Create a mail session    Session session = (prop);
    // 2. Create a mail object    MimeMessage message = new MimeMessage(session);
    // 3. Set parameters: title, sender, recipient, sending time, content    ("Email with pictures");
    (sendMan);
    (, new InternetAddress("lisi@"));
    (new Date());

    /*
      * Email development with attachments (pictures)
      */
    // Build a total mail block    MimeMultipart mixed = new MimeMultipart("mixed");
    // ---> Total mail is fast, set to the mail object    (mixed);
    // Left: (Text + Image Resource)    MimeBodyPart left = new MimeBodyPart();
    // Right: Attachment    MimeBodyPart right = new MimeBodyPart();
    // Set to the total mail block    (left);
    (right);

    /******appendix********/
    String attr_path = ().getResource("").getPath();
    DataSource attr_ds = new FileDataSource(new File(attr_path));
    DataHandler attr_handler = new DataHandler(attr_ds);
    (attr_handler);
    ("");


    /********************* Set email content: Multifunctional user email (related)*********************/
    // 4.1 Build a multi-functional mail block    MimeMultipart related = new MimeMultipart("related");
    // ---> Set to the left side of the total email fast    (related);

    // 4.2 Build multi-functional mail block content = text on the left + picture resources on the right    MimeBodyPart content = new MimeBodyPart();
    MimeBodyPart resource = new MimeBodyPart();

    // Set specific content: a. Resources (pictures)    String filePath = App_3ImgAndAtta.("").getPath();
    DataSource ds = new FileDataSource(new File(filePath));
    DataHandler handler = new DataHandler(ds);
    (handler);
    ("");  // Set the resource name and refer to the foreign key
    // Set specific content: b. Text    ("<img src='cid:'/> OK Haha!", "text/html;charset=UTF-8");

    (content);
    (resource);



    // 5. Send    Transport trans = ();
    ("zhangsan", "888");
    (message, ());
    ();
  }
}

The above is all about this article, I hope it will be helpful for everyone to learn Java programming.