Java SpringBoot使用126邮箱发送html内容邮件,带附件

package mail.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    /* pom.xml中添加依赖
    *   <!--添加 mail 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
    * */

    @Autowired
    JavaMailSenderImpl javaMailSender;

    /**
     * 发送简单邮件
     */
    @Test
    public void sendMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("这是测试邮件");
        message.setText("这是正文");
        message.setTo("xxxx@qq.com");
        message.setFrom("xxxxx@126.com");
        javaMailSender.send(message);
    }

    /**
     * 发送复杂邮件 html内容或带附件
     */
    @Test
    public void sendMail2() {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setSubject("这是测试邮件");
            // 发送html格式内容
            helper.setText("<font style='color:red'>这是正文</font>",true);
            helper.setTo("xxxx@qq.com");
            helper.setFrom("xxxx@126.com");

            //添加附件
            helper.addAttachment("1.jpg",new File("c:\\1.jpg"));
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        javaMailSender.send(message);
    }


}
spring:
  mail:
    host: smtp.126.com
    password: xxxx
    username: xxxx@126.com
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

 

posted @ 2019-10-09 15:23  深南大道  阅读(2279)  评论(0编辑  收藏  举报