This article briefly introduces how to send email via QQ Mailbox with Spring framework support, including simple text, attachments, as well as inline images, HTML and HTTP images.

Spring-context-support has long had built-in support for mail sending.

Of course, the official documentation clearly states that you need to rely on the JavaMail library.

In this day and age, we rarely set up our own SMTP server to send mail, and generally use the services of mail providers. For example, QQ mailbox, enterprise mailbox, 163, or ali cloud and other manufacturers.

Sign up for an account, then refer to your email service’s help center and account Settings page for SMTP server port information, as well as your registered account and password, and save them in a secure location.

Correlation dependencies.

The dependencies in POM.xml are as follows:

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version> 4.0.7.release </version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId> Commons -io</groupId> <artifactId> The < version > 2.2 < / version > < / dependency >Copy the code

Commons-io can be used as required. This article uses the IOUtils tool class, which provides many convenient and powerful IO tool methods. If you are interested, you can study it.

Spring-mail related interfaces and implementation classes

  • MailSender, the top-level interface for sending simple messages.
  • JavaMailSender, inherits the top-level interface and supports sending MIME mail.
  • JavaMailSenderImplImplementation class, as the name implies.
  • SimpleMailMessageClass, simple mail messages, includingfrom.to.cc.subjectAs well astextField.
  • MimeMessagePreparatorInterface for MIME mail callbacks.
  • MimeMessageHelperHelper classes that can be used to create MIME messages. Supports images, attachments, and HTML styles.

Simple test code

Here is a simple test code. Refer to the links at the end of this article for practical use. Organize your code better and use it better.

