springboot send mail (3): send mail with attachments

Springboot realizes the mail function: send html format mail:

1. Build a springboot project, import dependencies; application.properties configuration file, see

springboot send mail (1): send simple mail

2. Write the service interface and implement the class:

/**
 * Mail service interface
 * Created by ASUS on 5/5/2018
 *
 * @Authod Grey Wolf
 */
 public interface MailService {

   
    /**
      * Send mail with attachments
      * @param to
 * @param subject
 * @param content
 * @param filePath
 */
 void sendAttachmentsMail (String to , String subject , String content , String filePath) ;
 }
                        
/**
 *
 * 邮件服务类
 * Created by ASUS on 2018/5/5
 *
 * @Authod Grey Wolf
 */
@Service("mailService")
public class MailServiceImpl implements MailService {


    @Autowired
private JavaMailSender mailSender;    

    /**
      * Send mail with attachments
      * @param to recipient
      * @param subject subject
      * @param content content
      * @param filePath file path
      */
 @Override
 public void sendAttachmentsMail (String to , String subject , String content , String filePath ) {        
        MimeMessage message=mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper=new MimeMessageHelper(message,true);
            helper.setFrom(form);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content);
            FileSystemResource file=new FileSystemResource(new File(filePath));
            String fileName=filePath.substring(filePath.lastIndexOf(File.separator));
      //Adding multiple attachments can use multiple
      //helper.addAttachment(fileName,file);
     helper.addAttachment(fileName , file) ;
 mailSender .send (message) ;
 System.out .println ( "The email with attachment was sent successfully" ) ;
 } catch (Exception e){                                
            e.printStackTrace() ;
 System.out             .println ( "Failed to send email with attachment" ) ;
 }        
    }


}

3. Write the test class MailTest:

/**
 * Send mail test class
 * Created by ASUS on 5/5/2018
 *
 * @Authod Grey Wolf
 */
 @RunWith (SpringRunner. class )
 @SpringBootTest
 public class MailTest {

    @Autowired
    private MailService mailService;

    @Value("${mail.fromMail.addr}")
    private String form;

    @Test
    public  void sendAttachmentsMail(){
        String filePath="C:\\Users\\ASUS\\Pictures\\SharedImageServer\\contentpic\\2.jpg";
        mailService.sendAttachmentsMail(form,"带附件的邮件","有附件,请查收",filePath);
    }

}

4.看测试结果:


我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325725527&siteId=291194637