應(yīng)用場(chǎng)景
發(fā)送郵件驗(yàn)證碼等,定時(shí)發(fā)送、同時(shí)發(fā)送多封郵件等。
功能簡(jiǎn)介
本項(xiàng)目通過(guò)Springboot發(fā)送email郵件,包括普通文本郵件 、HTML內(nèi)容板式郵件 、包含靜態(tài)資源郵件以及帶附件郵件等。
一封郵件同時(shí)發(fā)送多人、異步多線程發(fā)送郵件、定時(shí)發(fā)送郵件等場(chǎng)景功能。
項(xiàng)目說(shuō)明
核心Maven依賴
org.springframework.boot
spring-boot-starter-mail
核心配置
如果是服務(wù)郵箱配置類似
#QQ郵箱服務(wù)主機(jī)地址
spring.mail.host=smtp.qq.com 
#郵箱賬號(hào) 
spring.mail.username=2389323369@qq.com
 #郵箱授權(quán)碼 
spring.mail.password=qtglycyclomqgci
#右鍵默認(rèn)編碼 
spring.mail.default-encoding=UTF-8
spring.mail.username=2289523269@qq.com
----需要修改成自己的郵箱賬號(hào)(發(fā)送方郵箱) #郵箱授權(quán)碼
spring.mail.password=qtglycyclomqgci
----需要修改成自己的郵箱授權(quán)碼(下面會(huì)介紹如何獲?。?/p>
QQ郵箱授權(quán)碼獲取
如果授權(quán)碼不正確會(huì)報(bào)錯(cuò)誤
org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535 Login Fail. Please enter your authorization code to login. More information in http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:439)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:322)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:311)
at com.example.demo.service.impl.MailServiceImpl.sendSimpleMail(MailServiceImpl.java:38)
1、什么是授權(quán)碼?
授權(quán)碼是QQ郵箱推出的,用于登錄第三方客戶端的專用密碼。適用于登錄以下服務(wù):POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務(wù)。溫馨提醒:為了你的帳戶安全,更改QQ密碼以及獨(dú)立密碼會(huì)觸發(fā)授權(quán)碼過(guò)期,需要重新獲取新的授權(quán)碼登錄。
2、怎么獲取授權(quán)碼?
進(jìn)入QQ郵箱主頁(yè)-->設(shè)置-->帳戶-->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務(wù):

點(diǎn)擊“開(kāi)啟”-->驗(yàn)證密保-->獲取授權(quán)碼:

