“This is the third day of my participation in the First Challenge 2022. For details: First Challenge 2022”

๐Ÿ‘จ๐ŸŽ“ Author: Bug Bacteria

โœ๏ธ blog: CSDN, Nuggets, etc

๐Ÿ’Œ public account: Magic House of the Circle of the Apes

๐Ÿšซ special statement: original is not easy, reprint please attach the original source link and this article statement, thank you for your cooperation.

๐Ÿ™ Copyright notice: part of the text or pictures in the article may come from the Internet or Baidu Encyclopedia, if there is infringement, please contact bug bacteria processing.

Hi, family. I’m the bug. Here I go again. Today we are going to talk about something, OK, and we will continue the Series of articles on SpringBoot. Hope to help more beginners quickly start!

In the process of reviewing articles, if you think the articles are helpful to you at all, please don’t be too mean with your likes and bravely light up the articles ๐Ÿ‘. Your likes (collect โญ๏ธ+ pay attention to ๐Ÿ‘จ port + message board) are the best encouragement and support for bugs on my creation path. Time does not abandon ๐Ÿƒ๐Ÿปโ™€๏ธ, creation stopped ๐Ÿ’•, refueling ๐Ÿป

A: the preface

Continuation of the previous article, we have successfully realized the email to send reminders, right, friends follow me all the way to read, do you feel more relaxed, after all, I will not be very long. If you go on like this, you’ll learn one point of knowledge every day, which will make thirty points in a month, and when that adds up, you’ll be the next big guy. If there is a small partner directly inserted midway, but also please trouble to see the content of a few periods, otherwise rrtly follow, must suffer a great loss, go to my column “SpringBoot zero foundation entry” from the beginning to follow up.

Today I will bring you a little fancy knowledge, usually in addition to the body of the email, there are also attachments or pictures in the body, such a requirement, how should we achieve? All right, without further ado, take that!

2. Business scenarios

1. How to send emails with attachments?

A, first of all, let’s define a model POJO [parameters for sending emails with image resources]. The code needs to be standardized. If it can be packaged, it will be packaged as far as possible, and the maintenance cost will be lower in the future. Then inherit the mail poJO, need partners can go to the previous chapter to get ha, here is not much repetition ha, save by some partners ridicule say fill up the word.