package com.cncounter.test.spring; import org.springframework.mail.MailException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; public class TestSpringEmail { public static void main(String[] args) { // sendTextEmail(); } public static void sendTextEmail() { // JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); // See mailsender.sethost ("smtp.qq.com "); // mailsender.setPort (465); Mailsender.setport (587); // Port number mailsender.setusername ("[email protected] "); // Use your own account mailsender. setPassword("usbusbcnzztbsbtob "); SimpleMailMessage MSG = new SimpleMailMessage(); msg.setFrom("[email protected] "); // Sender email msg.setto ("[email protected] "); // Recipient email msg.setSubject(" Test Spring mail "); MSG. SetText (" Your order number: 20181120075; Please don't tell anyone! "); // Text message try {mailsender.send (MSG); System.out.println(" Email sent successfully! "); } catch (MailException ex) {system.err.println (" failed to send: "+ ex.getMessage()); }}}Copy the code

The test results are as follows:

As you can see, text like simple captcha is easy to code with these encapsulated utility classes.

Example of sending attachments

Here is an example of sending attachments. Multiple attachments can be sent as needed.

package com.cncounter.test.spring; import org.apache.commons.io.IOUtils; import org.springframework.core.io.ByteArrayResource; import org.springframework.mail.MailException; import org.springframework.mail.javamail.*; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.*; import java.util.Properties; Public class TestSpringAttachEmail {public static void main(String[] args) throws Exception {// Send MIME mail with attachment sendAttachmentEmail(); } // Send MIME messages with attachments public static void sendAttachmentEmail() throws MessagingException, IOException {// mailSender mailSender = getJavaMailSender(); . / / MIME email MimeMessage MimeMessage = mailSender createMimeMessage (); // Auxiliary class; Explicitly use UTF-8 encoding; MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8 "); // boolean isHTML = true; // Email message helper.setFrom("[email protected] "); // Email helper.setto ("[email protected] "); // Recipient email helper.setSubject(" Test Spring to send attachments -1 "); / / title helper. SetText (" please click: < a href = "http://www.yuledanao.com/dl/PWA_INTRO.zip" > < b > PWA development profile. Zip < / b > < / a >; "+" or download the attachment! ", isHTML); // HTML- info // add 1 attachment; String fileName1 = "E:/PWA development intro. Zip "; InputStream inputStream1 = new FileInputStream(fileName1); // // Java Mail opens InputStreamResource twice. ByteArrayResource byteResource1 = new ByteArrayResource(IOUtils.toByteArray(inputStream1)); // InputStreamResource attachment1 = new InputStreamResource(inputStream1); Helper.addattglide ("PWA development intro. Zip ", byteResource1); try { mailSender.send(mimeMessage); System.out.println(" Email sent successfully! "); } catch (MailException ex) {system.err.println (" failed to send: "+ ex.getMessage()); } finally { IOUtils.closeQuietly(inputStream1); Public static JavaMailSender getJavaMailSender() {// JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); // See mailsender.sethost ("smtp.qq.com "); // mailsender.setPort (465); // The QQ port is not available. Why is that? mailSender.setPort(587); // Port number mailsender.setusername ("[email protected] "); // Use your own account mailsender. setPassword("usbusbcnzztbsbtob "); / / authorization code - text / / / / related attributes configuration, also can not change, use the default Properties props. = mailSender getJavaMailProperties (); props.put("mail.transport.protocol ", "smtp "); // Protocol props. Put ("mail.smtp.auth ", "true "); / / login props. The put (" mail. The SMTP. Starttls. Enable ", "true"); // Use SSL props. Put ("mail.debug ", "true "); // return mailSender; }}Copy the code

Of course, the specific code should be properly encapsulated as required. Such as custom utility classes.

The results are shown below:

Send an example of an inline picture

There are two methods, please choose according to your needs:

  1. HTML embeds the image of the HTTP path.
  2. Send images as an inline resource.

Here are examples of both types of inline images:

package com.cncounter.test.spring; import org.apache.commons.io.IOUtils; import org.springframework.core.io.ByteArrayResource; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; Public class TestSpringImageEmail {public static void main(String[] args) throws Exception {// Send a MIME email with an inline image sendImageEmail(); } // Send MIME messages with inline images public static void sendImageEmail() throws MessagingException, IOException {// mailSender mailSender = getJavaMailSender(); . / / MIME email MimeMessage MimeMessage = mailSender createMimeMessage (); // Auxiliary class; Explicitly use UTF-8 encoding; MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8 "); // boolean isHTML = true; // Email message helper.setFrom("[email protected] "); // Email helper.setto ("[email protected] "); // Recipient email helper.setSubject(" Test Spring to send inline image-3 "); // title helper.setText("<h1> Test image </h1> "+" Hisson TV -InLine: " + "<br/> " + "<a target='_blank' href='http://www.yuledanao.com/dl/haixin.png' ><img src='cid:image1' /></a> " + "<br/> "+ "img-src-http " + "<br/> " + "<a target='_blank' href='http://www.yuledanao.com/dl/haixin.png' ><img SRC = "http://www.yuledanao.com/dl/haixin.png" / > < / a > "+" < br / > < br / > "+" "+", please click: < a target = "_blank" href = "http://www.yuledanao.com/dl/PWA_INTRO.zip" > < b > PWA development profile. Zip < / b > < / a >; "+" or download the attachment! ", isHTML); // HTML- info // cid-content-id // Add inline image :/ / Do not send as attachment String imageName1 = "E:/ haixn.png "; InputStream imageInputStream1 = new FileInputStream(imageName1); ByteArrayResource imageResource1 = new ByteArrayResource(IOUtils.toByteArray(imageInputStream1)); helper.addInline("image1 ", imageResource1, "image/png "); // Add 1 attachment; String fileName1 = "E:/PWA development intro. Zip "; InputStream inputStream1 = new FileInputStream(fileName1); // // Java Mail opens InputStreamResource twice; // The first time to determine the encoding, the second time to execute the encoding. ByteArrayResource byteResource1 = new ByteArrayResource(IOUtils.toByteArray(inputStream1)); // InputStreamResource attachment1 = new InputStreamResource(inputStream1); Helper.addattglide ("PWA development intro. Zip ", byteResource1); try { mailSender.send(mimeMessage); System.out.println(" Email sent successfully! "); } catch (MailException ex) {system.err.println (" failed to send: "+ ex.getMessage()); } finally { IOUtils.closeQuietly(inputStream1); Public static JavaMailSender getJavaMailSender() {// JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); // See mailsender.sethost ("smtp.qq.com "); // mailsender.setPort (465); // The QQ port is not available. Why is that? mailSender.setPort(587); // Port number mailsender.setusername ("[email protected] "); // Use your own account mailsender. setPassword("usbusbcnzztbsbtob "); / / authorization code - text / / / / related attributes configuration, also can not change, use the default Properties props. = mailSender getJavaMailProperties (); props.put("mail.transport.protocol ", "smtp "); // Protocol props. Put ("mail.smtp.auth ", "true "); / / login props. The put (" mail. The SMTP. Starttls. Enable ", "true"); // use SSL //props. Put ("mail.debug ", "true "); // return mailSender; }}Copy the code

If there is no fixed HTTP server or CDN server on the public network, you need to send images in inline mode.

When images can be downloaded from the network, it is easier to reference HTTP resources.

If CSS style is required, set the style attribute of the HTML element.

The execution result is as follows:

There is no conflict with sending attachments. If you need to send a lot of images, you can use templating techniques, along with Maps/beans, to encapsulate incoming data.

For more information, please refer to related links.

A link to the

Spring Email tutorial: www.baeldung.com/spring-emai…

Spring integration Email document: docs. Spring. IO/spring/docs…

Date: 8 April 2018