1. 程式人生 > 其它 >Springboot實現郵件傳送

Springboot實現郵件傳送

技術標籤:spring bootjavajavamail

  1. 匯入mail座標
       <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</
    groupId
    >
    <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </
    dependency
    >
    </dependencies>
  2. 配置檔案配置
    [email protected]
    spring.mail.password=scetlwtrewchdege  #授權碼:在qq郵箱 設定->賬戶:開啟POP3/SMTP服務獲得
    spring.mail.host=smtp.qq.com
    #qq郵箱需要下面配置,其它不用
    spring.mail.properties.mail.smtp.ssl.enable=true
    
    
  3. 在測試類進行測試
    • 傳送簡單郵件
      @Autowired //詳情檢視 MailSenderAutoConfiguration
      JavaMailSenderImpl mailSender;
      @Test void contextLoads() { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setSubject("這是主題"); //設定主題 mailMessage.setText("這是內容"); //設定內容 mailMessage.setTo("[email protected]"); //設定傳送地址 mailMessage.setFrom("[email protected]"); //設定傳送賬戶(配置檔案中配置的) mailSender.send(mailMessage); //傳送郵件 }
    1. 傳送標準郵件(附件等)
      @Test
      void contextLoads2() throws MessagingException {
          //傳送複雜郵件
          MimeMessage mimeMessage = mailSender.createMimeMessage();
          MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
          
          helper.setText("<p style='color:red'>這是第二封郵件了</p>",true);
          helper.setSubject("第二封郵件的主題");
          helper.addAttachment("sss.jpg",new File("F:\\桌面\\sss.jpg"));
          helper.setTo("[email protected]");
          helper.setFrom("[email protected]");
          mailSender.send(mimeMessage);
      }
      
    2. 可以封裝方法,模擬真實環境,這裡就進行簡單的幾個封裝
      	/**
           *  自定義的方法,其它內容省略了先,太麻煩了
           * @param title:郵件主題
           * @param text :郵件內容(支援html)
           * @param encoding:編碼格式
           * @param flag : 是否存在上傳檔案
           * 
           * @throws MessagingException
           */
      public void sendMail(String title, String text, String encoding, Boolean flag, Map<String,File> files) throws MessagingException {
          //傳送複雜郵件
          MimeMessage mimeMessage = mailSender.createMimeMessage();
      
          MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,flag,encoding);
          helper.setText(text,true); //內容
          helper.setSubject(title); //主題
          if (flag)
              for (String s : files.keySet()) {
                  File file = files.get(s);
                  helper.addAttachment(s,file);
              }
          helper.setTo("[email protected]");
          helper.setFrom("[email protected]");
          mailSender.send(mimeMessage);
      }