package com.example.demo.component.mail.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.List; /** * @author luoYong * @version 1.0 * @date 2022/1/18 10:54 */ @apimodel (value = Public class ImgResMail extends Mail{@APIModelProperty (" Id for an image ") private List<String> contentIds; @APIModelProperty (" ApiModelProperty ") private List<String> paths; public List<String> getContentIds() { return contentIds; } public void setContentIds(List<String> contentIds) { this.contentIds = contentIds; } public List<String> getPaths() { return paths; } public void setPaths(List<String> paths) { this.paths = paths; }}Copy the code

Because of sending the mail with nearby, the basic mail content is still the original, but different from sending ordinary mail is the attachment mail also need to have the attachment storage address, attachment identification of the premise of these two information, the attachment mail can be sent out, which is also necessary to do. So follow the instructions, if you want to send email attachments.

B. Define a method for sending messages with attachments

We use JavaMailSenderImpl to configure the mail sender, MimeMessage to build the mail, and MimeMessageHelper to build the mail sending and receiving information.

/** * Send mail with attachments */ public void sendAccessoryMail(AccessoryMail Model) throws MessagingException {MimeMessage MimeMessage  = javaMailSender.createMimeMessage(); MimeMessageHelper msg = new MimeMessageHelper(mimeMessage, true); Msg.setfrom (model.getsendMailAccount ()); / / mail recipients MSG. SetTo (model. GetAcceptMailAccount ()); Msg.setsubject (model.getTheme()); Msg.settext (model.getmailText ()); Msg.setsentdate (model.getsendTime ()); // addAttachment MSG. Addattpath (model.getattachmentname (), new File(model.getattachmentpath ())); // addAttachment MSG. Addattpath (model.getattachmentname ()); javaMailSender.send(mimeMessage); }Copy the code

Read it:

1, javax.mail. Mail. Internet. MimeMessage that object is actually sent E-mail information, usually use the MimeMessage create email object, create the object should be introduced to a mail session parameter. 2, new MimeMessageHelper(mimeMessage, true) where the second parameter must be true.

Testcese = MailTest; testcese = MailTest;

/** * Send mail with attachments */ @testvoid sendSimpleMailForDoc() throws MessagingException {AccessoryMail mailModel = new AccessoryMail(); Mailmodel.settheme (" This is a test email "); / / set the mail subject mailModel. SetSendMailAccount (" [email protected] "); / / set the email sender mailModel. SetAcceptMailAccount (" [email protected] "); Mailmodel.setsendtime (new Date()); SetMailText (" This is the body of the test message "); / / set the mail text mailModel setAttachmentName (" 2022 PNG "); / / attachment name mailModel. SetAttachmentPath (" C: \ \ Users \ \ Administrator \ \ Desktop \ \ 2022. PNG "); / / address / / test methods sendMailBuild. SendAccessoryMail (mailModel); }Copy the code

Injection parameters must be noted as follows:

  • Attachment names must be complete (including file suffixes such as 2020.png,test.doc, etc.)
  • The attachment address must correspond to a real attachment address. If it cannot be found, the attachment cannot be sent

D, Run testCase, the email was sent successfully, and the attachment was received successfully. The diagram below:

The attachment I sent is a picture, you can also try the document doc, TXT and other files to see if it can also be successful.

The picture will be sent as an attachment by email. Have you passed the test?

2. How to send emails with pictures in the body?

Different from the previous scene, one is the attached image, one is the body image, the two have to be distinguished.

A, we also define a parameter body: ImgResMail

package com.example.demo.component.mail.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.List; /** * @author luoYong * @version 1.0 * @date 2022/1/18 10:54 */ @apimodel (value = Public class ImgResMail extends Mail {@APIModelProperty (" Id for an image ") private  List<String> contentIds; @APIModelProperty (" ApiModelProperty ") private List<String> paths; public List<String> getContentIds() { return contentIds; } public void setContentIds(List<String> contentIds) { this.contentIds = contentIds; } public List<String> getPaths() { return paths; } public void setPaths(List<String> paths) { this.paths = paths; }}Copy the code

B. Define methods

/** * Send an email with an image resource */ public void sendImgResMail(ImgResMail Model) throws MessagingException {MimeMessage MimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper msg = new MimeMessageHelper(mimeMessage, true); Msg.setfrom (model.getsendMailAccount ()); / / mail recipients MSG. SetTo (model. GetAcceptMailAccount ()); Msg.setsubject (model.getTheme()); Msg.setsentdate (model.getsendTime ()); Msg.settext (model.getmailText (),true); For (int I = 0; i < model.getContentIds().size(); i++) { msg.addInline(model.getContentIds().get(i), new FileSystemResource(new File(model.getPaths().get(i)))); } javaMailSender.send(mimeMessage); }Copy the code

Testcese = MailTest; testcese = MailTest;

@Test public void sendImgResMail() throws MessagingException { ImgResMail mailModel = new ImgResMail(); Mailmodel.settheme (" This is a test email "); / / set the mail subject mailModel. SetSendMailAccount (" [email protected] "); / / set the email sender mailModel. SetAcceptMailAccount (" [email protected] "); Mailmodel.setsendtime (new Date()); </p><p> <img SRC ='cid:img1'/><p> </p><img src='cid:img2'/>"); List<String> paths = new ArrayList<>(); Paths. Add ("C:\ Users\ Administrator\ Desktop\ 2022.png"); paths.add("C:\\Users\\Administrator\\Desktop\\test.png"); mailModel.setPaths(paths); List<String> contentIds = new ArrayList<>(); // The following image name matches your email body text, it must be the same, otherwise the image can not be found for display. contentIds.add("img1"); contentIds.add("img2"); mailModel.setContentIds(contentIds); sendMailBuild.sendImgResMail(mailModel); }Copy the code

D, Run testCase, the email is sent successfully, the email is received successfully! The diagram below:

If you need both an attachment and a picture, you can simply combine the two sending methods. The sending method is still the same, but you are sending a combined message by calling the two methods separately.

. .

OK, that’s all for this episode. If you have any questions, feel free to comment in the comments section. See you next time.

Three, the past popular recommendation

Springboot series (12) : how to code to send email reminder environment configuration (preparation)

Springboot series (12) : How to code simple email (part 1)

Springboot series (12) : How to code static template mail (part 2)

Springboot series (12) : how to code to achieve a large email send disk (summary)

. .

If you want to learn more, you can pay attention to the bug bug column “SpringBoot Zero-based Introduction”, from scratch, from zero to one! Hope I can help you.

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

โ˜˜๏ธ Be who you want to be, there is no time limit, you can start whenever you want,

๐Ÿ€ You can change from now on, you can also stay the same, this thing, there are no rules to speak of, you can live the most wonderful yourself.

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

โ€‹

๐Ÿ’“ If this article is helpful to you, please leave a like! (# ^. ^ #);

๐Ÿ’ if you like the article shared by bug fungus, please give bug fungus a point of concern! (เน‘ ‘แด— โ€ต เน‘);

๐Ÿ’— if you have any questions about the article, please also leave a message at the end of the article or add a group [QQ communication group :708072830];

๐Ÿ’ž In view of the limited personal experience, all views and technical research points, if you have any objection, please directly reply to participate in the discussion (do not post offensive comments, thank you);

๐Ÿ’• copyright notice: original is not easy, reprint please attach the original source link and this article statement, all rights reserved, piracy will investigate!! thank you