Send mail with Java springboot


Reprint: Using java to send mail
Reprint: Spring Boot realizes mail sending

Guide Package

If it is an mvn project, we only need to add dependencies

<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>

Normal: create a simple email

Mail creation steps:

  1. Create a mail object (MimeMessage);
  2. Set the sender and recipient. You can add multiple recipients, CC and BCC;
  3. Set the subject (title) of the email;
  4. Set the body (content) of the email;
  5. Set the displayed sending time;
  6. Save to local.
    The code is as follows:
public class TestMail {
    public static void main(String[] args) throws Exception {
        // 1. Create an email
        Properties props = new Properties();                // Parameter configuration for connecting to the mail server (only required when sending mail)
        Session session= Session.getInstance(props);        // Create a session object (prepared for sending mail) according to the parameter configuration
        MimeMessage message = new MimeMessage(session);     // Create mail object
 
        /*
         * You can also create MimeMessage objects based on existing eml mail files
         * MimeMessage message = new MimeMessage(session, new FileInputStream("myEmail.eml"));
         */
 
        // 2. From: sender
        //    The three parameters of Internet address are: mailbox, displayed nickname (only for display, no special requirements), and character set code of nickname
        //    When you really want to send, the mailbox must be a real and valid mailbox.
        message.setFrom(new InternetAddress("email@send.com", "USER_AA", "UTF-8"));
 
        // 3. To: recipient
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("cc@receive.com", "USER_CC", "UTF-8"));
        //    To: add recipients (optional)
        message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("dd@receive.com", "USER_DD", "UTF-8"));
        //    Cc: Cc (optional)
        message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("ee@receive.com", "USER_EE", "UTF-8"));
        //    Bcc: Secret delivery (optional)
        message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("ff@receive.com", "USER_FF", "UTF-8"));
 
        // 4. Subject: email subject
        message.setSubject("Mail subject", "UTF-8");
 
        // 5. Content: email body (html tag can be used)
        message.setContent("This is the body of the message", "text/html;charset=UTF-8");
 
        // 6. Set the displayed sending time
        message.setSentDate(new Date());
 
        // 7. Save the previous settings
        message.saveChanges();
 
        // 8. Save the message locally
        OutputStream out = new FileOutputStream("myEmail.eml");
        message.writeTo(out);
        out.flush();
        out.close();
    }
}

springboot mode

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

Basic configuration
Configure basic mailbox information
After the project is successfully created, the next step is in application Basic information of configuring mailbox in properties:

spring.mail.host=smtp.163.com
spring.mail.port=25
spring.mail.username=13XXXXXXX12@163.com
spring.mail.password=123456yjn
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true

The meanings of configuration are as follows:
Configure SMTP server address
The port 163 mailbox of the SMTP server does not use SSL. The default port is 25. The port 465 / 994 can be used with SSL (SSL for large factories such as QQ)
Configure mailbox user name
Configure the password. Note that it is not the real password, but the authorization code just applied for (something similar to the activation code)
Default message code
Accessories SSL encryption factory (required by qq mailbox and other large factories)
Indicates that the DEBUG mode is enabled. In this way, the log of mail sending process will be printed on the console to facilitate troubleshooting (with information)
code:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailApplicationTests {

    @Autowired
    JavaMailSender javaMailSender;

    @Test
    public void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("This is a test email");
        message.setFrom("13XXXXXXX12@163.com");
        message.setTo("95XXXXX50@qq.com");
        message.setCc("37xxxxx37@qq.com");
    	message.setBcc("14xxxxx098@qq.com");
        message.setSentDate(new Date());
        message.setText("This is the body of the test message");
        javaMailSender.send(message);
    }
}

From top to bottom, the code meanings are as follows:

Build a mail object
Set message subject
Set mail sender
Set mail recipients. You can have multiple recipients
Set email CC person, and there can be multiple CC persons
Set a secret CC person, which can have multiple
Set mail sending date
Set the body of the message
Send mail
Finally, by executing this method, the mail can be sent

Posted by Tonisius on Thu, 05 May 2022 10:19:09 +0300