核心代碼
@Service
public class MailServiceImpl implements MailService {
    /**
     * 日志
     */
  private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
  @Value("${spring.mail.username}")
    private String from;
    //用于發(fā)送文件
    @Autowired
    private JavaMailSender mailSender;
    @Override
    public void checkMail(EmailModel emailModel) {
        Assert.notNull(emailModel,"郵件模板不能為空");
        Assert.notNull(emailModel.getEmail(), "郵件收件人不能為空");
        Assert.notNull(emailModel.getSubject(), "郵件主題不能為空");
        Assert.notNull(emailModel.getContent(), "郵件內(nèi)容不能為空");
    }
    @Async("EmailAsync")
    @Override
    public Boolean sendSimpleMail(EmailModel emailModel) {
      try {
          SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);//發(fā)信人
            message.setTo(emailModel.getEmail().split(";"));//郵件收件人 1或多個(gè) 以";"隔開(kāi)
          message.setSubject(emailModel.getSubject());//主題
          message.setText(emailModel.getContent());//內(nèi)容
          mailSender.send(message);
            logger.info("發(fā)送文本郵件成功");
      } catch (Exception e) {
        e.printStackTrace();
        logger.error("發(fā)送文本郵件失敗");
        return false;
      }
      return true;
    }
    @Async("EmailAsync")
    @Override
    public Boolean sendHtmlMail(EmailModel emailModel) {
        String to = emailModel.getEmail();
        String subject = emailModel.getSubject();
        String content = emailModel.getContent();
        logger.info("發(fā)送HTML郵件開(kāi)始:{},{},{}", to, subject, content);
        //使用MimeMessage,MIME協(xié)議
        MimeMessage message = mailSender.createMimeMessage();
        
        MimeMessageHelper helper;
        //MimeMessageHelper幫助我們?cè)O(shè)置更豐富的內(nèi)容
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to.split(";"));
            helper.setSubject(subject);
            helper.setText(content, true);//true代表支持html
            mailSender.send(message);
            logger.info("發(fā)送HTML郵件成功");
        } catch (MessagingException e) {
            logger.error("發(fā)送HTML郵件失敗:", e);
            return false;
        }
        return true;
    }
    @Async("EmailAsync")
    @Override
    public Boolean sendAttachMentMail(EmailModel emailModel) {
        String to = emailModel.getEmail();
        String subject = emailModel.getSubject();
        String content = emailModel.getContent();
        String filePath = emailModel.getAttachFilePath();
        logger.info("發(fā)送附件郵件開(kāi)始:{},{},{},{}", to, subject, content, filePath);
        MimeMessage message = mailSender.createMimeMessage();
    
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            //true代表支持多組件,如附件,圖片等
            helper.setFrom(from);
            helper.setTo(to.split(";"));
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);//添加附件,可多次調(diào)用該方法添加多個(gè)附件
            mailSender.send(message);
            logger.info("發(fā)送附件郵件成功");
            } catch (MessagingException e) {
                logger.error("發(fā)送附件郵件失敗", e);
                return false;
        }
            return true;
    }
    @Async("EmailAsync")
    @Override
    public Boolean sendInlineResourceMail(EmailModel emailModel) {
        String to = emailModel.getEmail();
        String subject = emailModel.getSubject();
        String content = emailModel.getContent();
        String resourcePath = emailModel.getResourcePath();
        String resourceName = emailModel.getResourceName();
        logger.info("發(fā)送帶圖片郵件開(kāi)始:{},{},{},{},{}", to, subject, content, resourcePath, resourceName);
        MimeMessage message = mailSender.createMimeMessage();
        
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to.split(";"));
            helper.setSubject(subject);
            helper.setText(content, true);
            // 以絕對(duì)路徑的方式讀取文件
            FileSystemResource res = new FileSystemResource(new File(resourcePath));
            helper.addInline(resourceName, res);//重復(fù)使用添加多個(gè)圖片
            mailSender.send(message);
            logger.info("發(fā)送帶圖片郵件成功");
        } catch (MessagingException e) {
            logger.error("發(fā)送帶圖片郵件失敗", e);
            return false;
        }
        return true;
    }
    @Async("EmailAsync")
    @Override
    public Boolean sendHtmlImageMail(EmailModel emailModel) {
        String to = emailModel.getEmail();
        String subject = emailModel.getSubject();
        String content = emailModel.getContent();
        String resourcePath = emailModel.getResourcePath();
        logger.info("發(fā)送帶圖片郵件開(kāi)始:{},{},{},{}", to, subject, content, resourcePath);
        MimeMessage message = mailSender.createMimeMessage();
    
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to.split(";"));
            helper.setSubject(subject);
            helper.setText(content, true);
            // cid是固定寫法
            helper.setText(
                "
	hello world!
" + "", true); FileSystemResource img = new FileSystemResource(new File(resourcePath)); helper.addInline("aaa", img); mailSender.send(message); logger.info("發(fā)送帶圖片郵件成功"); return true; } catch (MessagingException e) { logger.error("發(fā)送帶圖片郵件失敗", e); return false; } } }
源碼下載地址獲取
關(guān)注微信公眾號(hào)“Java爛筆頭”,回復(fù)“郵件”
- 
                                郵件
                                +關(guān)注關(guān)注 0文章 32瀏覽量 19063
- 
                                HTML
                                +關(guān)注關(guān)注 0文章 280瀏覽量 45477
- 
                                spring
                                +關(guān)注關(guān)注 0文章 341瀏覽量 15682
- 
                                SpringBoot
                                +關(guān)注關(guān)注 0文章 175瀏覽量 588
發(fā)布評(píng)論請(qǐng)先 登錄
在Java中如何使用API來(lái)完成郵件的接收與發(fā)送
 
    
LV發(fā)送郵件
[ARM linux平臺(tái)] 如何實(shí)現(xiàn)發(fā)送郵件功能?
用SpringMVC發(fā)送郵件
采用BCB實(shí)現(xiàn)具有身份認(rèn)證功能的郵件發(fā)送l程序
C#教程之調(diào)用Outlook發(fā)送郵件
C#教程之調(diào)用SMTP發(fā)送有附件的郵件
如何向您選擇的某人發(fā)送電子郵件
 
    
怎么用Python構(gòu)建一個(gè)自動(dòng)發(fā)送郵件的腳本
 
    
怎么用Python構(gòu)建一個(gè)自動(dòng)發(fā)送郵件的腳本
 
    
 
           
        
 
         基于SpringBoot實(shí)現(xiàn)郵件發(fā)送
基于SpringBoot實(shí)現(xiàn)郵件發(fā)送 
                 
  
     
            
             
             
                 
             工商網(wǎng)監(jiān)
工商網(wǎng)監(jiān)
        
評(píng)論